Compare commits

..

12 Commits

Author SHA1 Message Date
Simon Sessingø 5197ae2990 Merge pull request #323 from skipperbent/v3-development
Version 3.4.6.2
2017-11-26 23:44:06 +01:00
Simon Sessingø 9c701aabee Merge pull request #321 from skipperbent/v3-development
Fixed url parsing issues
2017-11-26 18:45:54 +01:00
Simon Sessingø 2b0821a557 Merge pull request #320 from skipperbent/v3-development
Fixed typo
2017-11-26 18:29:36 +01:00
Simon Sessingø afc81d7005 Merge pull request #318 from skipperbent/v3-development
Version 3.4.6.0
2017-11-26 18:08:24 +01:00
Simon Sessingø 496d3e7182 Merge pull request #315 from skipperbent/v3-development
Version 3.4.5.5
2017-11-25 01:34:53 +01:00
Simon Sessingø 1fd13ed2aa Merge pull request #311 from skipperbent/v3-development
V3 development
2017-11-10 13:02:49 +01:00
Simon Sessingø 9d5c4a2ed1 Merge pull request #308 from skipperbent/v3-development
3.4.5.4
2017-11-10 08:24:55 +01:00
Simon Sessingø b8634bcf79 Merge pull request #307 from skipperbent/revert-306-revert-305-v3-development
Revert "Revert "V3 development""
2017-11-08 04:11:50 +01:00
Simon Sessingø 6ad22a3816 Revert "Revert "V3 development"" 2017-11-08 04:11:40 +01:00
Simon Sessingø ed41cd55af Merge pull request #306 from skipperbent/revert-305-v3-development
Revert "V3 development"
2017-11-08 04:09:55 +01:00
Simon Sessingø ebeca952cf Revert "V3 development" 2017-11-08 04:09:41 +01:00
Simon Sessingø 0672e85fd7 Merge pull request #305 from skipperbent/v3-development
V3 development
2017-11-08 04:09:31 +01:00
66 changed files with 1074 additions and 2045 deletions
-22
View File
@@ -1,22 +0,0 @@
engines:
phpmd:
enabled: true
checks:
Design/TooManyPublicMethods:
enabled: true
Naming/ShortVariable:
enabled: true
CleanCode/StaticAccess:
enabled: true
Controversial/CamelCaseMethodName:
enabled: true
fixme:
enabled: true
duplication:
enabled: true
config:
languages:
- php:
ratings:
paths:
- src/**
-13
View File
@@ -1,13 +0,0 @@
build:
tests:
override:
-
command: './vendor/bin/phpunit --coverage-clover=coverage.clover'
coverage:
file: 'coverage.clover'
format: 'clover'
checks:
php:
code_rating: true
duplication: true
-13
View File
@@ -1,13 +0,0 @@
sudo: false
language: php
php:
- 7.1
before_script:
- curl -sS http://getcomposer.org/installer | php
- php composer.phar install --prefer-source --no-interaction
script:
- ./vendor/bin/phpunit
+162 -439
View File
@@ -1,18 +1,45 @@
# Simple PHP router
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expandability in mind.
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.
**Note: this documentation is currently work-in-progress. Feel free to contribute.**
**Please note that this documentation is currently work-in-progress. Feel free to contribute.**
### Notes
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
### Feedback and development
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.
###### Issues guidelines
- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.
- We love to hear out any ideas or feedback to the library.
[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)
###### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
---
## Table of Contents
- [Getting started](#getting-started)
- [Notes](#notes-1)
- [Requirements](#requirements)
- [Feedback and development](#feedback-and-development)
- [Contribution development guidelines](#contribution-development-guidelines)
- [Notes](#notes-1)
- [Features](#features)
- [Installation](#installation)
- [Setting up Apache](#setting-up-apache)
@@ -20,14 +47,7 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Setting up IIS](#setting-up-iis)
- [Configuration](#configuration)
- [Helper functions](#helper-functions)
- [Help and support](#help-and-support)
- [How to debug](#how-to-debug)
- [Creating unit-tests](#creating-unit-tests)
- [Debug information](#debug-information)
- [Benchmark and log-info](#benchmark-and-log-info)
- [Reporting a new issue](#reporting-a-new-issue)
- [Procedure for reporting a new issue](#procedure-for-reporting-a-new-issue)
- [Issue template](#issue-template)
- [Routes](#routes)
- [Basic routing](#basic-routing)
- [Available methods](#available-methods)
@@ -79,7 +99,8 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Advanced](#advanced)
- [Url rewriting](#url-rewriting)
- [Changing current route](#changing-current-route)
- [Rewrite using callback](#rewrite-using-callback)
- [Rewrite using url](#rewrite-using-url)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually)
- [Parameters](#parameters)
@@ -98,9 +119,11 @@ Add the latest version of Simple PHP Router running this command.
composer require pecee/simple-router
```
## Notes
## Requirements
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
- PHP 5.5 or greater
## Notes
We've included a simple demo project for the router which can be found in the `demo-project` folder. This project should give you a basic understanding of how to setup and use simple-php-router project.
@@ -120,32 +143,6 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
- How to get ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers.
## Requirements
- PHP 5.5 or greater
### Feedback and development
If the library is missing a feature that you need in your project or if you have feedback, we'd love to hear from you.
Feel free to leave us feedback by [creating a new issue](https://github.com/skipperbent/simple-php-router/issues/new).
**Experiencing an issue?**
Please refer to our [Help and support](#help-and-support) section in the documentation before reporting a new issue.
##### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
## Features
- Basic routing (`GET`, `POST`, `PUT`, `PATCH`, `UPDATE`, `DELETE`) with support for custom multiple verbs.
@@ -210,7 +207,7 @@ Below is an example of an working `web.config` file used by simple-php-router.
Simply create a new `web.config` file in your projects `public` directory and paste the contents below in your newly created file. This will redirect all requests to your `index.php` file (see Configuration section below). If the `web.config` file already exists, add the `<rewrite>` section inside the `<system.webServer>` branch.
```xml
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
@@ -312,8 +309,6 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters
* @param array|null $getParams
* @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function url($name = null, $parameters = null, $getParams = null)
{
@@ -322,7 +317,6 @@ function url($name = null, $parameters = null, $getParams = null)
/**
* @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function response()
{
@@ -331,7 +325,6 @@ function response()
/**
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function request()
{
@@ -343,16 +336,15 @@ function request()
* @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method
* @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @return \Pecee\Http\Input\Input|string
*/
function input($index = null, $defaultValue = null, $methods = null)
{
if ($index !== null) {
return request()->getInputHandler()->get($index, $defaultValue, $methods);
return request()->getInput()->get($index, $defaultValue, $methods);
}
return request()->getInputHandler();
return request()->getInput();
}
function redirect($url, $code = null)
@@ -367,13 +359,12 @@ function redirect($url, $code = null)
/**
* Get current csrf-token
* @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function csrf_token()
{
$baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) {
return $baseVerifier->getTokenProvider()->getToken();
return $baseVerifier->getToken();
}
return null;
@@ -382,379 +373,6 @@ function csrf_token()
---
# Help and support
This section will go into details on how to debug the router and answer some of the commonly asked questions- and issues.
## How to debug
This section will show you how to write unit-tests for the router, view useful debugging information and answer some of the frequently asked questions.
It will also covers how to report any issue you might encounter.
### Creating unit-tests
The easiest and fastest way to debug any issues with the router, is to create a unit-test that represents the issue you are experiencing.
Unit-tests use a special `TestRouter` class, which simulates a request-method and requested url of a browser.
The `TestRouter` class can return the output directly or render a route silently.
```php
public function testUnicodeCharacters()
{
// Add route containing two optional paramters with special spanish characters like "í".
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
// Start the routing and simulate the url "/cursos/listado/especialidad/cirugía local".
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'GET');
// Verify that the url for the loaded route matches the expected route.
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
// Start the routing and simulate the url "/test/Dermatología" using "GET" as request-method.
TestRouter::debugNoReset('/test/Dermatología', 'GET');
// Another route containing one parameter with special spanish characters like "í".
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
// Get all parameters parsed by the loaded route.
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
// Check that the parameter named "param" matches the exspected value.
$this->assertEquals('Dermatología', $parameters['param']);
// Add route testing danish special characters like "ø".
TestRouter::get('/category/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
// Start the routing and simulate the url "/kategory/økse" using "GET" as request-method.
TestRouter::debugNoReset('/category/økse', 'GET');
// Validate that the URL of the loaded-route matches the expected url.
$this->assertEquals('/category/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
// Reset the router, so other tests wont inherit settings or the routes we've added.
TestRouter::router()->reset();
}
```
#### Using the TestRouter helper
Depending on your test, you can use the methods below when rendering routes in your unit-tests.
| Method | Description |
| ------------- |-------------|
| ```TestRouter::debug($url, $method)``` | Will render the route without returning anything. Exceptions will be thrown and the router will be reset automatically. |
| ```TestRouter::debugOutput($url, $method)``` | Will render the route and return any value that the route might output. Manual reset required by calling `TestRouter::router()->reset()`. |
| ```TestRouter::debugNoReset($url, $method);``` | Will render the route without resetting the router. Useful if you need to get loaded route, parameters etc. from the router. Manual reset required by calling `TestRouter::router()->reset()`. |
### Debug information
The library can output debug-information, which contains information like loaded routes, the parsed request-url etc. It also contains info which are important when reporting a new issue like PHP-version, library version, server-variables, router debug log etc.
You can activate the debug-information by calling the alternative start-method.
The example below will start the routing an return array with debugging-information
**Example:**
```php
$debugInfo = SimpleRouter::startDebug();
echo sprintf('<pre>%s</pre>', var_export($debugInfo));
exit;
```
**The example above will provide you with an output containing:**
| Key | Description |
| ------------- |------------- |
| `url` | The parsed request-uri. This url should match the url in the browser.|
| `method` | The browsers request method (example: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` etc).|
| `host` | The website host (example: `domain.com`).|
| `loaded_routes` | List of all the routes that matched the `url` and that has been rendered/loaded. |
| `all_routes` | All available routes |
| `boot_managers` | All available BootManagers |
| `csrf_verifier` | CsrfVerifier class |
| `log` | List of debug messages/log from the router. |
| `router_output` | The rendered callback output from the router. |
| `library_version` | The version of simple-php-router you are using. |
| `php_version` | The version of PHP you are using. |
| `server_params` | List of all `$_SERVER` variables/headers. |
#### Benchmark and logging
You can activate benchmark debugging/logging by calling `setDebugEnabled` method on the `Router` instance.
You have to enable debugging BEFORE starting the routing.
**Example:**
```php
SimpleRouter::router()->setDebugEnabled(true);
SimpleRouter::start();
```
When the routing is complete, you can get the debug-log by calling the `getDebugLog()` on the `Router` instance. This will return an `array` of log-messages each containing execution time, trace info and debug-message.
**Example:**
```php
$messages = SimpleRouter::router()->getDebugLog();
```
## Reporting a new issue
**Before reporting your issue, make sure that the issue you are experiencing aren't already answered in the [Common errors](#common-errors) section or by searching the [closed issues](https://github.com/skipperbent/simple-php-router/issues?q=is%3Aissue+is%3Aclosed) page on GitHub.**
To avoid confusion and to help you resolve your issue as quickly as possible, you should provide a detailed explanation of the problem you are experiencing.
### Procedure for reporting a new issue
1. Go to [this page](https://github.com/skipperbent/simple-php-router/issues/new) to create a new issue.
2. Add a title that describes your problems in as few words as possible.
3. Copy and paste the template below in the description of your issue and replace each step with your own information. If the step is not relevant for your issue you can delete it.
### Issue template
Copy and paste the template below into the description of your new issue and replace it with your own information.
You can check the [Debug information](#debug-information) section to see how to generate the debug-info.
<pre>
### Description
The library fails to render the route `/user/æsel` which contains one parameter using a custom regular expression for matching special foreign characters. Routes without special characters like `/user/tom` renders correctly.
### Steps to reproduce the error
1. Add the following route:
```php
SimpleRouter::get('/user/{name}', 'UserController@show')->where(['name' => '[\w]+']);
```
2. Navigate to `/user/æsel` in browser.
3. `NotFoundHttpException` is thrown by library.
### Route and/or callback for failing route
*Route:*
```php
SimpleRouter::get('/user/{name}', 'UserController@show')->where(['name' => '[\w]+']);
```
*Callback:*
```php
public function show($username) {
return sprintf('Username is: %s', $username);
}
```
### Debug info
```php
array (
'url' =>
Pecee\Http\Url::__set_state(array(
'originalUrl' => NULL,
'data' =>
array (
'scheme' => NULL,
'host' => NULL,
'port' => NULL,
'user' => NULL,
'pass' => NULL,
'path' => NULL,
'query' => NULL,
'fragment' => NULL,
),
)),
'method' => '',
'host' => NULL,
'loaded_routes' =>
array (
),
'all_routes' =>
array (
0 =>
Pecee\SimpleRouter\Route\RouteUrl::__set_state(array(
'url' => '/user/{name}/',
'name' => NULL,
'regex' => NULL,
'filterEmptyParams' => true,
'defaultParameterRegex' => NULL,
'paramModifiers' => '{}',
'paramOptionalSymbol' => '?',
'urlRegex' => '/^%s\\/?$/u',
'group' => NULL,
'parent' => NULL,
'callback' => 'UserController@show',
'defaultNamespace' => NULL,
'namespace' => NULL,
'requestMethods' =>
array (
0 => 'get',
),
'where' =>
array (
'name' => '[\\w]+',
),
'parameters' =>
array (
'name' => NULL,
),
'originalParameters' =>
array (
),
'middlewares' =>
array (
),
)),
),
'boot_managers' =>
array (
),
'csrf_verifier' => NULL,
'log' =>
array (
0 =>
array (
'message' => 'Started routing request (rewrite: no)',
'time' => '0.0000069141',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\SimpleRouter.php',
'line' => 57,
'function' => 'routeRequest',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
1 =>
array (
'message' => 'Loading routes',
'time' => '0.0036418438',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 273,
'function' => 'loadRoutes',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
2 =>
array (
'message' => 'Processing routes',
'time' => '0.0069010258',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 251,
'function' => 'processRoutes',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
3 =>
array (
'message' => 'Processing route "Pecee\\SimpleRouter\\Route\\RouteUrl"',
'time' => '0.0099139214',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 251,
'function' => 'processRoutes',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
4 =>
array (
'message' => 'Finished loading routes',
'time' => '0.0130679607',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 273,
'function' => 'loadRoutes',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
5 =>
array (
'message' => 'Matching route "Pecee\\SimpleRouter\\Route\\RouteUrl"',
'time' => '0.0160858631',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\SimpleRouter.php',
'line' => 57,
'function' => 'routeRequest',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
6 =>
array (
'message' => 'Route not found: "/"',
'time' => '0.0193598270',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\SimpleRouter.php',
'line' => 57,
'function' => 'routeRequest',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
7 =>
array (
'message' => 'Starting exception handling for "Pecee\\SimpleRouter\\Exceptions\\NotFoundHttpException"',
'time' => '0.0229449272',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 345,
'function' => 'handleException',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
8 =>
array (
'message' => 'Finished exception handling - exception not handled, throwing',
'time' => '0.0258929729',
'trace' =>
array (
'file' => 'E:\\Workspace\\simple-php-router\\src\\Pecee\\SimpleRouter\\Router.php',
'line' => 345,
'function' => 'handleException',
'class' => 'Pecee\\SimpleRouter\\Router',
'type' => '->',
),
),
),
'router_output' => NULL,
'library_version' => false,
'php_version' => '7.2.0',
'server_params' =>
array (),
)
```
</pre>
Remember that a more detailed issue- description and debug-info might suck to write, but it will help others understand- and resolve your issue without asking for the information.
**Note:** please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue. Providing the necessary steps to reproduce the error within your description, adding useful debugging info etc. will help others quickly resolve the issue you are reporting.
---
# Routes
Remember the ```routes.php``` file you required in your ```index.php```? This file be where you place all your custom rules for routing.
@@ -980,9 +598,9 @@ SimpleRouter::group(['namespace' => 'Admin'], function () {
});
```
### Subdomain-routing
### Sub domain-routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route urls, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
```php
SimpleRouter::group(['domain' => '{account}.myapp.com'], function () {
@@ -994,7 +612,7 @@ SimpleRouter::group(['domain' => '{account}.myapp.com'], function () {
### Route prefixes
The `prefix` group attribute may be used to prefix each route in the group with a given url. For example, you may want to prefix all route urls within the group with `admin`:
The `prefix` group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with `admin`:
```php
SimpleRouter::group(['prefix' => '/admin'], function () {
@@ -1276,7 +894,7 @@ class CustomExceptionHandler implements IExceptionHandler
/* You can use the exception handler to format errors depending on the request and type. */
if (stripos($request->getUrl()->getPath(), '/api') !== false) {
if (stripos($request->getUri()->getPath(), '/api') !== false) {
response()->json([
'error' => $error->getMessage(),
@@ -1517,22 +1135,126 @@ $siteId = input('site_id', 2, ['post', 'get']);
# Advanced
## Url rewriting
### Changing current route
Sometimes it can be useful to manipulate the route about to be loaded.
simple-php-router allows you to easily manipulate and change the routes which are about to be rendered.
simple-php-router allows you to easily change the route about to be executed.
All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property.
For easy access you can use the shortcut helper function `request()` instead of calling the class directly `\Pecee\SimpleRouter\SimpleRouter::router()`.
For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::router()`.
```php
request()->setRewriteCallback('Example\MyCustomClass@hello');
use Pecee\SimpleRouter;
$request = SimpleRouter::request();
$request->setRewriteCallback('Example\MyCustomClass@hello');
// -- or you can rewrite by url --
request()->setRewriteUrl('/my-rewrite-url');
$request->setRewriteUrl('/my-rewrite-url');
```
**Note:** It's only possible to change the route BEFORE the route has initially been rendered. You can use the `Request` object to manipulate the route which are about to be loaded.
### Rewrite using callback
This method is most efficient, as it will render the route immediately.
This method is useful for rendering 404-pages etc.
You can also change the callback by modifying the `$route` parameter. This is perfect if you just want to display a view quickly - or change the callback depending
on some criteria's for the request.
The callback below will fire immediately after the `Middleware` or `ExceptionHandler` has been loaded, as they are loaded before the route is rendered.
If you wish to change the callback from outside, please have this in mind.
The example below will render `DefaultController@notFound` regardless of the url.
**NOTE: Use this method if you want to load another controller. No additional middlewares or rules will be loaded.**
##### Middleware example
```php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class CustomMiddleware implements IMiddleware {
public function handle(Request $request) {
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
return $request;
}
}
```
##### Exception handler example
```php
namespace Demo\Handlers;
use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class CustomExceptionHandler implements IExceptionHandler
{
public function handleError(Request $request, \Exception $error)
{
/* The router will throw the NotFoundHttpException on 404 */
if($error instanceof NotFoundHttpException) {
/*
* Render your own custom 404-view, rewrite the request to another route,
* or simply return the $request object to ignore the error and continue on rendering the route.
*
* The code below will make the router render our page.notfound route.
*/
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
return $request;
}
throw $error;
}
}
```
### Rewrite using url
The example below will cause the router to reload the request and reinitialize all the routes. This method is slower, but will ensure that all middlewares and rules for the route is loaded.
This method is useful if you want to redirect a url to another-url which is dependent on a middleware. You can also add a custom rule by calling `$request->setRewriteRoute($route)` if
you want to customize request-methods or use another route-type like `RouteController` etc.
We are using the `url()` helper function to get the uri to another route added in the `routes.php` file.
**NOTE: Use this method if you want to fully load another route using it's settings (request method, middlewares etc).**
##### Middleware example
The example below will redirect the request to the `home`-route.
```php
namespace Demo\Middlewares;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class CustomMiddleware implements IMiddleware {
public function handle(Request $request) {
$request->setRewriteUrl(url('home'));
return $request;
}
}
```
### Bootmanager: loading routes dynamically
@@ -1556,10 +1278,11 @@ class CustomRouterRules implement IRouterBootManager {
foreach($rewriteRules as $url => $rule) {
// If the current url matches the rewrite url, we use our custom route
// If the current uri matches the url, we use our custom route
if($request->getUrl()->getPath() === $url) {
if($request->getUri()->getPath() === $url) {
$request->setRewriteUrl($rule);
return $request;
}
}
+3 -9
View File
@@ -9,12 +9,7 @@
"simple-php-router",
"laravel",
"pecee",
"php",
"framework",
"url-handling",
"input-handler",
"routing-engine",
"request-handler"
"php"
],
"license": "MIT",
"support": {
@@ -27,11 +22,10 @@
}
],
"require": {
"php": ">=7.1"
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0",
"mockery/mockery": "^1"
"phpunit/phpunit": "4.7.7"
},
"autoload": {
"psr-4": {
+3 -9
View File
@@ -18,8 +18,6 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters
* @param array|null $getParams
* @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function url($name = null, $parameters = null, $getParams = null)
{
@@ -28,7 +26,6 @@ function url($name = null, $parameters = null, $getParams = null)
/**
* @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function response()
{
@@ -37,7 +34,6 @@ function response()
/**
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function request()
{
@@ -49,16 +45,15 @@ function request()
* @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method
* @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @return \Pecee\Http\Input\Input|string
*/
function input($index = null, $defaultValue = null, $methods = null)
{
if ($index !== null) {
return request()->getInputHandler()->get($index, $defaultValue, $methods);
return request()->getInput()->get($index, $defaultValue, $methods);
}
return request()->getInputHandler();
return request()->getInput();
}
function redirect($url, $code = null)
@@ -73,7 +68,6 @@ function redirect($url, $code = null)
/**
* Get current csrf-token
* @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function csrf_token()
{
-24
View File
@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
bootstrap="tests/bootstrap.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false">
<testsuites>
<testsuite name="SimpleRouter Test Suite">
<directory>tests/Pecee/SimpleRouter/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
+14 -15
View File
@@ -1,48 +1,47 @@
<?php
namespace Pecee\Controllers;
interface IResourceController
{
/**
* @return string|null
* @return void
*/
public function index(): ?string;
public function index();
/**
* @param mixed $id
* @return string|null
* @return void
*/
public function show($id): ?string;
public function show($id);
/**
* @return string|null
* @return void
*/
public function store(): ?string;
public function store();
/**
* @return string|null
* @return void
*/
public function create(): ?string;
public function create();
/**
* View
* @param mixed $id
* @return string|null
* @return void
*/
public function edit($id): ?string;
public function edit($id);
/**
* @param mixed $id
* @return string|null
* @return void
*/
public function update($id): ?string;
public function update($id);
/**
* @param mixed $id
* @return string|null
* @return void
*/
public function destroy($id): ?string;
public function destroy($id);
}
@@ -1,8 +0,0 @@
<?php
namespace Pecee\Exceptions;
class InvalidArgumentException extends \InvalidArgumentException
{
}
@@ -25,11 +25,12 @@ class CallbackExceptionHandler implements IExceptionHandler
/**
* @param Request $request
* @param \Exception $error
* @return Request|null
*/
public function handleError(Request $request, \Exception $error): void
public function handleError(Request $request, \Exception $error)
{
/* Fire exceptions */
\call_user_func($this->callback,
return call_user_func($this->callback,
$request,
$error
);
+2 -2
View File
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Handlers;
use Pecee\Http\Request;
@@ -9,7 +8,8 @@ interface IExceptionHandler
/**
* @param Request $request
* @param \Exception $error
* @return Request|null
*/
public function handleError(Request $request, \Exception $error): void;
public function handleError(Request $request, \Exception $error);
}
@@ -1,8 +0,0 @@
<?php
namespace Pecee\Http\Exceptions;
class MalformedUrlException extends \Exception
{
}
+5 -8
View File
@@ -1,21 +1,18 @@
<?php
namespace Pecee\Http\Input;
interface IInputItem
{
public function getIndex(): string;
public function getIndex();
public function setIndex(string $index): self;
public function setIndex($index);
public function getName(): string;
public function getName();
public function setName(string $name): self;
public function setName($name);
public function getValue(): string;
public function setValue(string $value): self;
public function getValue();
public function __toString();
@@ -2,10 +2,9 @@
namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request;
class InputHandler
class Input
{
/**
* @var array
@@ -27,10 +26,6 @@ class InputHandler
*/
protected $request;
/**
* Input constructor.
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
@@ -38,51 +33,40 @@ class InputHandler
$this->parseInputs();
}
/**
* Parse input values
*
*/
public function parseInputs(): void
public function parseInputs()
{
/* Parse get requests */
if (\count($_GET) !== 0) {
if (count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET);
}
/* Parse post requests */
$postVars = $_POST;
if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
if (\count($postVars) !== 0) {
if (count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars);
}
/* Parse get requests */
if (\count($_FILES) !== 0) {
if (count($_FILES) !== 0) {
$this->file = $this->parseFiles();
}
}
/**
* @return array
*/
public function parseFiles(): array
public function parseFiles()
{
$list = [];
foreach ((array)$_FILES as $key => $value) {
// Handle array input
if (\is_array($value['name']) === false) {
if (is_array($value['name']) === false) {
$values['index'] = $key;
try {
$list[$key] = InputFile::createFromArray($values + $value);
} catch (InvalidArgumentException $e) {
}
$list[$key] = InputFile::createFromArray($values + $value);
continue;
}
@@ -101,7 +85,7 @@ class InputHandler
return $list;
}
protected function rearrangeFiles(array $values, &$index, $original): array
protected function rearrangeFiles(array $values, &$index, $original)
{
$originalIndex = $index[0];
@@ -111,30 +95,24 @@ class InputHandler
foreach ($values as $key => $value) {
if (\is_array($original['name'][$key]) === false) {
if (is_array($original['name'][$key]) === false) {
try {
$file = InputFile::createFromArray([
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'tmp_name' => $original['tmp_name'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
]);
$file = InputFile::createFromArray([
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
'name' => $original['name'][$key],
'error' => $original['error'][$key],
'tmp_name' => $original['tmp_name'][$key],
'type' => $original['type'][$key],
'size' => $original['size'][$key],
]);
if (isset($output[$key]) === true) {
$output[$key][] = $file;
continue;
}
$output[$key] = $file;
if (isset($output[$key]) === true) {
$output[$key][] = $file;
continue;
} catch (InvalidArgumentException $e) {
}
$output[$key] = $file;
continue;
}
$index[] = $key;
@@ -152,14 +130,14 @@ class InputHandler
return $output;
}
protected function handleGetPost(array $array): array
protected function handleGetPost(array $array)
{
$list = [];
foreach ($array as $key => $value) {
// Handle array input
if (\is_array($value) === false) {
if (is_array($value) === false) {
$list[$key] = new InputItem($key, $value);
continue;
}
@@ -179,9 +157,9 @@ class InputHandler
* @param string|null $defaultValue
* @return InputItem|string
*/
public function findPost(string $index, ?string $defaultValue = null)
public function findPost($index, $defaultValue = null)
{
return $this->post[$index] ?? $defaultValue;
return isset($this->post[$index]) ? $this->post[$index] : $defaultValue;
}
/**
@@ -191,9 +169,9 @@ class InputHandler
* @param string|null $defaultValue
* @return InputFile|string
*/
public function findFile(string $index, ?string $defaultValue = null)
public function findFile($index, $defaultValue = null)
{
return $this->file[$index] ?? $defaultValue;
return isset($this->file[$index]) ? $this->file[$index] : $defaultValue;
}
/**
@@ -203,9 +181,9 @@ class InputHandler
* @param string|null $defaultValue
* @return InputItem|string
*/
public function findGet(string $index, ?string $defaultValue = null)
public function findGet($index, $defaultValue = null)
{
return $this->get[$index] ?? $defaultValue;
return isset($this->get[$index]) ? $this->get[$index] : $defaultValue;
}
/**
@@ -216,27 +194,27 @@ class InputHandler
* @param array|string|null $methods
* @return IInputItem|string
*/
public function getObject(string $index, ?string $defaultValue = null, $methods = null)
public function getObject($index, $defaultValue = null, $methods = null)
{
if ($methods !== null && \is_string($methods) === true) {
if ($methods !== null && is_string($methods) === true) {
$methods = [$methods];
}
$element = null;
if ($methods === null || \in_array('get', $methods, true) === true) {
if ($methods === null || in_array('get', $methods, false) === true) {
$element = $this->findGet($index);
}
if (($element === null && $methods === null) || ($methods !== null && \in_array('post', $methods, true) === true)) {
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) {
$element = $this->findPost($index);
}
if (($element === null && $methods === null) || ($methods !== null && \in_array('file', $methods, true) === true)) {
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) {
$element = $this->findFile($index);
}
return $element ?? $defaultValue;
return ($element !== null) ? $element : $defaultValue;
}
/**
@@ -247,7 +225,7 @@ class InputHandler
* @param array|string|null $methods
* @return InputItem|string
*/
public function get(string $index, ?string $defaultValue = null, $methods = null)
public function get($index, $defaultValue = null, $methods = null)
{
$input = $this->getObject($index, $defaultValue, $methods);
@@ -264,7 +242,7 @@ class InputHandler
* @param string $index
* @return bool
*/
public function exists(string $index): bool
public function exists($index)
{
return ($this->getObject($index) !== null);
}
@@ -274,23 +252,23 @@ class InputHandler
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null): array
public function all(array $filter = null)
{
$output = $_GET + $_POST;
$output = $_POST;
if ($this->request->getMethod() === 'post') {
$contents = file_get_contents('php://input');
if (strpos(trim($contents), '{') === 0) {
$post = json_decode($contents, true);
if ($post !== false) {
$output += $post;
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : $output;
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : array_merge($_GET, $output);
}
}
+41 -56
View File
@@ -1,9 +1,6 @@
<?php
namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
class InputFile implements IInputItem
{
public $index;
@@ -11,15 +8,13 @@ class InputFile implements IInputItem
public $filename;
public $size;
public $type;
public $errors;
public $error;
public $tmpName;
public function __construct(string $index)
public function __construct($index)
{
$this->index = $index;
$this->errors = 0;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
}
@@ -28,38 +23,39 @@ class InputFile implements IInputItem
* Create from array
*
* @param array $values
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
* @return static
*/
public static function createFromArray(array $values): self
public static function createFromArray(array $values)
{
if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required');
throw new \InvalidArgumentException('Index key is required');
}
/* Easy way of ensuring that all indexes-are set and not filling the screen with isset() */
$values += [
$values = array_merge([
'tmp_name' => null,
'type' => null,
'size' => null,
'name' => null,
'filename' => null,
'error' => null,
];
], $values);
return (new static($values['index']))
->setSize((int)$values['size'])
->setSize($values['size'])
->setError($values['error'])
->setType($values['type'])
->setTmpName($values['tmp_name'])
->setFilename($values['name']);
->setFilename($values['filename']);
}
/**
* @return string
*/
public function getIndex(): string
public function getIndex()
{
return $this->index;
}
@@ -67,9 +63,9 @@ class InputFile implements IInputItem
/**
* Set input index
* @param string $index
* @return static
* @return static $this
*/
public function setIndex(string $index): IInputItem
public function setIndex($index)
{
$this->index = $index;
@@ -79,7 +75,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getSize(): string
public function getSize()
{
return $this->size;
}
@@ -87,9 +83,9 @@ class InputFile implements IInputItem
/**
* Set file size
* @param int $size
* @return static
* @return static $this
*/
public function setSize(int $size): IInputItem
public function setSize($size)
{
$this->size = $size;
@@ -100,7 +96,7 @@ class InputFile implements IInputItem
* Get mime-type of file
* @return string
*/
public function getMime(): string
public function getMime()
{
return $this->getType();
}
@@ -108,7 +104,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getType(): string
public function getType()
{
return $this->type;
}
@@ -116,9 +112,9 @@ class InputFile implements IInputItem
/**
* Set type
* @param string $type
* @return static
* @return static $this
*/
public function setType(string $type): IInputItem
public function setType($type)
{
$this->type = $type;
@@ -130,7 +126,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getExtension(): string
public function getExtension()
{
return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
}
@@ -140,7 +136,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getName(): string
public function getName()
{
return $this->name;
}
@@ -150,9 +146,9 @@ class InputFile implements IInputItem
* Useful for adding validation etc.
*
* @param string $name
* @return static
* @return static $this
*/
public function setName(string $name): IInputItem
public function setName($name)
{
$this->name = $name;
@@ -163,9 +159,9 @@ class InputFile implements IInputItem
* Set filename
*
* @param string $name
* @return static
* @return static $this
*/
public function setFilename($name): IInputItem
public function setFilename($name)
{
$this->filename = $name;
@@ -177,7 +173,7 @@ class InputFile implements IInputItem
*
* @return string mixed
*/
public function getFilename(): string
public function getFilename()
{
return $this->filename;
}
@@ -188,7 +184,7 @@ class InputFile implements IInputItem
* @param string $destination
* @return bool
*/
public function move($destination): bool
public function move($destination)
{
return move_uploaded_file($this->tmpName, $destination);
}
@@ -198,7 +194,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getContents(): string
public function getContents()
{
return file_get_contents($this->tmpName);
}
@@ -208,7 +204,7 @@ class InputFile implements IInputItem
*
* @return bool
*/
public function hasError(): bool
public function hasError()
{
return ($this->getError() !== 0);
}
@@ -218,20 +214,20 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getError(): string
public function getError()
{
return $this->errors;
return $this->error;
}
/**
* Set error
*
* @param int $error
* @return static
* @return static $this
*/
public function setError($error): IInputItem
public function setError($error)
{
$this->errors = (int)$error;
$this->error = (int)$error;
return $this;
}
@@ -239,7 +235,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getTmpName(): string
public function getTmpName()
{
return $this->tmpName;
}
@@ -247,9 +243,9 @@ class InputFile implements IInputItem
/**
* Set file temp. name
* @param string $name
* @return static
* @return static $this
*/
public function setTmpName($name): IInputItem
public function setTmpName($name)
{
$this->tmpName = $name;
@@ -261,30 +257,19 @@ class InputFile implements IInputItem
return $this->getTmpName();
}
public function getValue(): string
public function getValue()
{
return $this->getFilename();
}
/**
* @param string $value
* @return static
*/
public function setValue(string $value): IInputItem
{
$this->filename = $value;
return $this;
}
public function toArray(): array
public function toArray()
{
return [
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->name,
'error' => $this->errors,
'error' => $this->error,
'filename' => $this->filename,
];
}
+9 -10
View File
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Http\Input;
class InputItem implements IInputItem
@@ -8,7 +7,7 @@ class InputItem implements IInputItem
public $name;
public $value;
public function __construct(string $index, ?string $value = null)
public function __construct($index, $value = null)
{
$this->index = $index;
$this->value = $value;
@@ -20,12 +19,12 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getIndex(): string
public function getIndex()
{
return $this->index;
}
public function setIndex(string $index): IInputItem
public function setIndex($index)
{
$this->index = $index;
@@ -35,7 +34,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getName(): string
public function getName()
{
return $this->name;
}
@@ -43,9 +42,9 @@ class InputItem implements IInputItem
/**
* Set input name
* @param string $name
* @return static
* @return static $this
*/
public function setName(string $name): IInputItem
public function setName($name)
{
$this->name = $name;
@@ -55,7 +54,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getValue(): string
public function getValue()
{
return $this->value;
}
@@ -63,9 +62,9 @@ class InputItem implements IInputItem
/**
* Set input value
* @param string $value
* @return static
* @return static $this
*/
public function setValue(string $value): IInputItem
public function setValue($value)
{
$this->value = $value;
+13 -23
View File
@@ -9,16 +9,12 @@ use Pecee\Http\Security\ITokenProvider;
class BaseCsrfVerifier implements IMiddleware
{
public const POST_KEY = 'csrf-token';
public const HEADER_KEY = 'X-CSRF-TOKEN';
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $tokenProvider;
/**
* BaseCsrfVerifier constructor.
* @throws \Pecee\Http\Security\Exceptions\SecurityException
*/
public function __construct()
{
$this->tokenProvider = new CookieTokenProvider();
@@ -29,23 +25,23 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request
* @return bool
*/
protected function skip(Request $request): bool
protected function skip(Request $request)
{
if ($this->except === null || \count($this->except) === 0) {
if ($this->except === null || count($this->except) === 0) {
return false;
}
$max = \count($this->except) - 1;
$max = count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
$url = rtrim($url, '/');
if ($url[\strlen($url) - 1] === '*') {
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = $request->getUrl()->contains($url);
$skip = (stripos($request->getUri()->getPath(), $url) === 0);
} else {
$skip = ($url === $request->getUrl()->getOriginalUrl());
$skip = ($url === $request->getUri()->getPath());
}
if ($skip === true) {
@@ -56,18 +52,12 @@ class BaseCsrfVerifier implements IMiddleware
return false;
}
/**
* Handle request
*
* @param Request $request
* @throws TokenMismatchException
*/
public function handle(Request $request): void
public function handle(Request $request)
{
if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) {
$token = $request->getInputHandler()->get(static::POST_KEY, null, 'post');
$token = $request->getInput()->get(static::POST_KEY, null, 'post');
// If the token is not posted, check headers for valid x-csrf-token
if ($token === null) {
@@ -85,7 +75,7 @@ class BaseCsrfVerifier implements IMiddleware
}
public function getTokenProvider(): ITokenProvider
public function getTokenProvider()
{
return $this->tokenProvider;
}
@@ -94,7 +84,7 @@ class BaseCsrfVerifier implements IMiddleware
* Set token provider
* @param ITokenProvider $provider
*/
public function setTokenProvider(ITokenProvider $provider): void
public function setTokenProvider(ITokenProvider $provider)
{
$this->tokenProvider = $provider;
}
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Http\Middleware\Exceptions;
class TokenMismatchException extends \Exception
+2 -2
View File
@@ -1,5 +1,4 @@
<?php
namespace Pecee\Http\Middleware;
use Pecee\Http\Request;
@@ -8,7 +7,8 @@ interface IMiddleware
{
/**
* @param Request $request
* @return Request|null
*/
public function handle(Request $request): void;
public function handle(Request $request);
}
+69 -129
View File
@@ -2,7 +2,7 @@
namespace Pecee\Http;
use Pecee\Http\Input\InputHandler;
use Pecee\Http\Input\Input;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter;
@@ -10,13 +10,11 @@ use Pecee\SimpleRouter\SimpleRouter;
class Request
{
private $data = [];
protected $headers = [];
protected $headers;
protected $host;
protected $url;
protected $uri;
protected $method;
protected $inputHandler;
protected $hasRewrite = false;
protected $input;
/**
* @var ILoadableRoute|null
@@ -25,55 +23,58 @@ class Request
protected $rewriteUrl;
/**
* @var array
* @var ILoadableRoute|null
*/
protected $loadedRoutes = [];
protected $loadedRoute;
/**
* Request constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function __construct()
{
$this->parseHeaders();
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUri(new Uri($this->getHeader('unencoded-url', $this->getHeader('request-uri'))));
$this->input = new Input($this);
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'), 'post'));
}
protected function parseHeaders()
{
$this->headers = [];
foreach ($_SERVER as $key => $value) {
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri')));
$this->inputHandler = new InputHandler($this);
$this->method = strtolower($this->inputHandler->get('_method', $this->getHeader('request-method')));
}
public function isSecure(): bool
public function isSecure()
{
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
}
/**
* @return Url
* @return Uri
*/
public function getUrl(): Url
public function getUri()
{
return $this->url;
return $this->uri;
}
/**
* @return string|null
* @return string
*/
public function getHost(): ?string
public function getHost()
{
return $this->host;
}
/**
* @return string|null
* @return string
*/
public function getMethod(): ?string
public function getMethod()
{
return $this->method;
}
@@ -82,7 +83,7 @@ class Request
* Get http basic auth user
* @return string|null
*/
public function getUser(): ?string
public function getUser()
{
return $this->getHeader('php-auth-user');
}
@@ -91,7 +92,7 @@ class Request
* Get http basic auth password
* @return string|null
*/
public function getPassword(): ?string
public function getPassword()
{
return $this->getHeader('php-auth-pw');
}
@@ -100,16 +101,16 @@ class Request
* Get all headers
* @return array
*/
public function getHeaders(): array
public function getHeaders()
{
return $this->headers;
}
/**
* Get id address
* @return string|null
* @return string
*/
public function getIp(): ?string
public function getIp()
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
@@ -126,27 +127,27 @@ class Request
* Get remote address/ip
*
* @alias static::getIp
* @return string|null
* @return string
*/
public function getRemoteAddr(): ?string
public function getRemoteAddr()
{
return $this->getIp();
}
/**
* Get referer
* @return string|null
* @return string
*/
public function getReferer(): ?string
public function getReferer()
{
return $this->getHeader('http-referer');
}
/**
* Get user agent
* @return string|null
* @return string
*/
public function getUserAgent(): ?string
public function getUserAgent()
{
return $this->getHeader('http-user-agent');
}
@@ -159,18 +160,18 @@ class Request
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null): ?string
public function getHeader($name, $defaultValue = null)
{
return $this->headers[strtolower($name)] ?? $defaultValue;
return isset($this->headers[strtolower($name)]) ? $this->headers[strtolower($name)] : $defaultValue;
}
/**
* Get input class
* @return InputHandler
* @return Input
*/
public function getInputHandler(): InputHandler
public function getInput()
{
return $this->inputHandler;
return $this->input;
}
/**
@@ -180,43 +181,32 @@ class Request
*
* @return bool
*/
public function isFormatAccepted($format): bool
public function isFormatAccepted($format)
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) !== false);
}
/**
* Returns true if the request is made through Ajax
*
* @return bool
*/
public function isAjax(): bool
{
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
/**
* Get accept formats
* @return array
*/
public function getAcceptFormats(): array
public function getAcceptFormats()
{
return explode(',', $this->getHeader('http-accept'));
}
/**
* @param string|Url $url
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @param Uri $uri
*/
public function setUrl($url): void
public function setUri(Uri $uri)
{
$this->url = ($url instanceof Url) ? $url : new Url($url);
$this->uri = $uri;
}
/**
* @param string|null $host
* @param string $host
*/
public function setHost(?string $host): void
public function setHost($host)
{
$this->host = $host;
}
@@ -224,7 +214,7 @@ class Request
/**
* @param string $method
*/
public function setMethod(string $method): void
public function setMethod($method)
{
$this->method = $method;
}
@@ -235,9 +225,8 @@ class Request
* @param ILoadableRoute $route
* @return static
*/
public function setRewriteRoute(ILoadableRoute $route): self
public function setRewriteRoute(ILoadableRoute $route)
{
$this->hasRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
return $this;
@@ -248,7 +237,7 @@ class Request
*
* @return ILoadableRoute|null
*/
public function getRewriteRoute(): ?ILoadableRoute
public function getRewriteRoute()
{
return $this->rewriteRoute;
}
@@ -256,9 +245,9 @@ class Request
/**
* Get rewrite url
*
* @return string|null
* @return string
*/
public function getRewriteUrl(): ?string
public function getRewriteUrl()
{
return $this->rewriteUrl;
}
@@ -269,97 +258,48 @@ class Request
* @param string $rewriteUrl
* @return static
*/
public function setRewriteUrl(string $rewriteUrl): self
public function setRewriteUrl($rewriteUrl)
{
$this->hasRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
$this->rewriteUrl = $rewriteUrl;
return $this;
}
/**
* Set rewrite callback
* @param string|\Closure $callback
* @param string $callback
* @return static
*/
public function setRewriteCallback($callback): self
public function setRewriteCallback($callback)
{
$this->hasRewrite = true;
return $this->setRewriteRoute(new RouteUrl($this->getUrl()->getPath(), $callback));
return $this->setRewriteRoute(new RouteUrl($this->uri, $callback));
}
/**
* Get loaded route
* @return ILoadableRoute|null
*/
public function getLoadedRoute(): ?ILoadableRoute
public function getLoadedRoute()
{
return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
return $this->loadedRoute;
}
/**
* Get all loaded routes
*
* @return array
*/
public function getLoadedRoutes(): array
{
return $this->loadedRoutes;
}
/**
* Set loaded routes
*
* @param array $routes
* @return static
*/
public function setLoadedRoutes(array $routes): self
{
$this->loadedRoutes = $routes;
return $this;
}
/**
* Added loaded route
* Set loaded route
*
* @param ILoadableRoute $route
* @return static
*/
public function addLoadedRoute(ILoadableRoute $route): self
public function setLoadedRoute(ILoadableRoute $route)
{
$this->loadedRoutes[] = $route;
return $this;
}
/**
* Returns true if the request contains a rewrite
*
* @return bool
*/
public function hasRewrite(): bool
{
return $this->hasRewrite;
}
/**
* Defines if the current request contains a rewrite.
*
* @param bool $boolean
* @return Request
*/
public function setHasRewrite(bool $boolean): self
{
$this->hasRewrite = $boolean;
$this->loadedRoute = $route;
return $this;
}
public function __isset($name)
{
return array_key_exists($name, $this->data) === true;
return array_key_exists($name, $this->data);
}
public function __set($name, $value = null)
@@ -369,7 +309,7 @@ class Request
public function __get($name)
{
return $this->data[$name] ?? null;
return isset($this->data[$name]) ? $this->data[$name] : null;
}
}
+20 -23
View File
@@ -2,8 +2,6 @@
namespace Pecee\Http;
use Pecee\Exceptions\InvalidArgumentException;
class Response
{
protected $request;
@@ -19,7 +17,7 @@ class Response
* @param int $code
* @return static
*/
public function httpCode(int $code): self
public function httpCode($code)
{
http_response_code($code);
@@ -32,19 +30,19 @@ class Response
* @param string $url
* @param int $httpCode
*/
public function redirect(string $url, ?int $httpCode = null): void
public function redirect($url, $httpCode = null)
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
}
$this->header('location: ' . $url);
exit(0);
die();
}
public function refresh(): void
public function refresh()
{
$this->redirect($this->request->getUrl()->getOriginalUrl());
$this->redirect($this->request->getUri()->getPath());
}
/**
@@ -52,7 +50,7 @@ class Response
* @param string $name
* @return static
*/
public function auth(string $name = ''): self
public function auth($name = '')
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
@@ -62,22 +60,23 @@ class Response
return $this;
}
public function cache(string $eTag, int $lastModifiedTime = 2592000): self
public function cache($eTag, $lastModified = 2592000)
{
$this->headers([
'Cache-Control: public',
sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
sprintf('Etag: %s', $eTag),
'Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT',
'Etag: ' . $eTag,
]);
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModifiedTime)) {
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) {
$this->header('HTTP/1.1 304 Not Modified');
exit(0);
exit();
}
return $this;
@@ -86,18 +85,16 @@ class Response
/**
* Json encode
* @param array|\JsonSerializable $value
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
* @param int $dept JSON debt.
* @throws InvalidArgumentException
* @throws \InvalidArgumentException;
*/
public function json($value, ?int $options = null, int $dept = 512): void
public function json($value)
{
if (($value instanceof \JsonSerializable) === false && \is_array($value) === false) {
throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
if (($value instanceof \JsonSerializable) === false && is_array($value) === false) {
throw new \InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
}
$this->header('Content-Type: application/json; charset=utf-8');
echo json_encode($value, $options, $dept);
$this->header('Content-type: application/json');
echo json_encode($value);
exit(0);
}
@@ -106,7 +103,7 @@ class Response
* @param string $value
* @return static
*/
public function header(string $value): self
public function header($value)
{
header($value);
@@ -118,7 +115,7 @@ class Response
* @param array $headers
* @return static
*/
public function headers(array $headers): self
public function headers(array $headers)
{
foreach ($headers as $header) {
$this->header($header);
+23 -22
View File
@@ -2,19 +2,13 @@
namespace Pecee\Http\Security;
use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider
{
public const CSRF_KEY = 'CSRF-TOKEN';
const CSRF_KEY = 'CSRF-TOKEN';
protected $token;
protected $cookieTimeoutMinutes = 120;
/**
* CookieTokenProvider constructor.
* @throws SecurityException
*/
public function __construct()
{
$this->token = $this->getToken();
@@ -27,16 +21,23 @@ class CookieTokenProvider implements ITokenProvider
/**
* Generate random identifier for CSRF token
*
* @throws \RuntimeException
* @return string
* @throws SecurityException
*/
public function generateToken(): string
public function generateToken()
{
try {
if (function_exists('random_bytes') === true) {
return bin2hex(random_bytes(32));
} catch (\Exception $e) {
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
$isSourceStrong = false;
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
if ($isSourceStrong === false || $random === false) {
throw new \RuntimeException('IV generation failed');
}
return $random;
}
/**
@@ -45,9 +46,9 @@ class CookieTokenProvider implements ITokenProvider
* @param string $token
* @return bool
*/
public function validate(string $token): bool
public function validate($token)
{
if ($this->getToken() !== null) {
if ($token !== null && $this->getToken() !== null) {
return hash_equals($token, $this->getToken());
}
@@ -60,7 +61,7 @@ class CookieTokenProvider implements ITokenProvider
*
* @param string $token
*/
public function setToken(string $token): void
public function setToken($token)
{
$this->token = $token;
setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
@@ -71,17 +72,17 @@ class CookieTokenProvider implements ITokenProvider
* @param string|null $defaultValue
* @return string|null
*/
public function getToken(?string $defaultValue = null): ?string
public function getToken($defaultValue = null)
{
$this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
return $this->token ?? $defaultValue;
return ($this->token !== null) ? $this->token : $defaultValue;
}
/**
* Refresh existing token
*/
public function refresh(): void
public function refresh()
{
if ($this->token !== null) {
$this->setToken($this->token);
@@ -92,7 +93,7 @@ class CookieTokenProvider implements ITokenProvider
* Returns whether the csrf token has been defined
* @return bool
*/
public function hasToken(): bool
public function hasToken()
{
return isset($_COOKIE[static::CSRF_KEY]);
}
@@ -101,16 +102,16 @@ class CookieTokenProvider implements ITokenProvider
* Get timeout for cookie in minutes
* @return int
*/
public function getCookieTimeoutMinutes(): int
public function getCookieTimeoutMinutes()
{
return $this->cookieTimeoutMinutes;
}
/**
* Set cookie timeout in minutes
* @param int $minutes
* @param $minutes
*/
public function setCookieTimeoutMinutes(int $minutes): void
public function setCookieTimeoutMinutes($minutes)
{
$this->cookieTimeoutMinutes = $minutes;
}
@@ -1,8 +0,0 @@
<?php
namespace Pecee\Http\Security\Exceptions;
class SecurityException extends \Exception
{
}
+2 -10
View File
@@ -8,7 +8,7 @@ interface ITokenProvider
/**
* Refresh existing token
*/
public function refresh(): void;
public function refresh();
/**
* Validate valid CSRF token
@@ -16,14 +16,6 @@ interface ITokenProvider
* @param string $token
* @return bool
*/
public function validate(string $token): bool;
/**
* Get token token
*
* @param string|null $defaultValue
* @return string|null
*/
public function getToken(?string $defaultValue = null): ?string;
public function validate($token);
}
@@ -2,44 +2,36 @@
namespace Pecee\Http;
use Pecee\Http\Exceptions\MalformedUrlException;
class Url
class Uri
{
private $originalUrl;
private $data = [
'scheme' => null,
'host' => null,
'port' => null,
'user' => null,
'pass' => null,
'path' => null,
'query' => null,
'fragment' => null,
'scheme' => '',
'host' => '',
'port' => '',
'user' => '',
'pass' => '',
'path' => '',
'query' => '',
'fragment' => '',
];
/**
* Url constructor.
* @param string $url
* @throws MalformedUrlException
*/
public function __construct(?string $url)
public function __construct($url)
{
$this->originalUrl = $url;
if ($url !== null) {
$this->data = $this->parseUrl($url) + $this->data;
$this->data = $this->parseUrl($url) + $this->data;
if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
$this->data['path'] = rtrim($this->data['path'], '/') . '/';
}
if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
$this->data['path'] = rtrim($this->data['path'], '/') . '/';
}
}
/**
* Check if url is using a secure protocol like https
* @return bool
*/
public function isSecure(): bool
public function isSecure()
{
return (strtolower($this->getScheme()) === 'https');
}
@@ -48,7 +40,7 @@ class Url
* Checks if url is relative
* @return bool
*/
public function isRelative(): bool
public function isRelative()
{
return ($this->getHost() === null);
}
@@ -57,7 +49,7 @@ class Url
* Get url scheme
* @return string|null
*/
public function getScheme(): ?string
public function getScheme()
{
return $this->data['scheme'];
}
@@ -66,7 +58,7 @@ class Url
* Get url host
* @return string|null
*/
public function getHost(): ?string
public function getHost()
{
return $this->data['host'];
}
@@ -75,7 +67,7 @@ class Url
* Get url port
* @return int|null
*/
public function getPort(): ?int
public function getPort()
{
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
}
@@ -84,7 +76,7 @@ class Url
* Parse username from url
* @return string|null
*/
public function getUserName(): ?string
public function getUserName()
{
return $this->data['user'];
}
@@ -93,7 +85,7 @@ class Url
* Parse password from url
* @return string|null
*/
public function getPassword(): ?string
public function getPassword()
{
return $this->data['pass'];
}
@@ -102,16 +94,16 @@ class Url
* Get path from url
* @return string
*/
public function getPath(): ?string
public function getPath()
{
return $this->data['path'] ?? '/';
return $this->data['path'];
}
/**
* Get querystring from url
* @return string|null
*/
public function getQueryString(): ?string
public function getQueryString()
{
return $this->data['query'];
}
@@ -120,7 +112,7 @@ class Url
* Get fragment from url (everything after #)
* @return string|null
*/
public function getFragment(): ?string
public function getFragment()
{
return $this->data['fragment'];
}
@@ -128,7 +120,7 @@ class Url
/**
* @return string
*/
public function getOriginalUrl(): string
public function getOriginalUrl()
{
return $this->originalUrl;
}
@@ -137,13 +129,13 @@ class Url
* UTF-8 aware parse_url() replacement.
* @param string $url
* @param int $component
* @throws MalformedUrlException
* @throws \InvalidArgumentException
* @return array
*/
public function parseUrl(string $url, int $component = -1): array
public function parseUrl($url, $component = -1)
{
$encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u',
'%[^:/@?&=#]+%u',
function ($matches) {
return urlencode($matches[0]);
},
@@ -153,42 +145,21 @@ class Url
$parts = parse_url($encodedUrl, $component);
if ($parts === false) {
throw new MalformedUrlException('Malformed URL: ' . $url);
throw new \InvalidArgumentException('Malformed URL: ' . $url);
}
return array_map('urldecode', $parts);
}
foreach ((array)$parts as $name => $value) {
$parts[$name] = urldecode($value);
}
/**
* Get position of value.
* Returns -1 on failure.
*
* @param string $value
* @return int
*/
public function indexOf(string $value): int
{
$index = stripos($this->getOriginalUrl(), $value);
return ($index === false) ? -1 : $index;
}
/**
* Check if url contains value.
*
* @param string $value
* @return bool
*/
public function contains(string $value): bool
{
return (stripos($this->getOriginalUrl(), $value) !== false);
return $parts;
}
/**
* Returns data array with information about the url
* @return array
*/
public function getData(): array
public function getData()
{
return $this->data;
}
@@ -1,5 +1,4 @@
<?php
namespace Pecee\SimpleRouter\Exceptions;
class HttpException extends \Exception
@@ -1,5 +1,4 @@
<?php
namespace Pecee\SimpleRouter\Exceptions;
class NotFoundHttpException extends HttpException
@@ -1,5 +1,4 @@
<?php
namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
@@ -10,6 +9,7 @@ interface IRouterBootManager
* Called when router loads it's routes
*
* @param Request $request
* @return Request
*/
public function boot(Request $request): void;
public function boot(Request $request);
}
@@ -1,5 +1,4 @@
<?php
namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute
@@ -9,7 +8,7 @@ interface IControllerRoute extends IRoute
*
* @return string
*/
public function getController(): string;
public function getController();
/**
* Set controller class-name
@@ -17,6 +16,21 @@ interface IControllerRoute extends IRoute
* @param string $controller
* @return static
*/
public function setController(string $controller): self;
public function setController($controller);
/**
* Return active method
*
* @return string
*/
public function getMethod();
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method);
}
+12 -12
View File
@@ -13,21 +13,21 @@ interface IGroupRoute extends IRoute
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request): bool;
public function matchDomain(Request $request);
/**
* Add exception handler
*
* @param IExceptionHandler|string $handler
* @return static
* @return static $this;
*/
public function addExceptionHandler($handler): self;
public function addExceptionHandler($handler);
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static
* @return static $this
*/
public function setExceptionHandlers(array $handlers);
@@ -36,35 +36,35 @@ interface IGroupRoute extends IRoute
*
* @return array
*/
public function getExceptionHandlers(): array;
public function getExceptionHandlers();
/**
* Get domains for domain.
*
* @return array
*/
public function getDomains(): array;
public function getDomains();
/**
* Set allowed domains for group.
*
* @param array $domains
* @return static
* @return $this
*/
public function setDomains(array $domains): self;
public function setDomains(array $domains);
/**
* Set prefix that child-routes will inherit.
*
* @param string $prefix
* @return static
* @return string
*/
public function setPrefix($prefix): self;
public function setPrefix($prefix);
/**
* Get prefix.
*
* @return string|null
* @return string
*/
public function getPrefix(): ?string;
public function getPrefix();
}
+12 -24
View File
@@ -1,9 +1,7 @@
<?php
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface ILoadableRoute extends IRoute
{
@@ -16,35 +14,25 @@ interface ILoadableRoute extends IRoute
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null): string;
public function findUrl($method = null, $parameters = null, $name = null);
/**
* Loads and renders middleware-classes
* Loads and renders middlewares-classes
*
* @param Request $request
* @param Router $router
*/
public function loadMiddleware(Request $request, Router $router): void;
public function loadMiddleware(Request $request);
/**
* Get url
* @return string
*/
public function getUrl(): string;
public function getUrl();
/**
* Set url
* @param string $url
* @return static
*/
public function setUrl(string $url): self;
public function setUrl($url);
/**
* Returns the provided name for the router.
*
* @return string|null
* @return string
*/
public function getName(): ?string;
public function getName();
/**
* Check if route has given name.
@@ -52,22 +40,22 @@ interface ILoadableRoute extends IRoute
* @param string $name
* @return bool
*/
public function hasName(string $name): bool;
public function hasName($name);
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static
* @return static $this
*/
public function setName(string $name): self;
public function setName($name);
/**
* Get regular expression match used for matching route (if defined).
*
* @return string
*/
public function getMatch(): ?string;
public function getMatch();
/**
* Add regular expression match for the entire route.
@@ -75,6 +63,6 @@ interface ILoadableRoute extends IRoute
* @param string $regex
* @return static
*/
public function setMatch($regex): self;
public function setMatch($regex);
}
+36 -58
View File
@@ -3,7 +3,6 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface IRoute
{
@@ -14,18 +13,17 @@ interface IRoute
* @param Request $request
* @return bool
*/
public function matchRoute($route, Request $request): bool;
public function matchRoute($route, Request $request);
/**
* Called when route is matched.
* Returns class to be rendered.
*
* @param Request $request
* @param Router $router
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string
*/
public function renderRoute(Request $request, Router $router): ?string;
public function renderRoute(Request $request);
/**
* Returns callback name/identifier for the current route based on the callback.
@@ -34,50 +32,50 @@ interface IRoute
*
* @return string
*/
public function getIdentifier(): string;
public function getIdentifier();
/**
* Set allowed request methods
*
* @param array $methods
* @return static
* @return static $this
*/
public function setRequestMethods(array $methods): self;
public function setRequestMethods(array $methods);
/**
* Get allowed request methods
*
* @return array
*/
public function getRequestMethods(): array;
public function getRequestMethods();
/**
* @return IRoute|null
*/
public function getParent(): ?IRoute;
public function getParent();
/**
* Get the group for the route.
*
* @return IGroupRoute|null
*/
public function getGroup(): ?IGroupRoute;
public function getGroup();
/**
* Set group
*
* @param IGroupRoute $group
* @return static
* @return static $this
*/
public function setGroup(IGroupRoute $group): self;
public function setGroup(IGroupRoute $group);
/**
* Set parent route
*
* @param IRoute $parent
* @return static
* @return static $this
*/
public function setParent(IRoute $parent): self;
public function setParent(IRoute $parent);
/**
* Set callback
@@ -85,64 +83,44 @@ interface IRoute
* @param string $callback
* @return static
*/
public function setCallback($callback): self;
public function setCallback($callback);
/**
* @return string|callable
* @return string
*/
public function getCallback();
/**
* Return active method
*
* @return string|null
*/
public function getMethod(): ?string;
public function getMethod();
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod(string $method): self;
public function getClass();
/**
* Get class
*
* @return string|null
*/
public function getClass(): ?string;
public function setMethod($method);
/**
* @param string $namespace
* @return static
* @return static $this
*/
public function setNamespace(string $namespace): self;
public function setNamespace($namespace);
/**
* @return string|null
* @return string
*/
public function getNamespace(): ?string;
public function getNamespace();
/**
* @param string $namespace
* @return static
* @return static $this
*/
public function setDefaultNamespace($namespace): IRoute;
public function setDefaultNamespace($namespace);
/**
* Get default namespace
* @return string|null
*/
public function getDefaultNamespace(): ?string;
public function getDefaultNamespace();
/**
* Get parameter names.
*
* @return array
*/
public function getWhere(): array;
public function getWhere();
/**
* Set parameter names.
@@ -150,45 +128,45 @@ interface IRoute
* @param array $options
* @return static
*/
public function setWhere(array $options): self;
public function setWhere(array $options);
/**
* Get parameters
*
* @return array
*/
public function getParameters(): array;
public function getParameters();
/**
* Get parameters
*
* @param array $parameters
* @return static
* @return static $this
*/
public function setParameters(array $parameters): self;
public function setParameters(array $parameters);
/**
* Merge with information from another route.
*
* @param array $settings
* @param bool $merge
* @return static
* @return static $this
*/
public function setSettings(array $settings, bool $merge = false): self;
public function setSettings(array $settings, $merge = false);
/**
* Export route settings to array so they can be merged with another route.
*
* @return array
*/
public function toArray(): array;
public function toArray();
/**
* Get middlewares array
*
* @return array
*/
public function getMiddlewares(): array;
public function getMiddlewares();
/**
* Set middleware class-name
@@ -196,14 +174,14 @@ interface IRoute
* @param string $middleware
* @return static
*/
public function addMiddleware($middleware): self;
public function addMiddleware($middleware);
/**
* Set middlewares array
*
* @param array $middlewares
* @return static
* @return $this
*/
public function setMiddlewares(array $middlewares): self;
public function setMiddlewares(array $middlewares);
}
+44 -44
View File
@@ -5,7 +5,6 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Router;
abstract class LoadableRoute extends Route implements ILoadableRoute
{
@@ -25,32 +24,32 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Loads and renders middlewares-classes
*
* @param Request $request
* @param Router $router
* @throws HttpException
*/
public function loadMiddleware(Request $request, Router $router): void
public function loadMiddleware(Request $request)
{
$router->debug('Loading middlewares');
$max = count($this->getMiddlewares());
foreach ($this->getMiddlewares() as $middleware) {
if ($max !== 0) {
if (\is_object($middleware) === false) {
$middleware = $this->loadClass($middleware);
for ($i = 0; $i < $max; $i++) {
$middleware = $this->getMiddlewares()[$i];
if (is_object($middleware) === false) {
$middleware = $this->loadClass($middleware);
}
if (($middleware instanceof IMiddleware) === false) {
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
}
$middleware->handle($request);
}
if (($middleware instanceof IMiddleware) === false) {
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
}
$router->debug('Loading middleware "%s"', \get_class($middleware));
$middleware->handle($request);
$router->debug('Finished loading middleware');
}
$router->debug('Finished loading middlewares');
}
public function matchRegex(Request $request, $url): ?bool
public function matchRegex(Request $request, $url)
{
/* Match on custom defined regular expression */
@@ -58,7 +57,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null;
}
return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
return (preg_match($this->regex, $request->getHost() . $url) !== 0);
}
/**
@@ -67,7 +66,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $url
* @return static
*/
public function setUrl(string $url): ILoadableRoute
public function setUrl($url)
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
@@ -75,7 +74,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if ((bool)preg_match_all('/' . $regex . '/u', $this->url, $matches) !== false) {
if (preg_match_all('/' . $regex . '/u', $this->url, $matches) === 1) {
$this->parameters = array_fill_keys($matches[1], null);
}
}
@@ -83,7 +82,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this;
}
public function getUrl(): string
public function getUrl()
{
return $this->url;
}
@@ -97,13 +96,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null): string
public function findUrl($method = null, $parameters = null, $name = null)
{
$url = $this->getUrl();
$group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) {
if ($group !== null && count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url;
}
@@ -119,10 +118,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/* Replace any {parameter} in the url with the correct value */
$params = $this->getParameters();
$max = count($params) - 1;
$keys = array_keys($params);
foreach (array_keys($params) as $param) {
for ($i = $max; $i >= 0; $i--) {
$param = $keys[$i];
if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) {
if ($parameters === '' || (is_array($parameters) && count($parameters) === 0)) {
$value = '';
} else {
$p = (array)$parameters;
@@ -142,7 +144,8 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
}
}
$url = '/' . ltrim($url, '/') . implode('/', $unknownParams);
$url = '/' . ltrim($url, '/');
$url .= join('/', $unknownParams);
return rtrim($url, '/') . '/';
}
@@ -152,7 +155,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
public function getName(): string
public function getName()
{
return $this->name;
}
@@ -163,9 +166,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $name
* @return bool
*/
public function hasName(string $name): bool
public function hasName($name)
{
return strtolower($this->name) === strtolower($name);
return (strtolower($this->name) === strtolower($name));
}
/**
@@ -174,7 +177,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex
* @return static
*/
public function setMatch($regex): ILoadableRoute
public function setMatch($regex)
{
$this->regex = $regex;
@@ -186,7 +189,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
public function getMatch(): string
public function getMatch()
{
return $this->regex;
}
@@ -199,7 +202,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|array $name
* @return static
*/
public function name($name): ILoadableRoute
public function name($name)
{
return $this->setName($name);
}
@@ -208,9 +211,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static
* @return static $this
*/
public function setName(string $name): ILoadableRoute
public function setName($name)
{
$this->name = $name;
@@ -224,20 +227,17 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, bool $merge = false): IRoute
public function setSettings(array $values, $merge = false)
{
if (isset($values['as']) === true) {
$name = $values['as'];
if (isset($values['as'])) {
if ($this->name !== null && $merge !== false) {
$name .= '.' . $this->name;
$this->setName($values['as'] . '.' . $this->name);
} else {
$this->setName($values['as']);
}
$this->setName($name);
}
if (isset($values['prefix']) === true) {
if (isset($values['prefix'])) {
$this->setUrl($values['prefix'] . $this->getUrl());
}
+87 -110
View File
@@ -5,19 +5,18 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute
{
protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
const PARAMETERS_DEFAULT_REGEX = '[\w]+';
public const REQUEST_TYPE_GET = 'get';
public const REQUEST_TYPE_POST = 'post';
public const REQUEST_TYPE_PUT = 'put';
public const REQUEST_TYPE_PATCH = 'patch';
public const REQUEST_TYPE_OPTIONS = 'options';
public const REQUEST_TYPE_DELETE = 'delete';
const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_POST = 'post';
const REQUEST_TYPE_PUT = 'put';
const REQUEST_TYPE_PATCH = 'patch';
const REQUEST_TYPE_OPTIONS = 'options';
const REQUEST_TYPE_DELETE = 'delete';
public static $requestTypes = [
self::REQUEST_TYPE_GET,
@@ -34,7 +33,7 @@ abstract class Route implements IRoute
*
* @var bool
*/
protected $filterEmptyParams = true;
protected $filterEmptyParams = false;
/**
* Default regular expression used for parsing parameters.
@@ -57,12 +56,6 @@ abstract class Route implements IRoute
protected $originalParameters = [];
protected $middlewares = [];
/**
* Load class by name
* @param string $name
* @return mixed
* @throws NotFoundHttpException
*/
protected function loadClass($name)
{
if (class_exists($name) === false) {
@@ -72,42 +65,20 @@ abstract class Route implements IRoute
return new $name();
}
/**
* Render route
*
* @param Request $request
* @param Router $router
* @return string|null
* @throws NotFoundHttpException
*/
public function renderRoute(Request $request, Router $router): ?string
public function renderRoute(Request $request)
{
$router->debug('Starting rendering route');
$callback = $this->getCallback();
if ($callback === null) {
return null;
}
$router->debug('Parsing parameters');
$parameters = $this->getParameters();
$router->debug('Finished parsing parameters');
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
});
}
/* Render callback function */
if (\is_callable($callback) === true) {
$router->debug('Executing callback');
if (is_callable($callback) === true) {
/* When the callback is a function */
return call_user_func_array($callback, $this->getParameters());
return \call_user_func_array($callback, $parameters);
}
/* When the callback is a class + method */
@@ -117,7 +88,6 @@ abstract class Route implements IRoute
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
$router->debug('Loading class %s', $className);
$class = $this->loadClass($className);
$method = $controller[1];
@@ -125,9 +95,17 @@ abstract class Route implements IRoute
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
}
$router->debug('Executing callback');
$parameters = $this->getParameters();
return \call_user_func_array([$class, $method], $parameters);
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
});
}
return call_user_func_array([$class, $method], $parameters);
}
protected function parseParameters($route, $url, $parameterRegex = null)
@@ -139,17 +117,15 @@ abstract class Route implements IRoute
// Ensures that hostnames/domains will work with parameters
$url = '/' . ltrim($url, '/');
if ((bool)preg_match_all('/' . $regex . '/u', $route, $parameters) === false) {
$urlRegex = preg_quote($route, '/');
} else {
if (preg_match_all('/' . $regex . '/u', $route, $parameters) !== 0) {
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route);
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', rtrim($route, '/'));
foreach ($urlParts as $key => $t) {
$regex = '';
if ($key < \count($parameters[1])) {
if ($key < count($parameters[1])) {
$name = $parameters[1][$key];
@@ -162,35 +138,39 @@ abstract class Route implements IRoute
if ($parameterRegex !== null) {
$regex = $parameterRegex;
} else {
$regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex;
}
}
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
}
$urlParts[$key] = preg_quote($t, '/') . $regex;
}
$urlRegex = implode('', $urlParts);
$urlRegex = join('', $urlParts);
} else {
$urlRegex = preg_quote($route, '/');
}
if ((bool)preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === false) {
return null;
}
if (preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === 1) {
$values = [];
$values = [];
if (isset($parameters[1]) === true) {
if (isset($parameters[1]) === true) {
/* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) {
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
/* Only take matched parameters with name */
foreach ((array)$parameters[1] as $name) {
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
}
}
return $values;
}
return $values;
return null;
}
/**
@@ -200,9 +180,9 @@ abstract class Route implements IRoute
*
* @return string
*/
public function getIdentifier(): string
public function getIdentifier()
{
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
return $this->callback;
}
@@ -213,9 +193,9 @@ abstract class Route implements IRoute
* Set allowed request methods
*
* @param array $methods
* @return static
* @return static $this
*/
public function setRequestMethods(array $methods): IRoute
public function setRequestMethods(array $methods)
{
$this->requestMethods = $methods;
@@ -227,7 +207,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getRequestMethods(): array
public function getRequestMethods()
{
return $this->requestMethods;
}
@@ -235,7 +215,7 @@ abstract class Route implements IRoute
/**
* @return IRoute|null
*/
public function getParent(): ?IRoute
public function getParent()
{
return $this->parent;
}
@@ -245,7 +225,7 @@ abstract class Route implements IRoute
*
* @return IGroupRoute|null
*/
public function getGroup(): ?IGroupRoute
public function getGroup()
{
return $this->group;
}
@@ -254,15 +234,12 @@ abstract class Route implements IRoute
* Set group
*
* @param IGroupRoute $group
* @return static
* @return static $this
*/
public function setGroup(IGroupRoute $group): IRoute
public function setGroup(IGroupRoute $group)
{
$this->group = $group;
/* Add/merge parent settings with child */
$this->setSettings($group->toArray(), true);
return $this;
}
@@ -270,9 +247,9 @@ abstract class Route implements IRoute
* Set parent route
*
* @param IRoute $parent
* @return static
* @return static $this
*/
public function setParent(IRoute $parent): IRoute
public function setParent(IRoute $parent)
{
$this->parent = $parent;
@@ -285,7 +262,7 @@ abstract class Route implements IRoute
* @param string $callback
* @return static
*/
public function setCallback($callback): IRoute
public function setCallback($callback)
{
$this->callback = $callback;
@@ -293,16 +270,16 @@ abstract class Route implements IRoute
}
/**
* @return string|callable
* @return string
*/
public function getCallback()
{
return $this->callback;
}
public function getMethod(): ?string
public function getMethod()
{
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[1];
@@ -311,9 +288,9 @@ abstract class Route implements IRoute
return null;
}
public function getClass(): ?string
public function getClass()
{
if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[0];
@@ -322,14 +299,14 @@ abstract class Route implements IRoute
return null;
}
public function setMethod(string $method): IRoute
public function setMethod($method)
{
$this->callback = sprintf('%s@%s', $this->getClass(), $method);
return $this;
}
public function setClass(string $class): IRoute
public function setClass($class)
{
$this->callback = sprintf('%s@%s', $class, $this->getMethod());
@@ -338,9 +315,9 @@ abstract class Route implements IRoute
/**
* @param string $namespace
* @return static
* @return static $this
*/
public function setNamespace(string $namespace): IRoute
public function setNamespace($namespace)
{
$this->namespace = $namespace;
@@ -349,26 +326,26 @@ abstract class Route implements IRoute
/**
* @param string $namespace
* @return static
* @return static $this
*/
public function setDefaultNamespace($namespace): IRoute
public function setDefaultNamespace($namespace)
{
$this->defaultNamespace = $namespace;
return $this;
}
public function getDefaultNamespace(): ?string
public function getDefaultNamespace()
{
return $this->defaultNamespace;
}
/**
* @return string|null
* @return string
*/
public function getNamespace(): ?string
public function getNamespace()
{
return $this->namespace ?? $this->defaultNamespace;
return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace;
}
/**
@@ -376,7 +353,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function toArray(): array
public function toArray()
{
$values = [];
@@ -384,15 +361,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace;
}
if (\count($this->requestMethods) !== 0) {
if (count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods;
}
if (\count($this->where) !== 0) {
if (count($this->where) !== 0) {
$values['where'] = $this->where;
}
if (\count($this->middlewares) !== 0) {
if (count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares;
}
@@ -408,9 +385,9 @@ abstract class Route implements IRoute
*
* @param array $values
* @param bool $merge
* @return static
* @return static $this
*/
public function setSettings(array $values, bool $merge = false): IRoute
public function setSettings(array $values, $merge = false)
{
if ($this->namespace === null && isset($values['namespace']) === true) {
$this->setNamespace($values['namespace']);
@@ -445,7 +422,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getWhere(): array
public function getWhere()
{
return $this->where;
}
@@ -456,7 +433,7 @@ abstract class Route implements IRoute
* @param array $options
* @return static
*/
public function setWhere(array $options): IRoute
public function setWhere(array $options)
{
$this->where = $options;
@@ -481,12 +458,12 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getParameters(): array
public function getParameters()
{
/* Sort the parameters after the user-defined param order, if any */
$parameters = [];
if (\count($this->originalParameters) !== 0) {
if (count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters;
}
@@ -497,15 +474,15 @@ abstract class Route implements IRoute
* Get parameters
*
* @param array $parameters
* @return static
* @return static $this
*/
public function setParameters(array $parameters): IRoute
public function setParameters(array $parameters)
{
/*
* If this is the first time setting parameters we store them so we
* later can organize the array, in case somebody tried to sort the array.
*/
if (\count($parameters) !== 0 && \count($this->originalParameters) === 0) {
if (count($parameters) !== 0 && count($this->originalParameters) === 0) {
$this->originalParameters = $parameters;
}
@@ -534,7 +511,7 @@ abstract class Route implements IRoute
* @param IMiddleware|string $middleware
* @return static
*/
public function addMiddleware($middleware): IRoute
public function addMiddleware($middleware)
{
$this->middlewares[] = $middleware;
@@ -545,9 +522,9 @@ abstract class Route implements IRoute
* Set middlewares array
*
* @param array $middlewares
* @return static
* @return $this
*/
public function setMiddlewares(array $middlewares): IRoute
public function setMiddlewares(array $middlewares)
{
$this->middlewares = $middlewares;
@@ -555,9 +532,9 @@ abstract class Route implements IRoute
}
/**
* @return array
* @return string|array
*/
public function getMiddlewares(): array
public function getMiddlewares()
{
return $this->middlewares;
}
@@ -567,7 +544,7 @@ abstract class Route implements IRoute
* This is used when no custom parameter regex is found.
*
* @param string $regex
* @return static
* @return static $this
*/
public function setDefaultParameterRegex($regex)
{
@@ -581,7 +558,7 @@ abstract class Route implements IRoute
*
* @return string
*/
public function getDefaultParameterRegex(): string
public function getDefaultParameterRegex()
{
return $this->defaultParameterRegex;
}
@@ -1,5 +1,4 @@
<?php
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
@@ -24,7 +23,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
public function hasName(string $name): bool
public function hasName($name)
{
if ($this->name === null) {
return false;
@@ -35,7 +34,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
if (in_array($method, $this->names, false) === true && strtolower($this->name) === strtolower($newName)) {
return true;
}
}
@@ -49,7 +48,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null): string
public function findUrl($method = null, $parameters = null, $name = null)
{
if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
@@ -67,7 +66,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (static::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, \strlen($requestType));
$method = (string)substr($method, strlen($requestType));
break;
}
}
@@ -77,21 +76,17 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup();
if ($group !== null && \count($group->getDomains()) !== 0) {
if ($group !== null && count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0];
}
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . implode('/', $parameters);
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters);
return '/' . trim($url, '/') . '/';
}
public function matchRoute($url, Request $request): bool
public function matchRoute($url, Request $request)
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -102,12 +97,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl);
if (\count($path) !== 0) {
if (count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method);
$this->parameters = \array_slice($path, 1);
$this->parameters = array_slice($path, 1);
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
@@ -123,7 +118,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
*
* @return string
*/
public function getController(): string
public function getController()
{
return $this->controller;
}
@@ -134,7 +129,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
public function setController(string $controller): IControllerRoute
public function setController($controller)
{
$this->controller = $controller;
@@ -144,9 +139,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
/**
* Return active method
*
* @return string|null
* @return string
*/
public function getMethod(): ?string
public function getMethod()
{
return $this->method;
}
@@ -157,7 +152,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $method
* @return static
*/
public function setMethod(string $method): IRoute
public function setMethod($method)
{
$this->method = $method;
@@ -171,9 +166,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, bool $merge = false): IRoute
public function setSettings(array $values, $merge = false)
{
if (isset($values['names']) === true) {
if (isset($values['names'])) {
$this->names = $values['names'];
}
+21 -28
View File
@@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request): bool
public function matchDomain(Request $request)
{
if ($this->domains === null || \count($this->domains) === 0) {
if ($this->domains === null || count($this->domains) === 0) {
return true;
}
@@ -28,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && \count($parameters) !== 0) {
if ($parameters !== null && count($parameters) !== 0) {
$this->parameters = $parameters;
@@ -46,12 +46,8 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @return bool
*/
public function matchRoute($url, Request $request): bool
public function matchRoute($url, Request $request)
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
return false;
@@ -64,9 +60,9 @@ class RouteGroup extends Route implements IGroupRoute
* Add exception handler
*
* @param IExceptionHandler|string $handler
* @return static
* @return static $this
*/
public function addExceptionHandler($handler): IGroupRoute
public function addExceptionHandler($handler)
{
$this->exceptionHandlers[] = $handler;
@@ -77,9 +73,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set exception-handlers for group
*
* @param array $handlers
* @return static
* @return static $this
*/
public function setExceptionHandlers(array $handlers): IGroupRoute
public function setExceptionHandlers(array $handlers)
{
$this->exceptionHandlers = $handlers;
@@ -91,7 +87,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function getExceptionHandlers(): array
public function getExceptionHandlers()
{
return $this->exceptionHandlers;
}
@@ -101,7 +97,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function getDomains(): array
public function getDomains()
{
return $this->domains;
}
@@ -110,9 +106,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set allowed domains for group.
*
* @param array $domains
* @return static
* @return $this
*/
public function setDomains(array $domains): IGroupRoute
public function setDomains(array $domains)
{
$this->domains = $domains;
@@ -123,7 +119,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix
* @return static
*/
public function setPrefix($prefix): IGroupRoute
public function setPrefix($prefix)
{
$this->prefix = '/' . trim($prefix, '/');
@@ -133,9 +129,9 @@ class RouteGroup extends Route implements IGroupRoute
/**
* Set prefix that child-routes will inherit.
*
* @return string|null
* @return string
*/
public function getPrefix(): ?string
public function getPrefix()
{
return $this->prefix;
}
@@ -147,7 +143,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, bool $merge = false): IRoute
public function setSettings(array $values, $merge = false)
{
if (isset($values['prefix']) === true) {
@@ -163,14 +159,11 @@ class RouteGroup extends Route implements IGroupRoute
}
if (isset($values['as']) === true) {
$name = $values['as'];
if ($this->name !== null && $merge !== false) {
$name .= '.' . $this->name;
$this->name = $values['as'] . '.' . $this->name;
} else {
$this->name = $values['as'];
}
$this->name = $name;
}
parent::setSettings($values, $merge);
@@ -183,7 +176,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function toArray(): array
public function toArray()
{
$values = [];
@@ -195,7 +188,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name;
}
if (\count($this->parameters) !== 0) {
if (count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters;
}
@@ -15,12 +15,8 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request
* @return bool
*/
public function matchRoute($url, Request $request): bool
public function matchRoute($url, Request $request)
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url);
+12 -16
View File
@@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
public function hasName(string $name): bool
public function hasName($name)
{
if ($this->name === null) {
return false;
@@ -60,7 +60,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return (strtolower($this->name) === strtolower($name));
}
public function findUrl($method = null, $parameters = null, $name = null): string
public function findUrl($method = null, $parameters = null, $name = null)
{
$url = array_search($name, $this->names, false);
if ($url !== false) {
@@ -77,12 +77,8 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return true;
}
public function matchRoute($url, Request $request): bool
public function matchRoute($url, Request $request)
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -114,7 +110,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
}
// Update
if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
return $this->call($this->methodNames['update']);
}
@@ -145,7 +141,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* @return string
*/
public function getController(): string
public function getController()
{
return $this->controller;
}
@@ -154,14 +150,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
public function setController(string $controller): IControllerRoute
public function setController($controller)
{
$this->controller = $controller;
return $this;
}
public function setName(string $name): ILoadableRoute
public function setName($name)
{
$this->name = $name;
@@ -194,9 +190,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* Get method names
*
* @return array
* @return array $this
*/
public function getMethodNames(): array
public function getMethodNames()
{
return $this->methodNames;
}
@@ -208,13 +204,13 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, bool $merge = false): IRoute
public function setSettings(array $values, $merge = false)
{
if (isset($values['names']) === true) {
if (isset($values['names'])) {
$this->names = $values['names'];
}
if (isset($values['methods']) === true) {
if (isset($values['methods'])) {
$this->methodNames = $values['methods'];
}
+1 -5
View File
@@ -12,12 +12,8 @@ class RouteUrl extends LoadableRoute
$this->setCallback($callback);
}
public function matchRoute($url, Request $request): bool
public function matchRoute($url, Request $request)
{
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
+160 -290
View File
@@ -2,7 +2,6 @@
namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\IExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
@@ -17,6 +16,12 @@ use Pecee\SimpleRouter\Route\IRoute;
class Router
{
/**
* The instance of this class
* @var static
*/
protected static $instance;
/**
* Current request
* @var Request
@@ -66,45 +71,12 @@ class Router
*/
protected $exceptionHandlers;
/**
* List of loaded exception that has been loaded.
* Used to ensure that exception-handlers aren't loaded twice when rewriting route.
*
* @var array
*/
protected $loadedExceptionHandlers;
/**
* Enable or disabled debugging
* @var bool
*/
protected $debugEnabled = false;
/**
* The start time used when debugging is enabled
* @var float
*/
protected $debugStartTime;
/**
* List containing all debug messages
* @var array
*/
protected $debugList = [];
/**
* Router constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function __construct()
{
$this->reset();
}
/**
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function reset(): void
public function reset()
{
$this->processingRoute = false;
$this->request = new Request();
@@ -113,7 +85,6 @@ class Router
$this->routeStack = [];
$this->processedRoutes = [];
$this->exceptionHandlers = [];
$this->loadedExceptionHandlers = [];
}
/**
@@ -121,76 +92,56 @@ class Router
* @param IRoute $route
* @return IRoute
*/
public function addRoute(IRoute $route): IRoute
public function addRoute(IRoute $route)
{
/*
* If a route is currently being processed, that means that the route being added are rendered from the parent
* routes callback, so we add them to the stack instead.
* If a route is currently being processed, that means that the
* route being added are rendered from the parent routes callback,
* so we add them to the stack instead.
*/
if ($this->processingRoute === true) {
$this->routeStack[] = $route;
return $route;
} else {
$this->routes[] = $route;
}
$this->routes[] = $route;
return $route;
}
/**
* Render and process any new routes added.
*
* @param IRoute $route
* @throws NotFoundHttpException
*/
protected function renderAndProcess(IRoute $route): void
{
$this->processingRoute = true;
$route->renderRoute($this->request, $this);
$this->processingRoute = false;
if (\count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
$this->routeStack = [];
/* Route any routes added to the stack */
$this->processRoutes($stack, $route);
}
}
/**
* Process added routes.
*
* @param array $routes
* @param IGroupRoute|null $group
* @param IRoute|null $parent
* @throws NotFoundHttpException
*/
protected function processRoutes(array $routes, ?IGroupRoute $group = null): void
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null)
{
$this->debug('Processing routes');
// Loop through each route-request
$max = count($routes) - 1;
$exceptionHandlers = [];
// Stop processing routes if no valid route is found.
if ($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
$this->debug('Halted route-processing as no valid route was found');
return;
}
$url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
/* @var $route IRoute */
foreach ($routes as $route) {
for ($i = $max; $i >= 0; $i--) {
$this->debug('Processing route "%s"', \get_class($route));
$route = $routes[$i];
if ($parent !== null) {
/* Add the parent route */
$route->setParent($parent);
/* Add/merge parent settings with child */
$route->setSettings($parent->toArray(), true);
}
if ($group !== null) {
/* Add the parent group */
$route->setGroup($group);
}
@@ -198,33 +149,47 @@ class Router
/* @var $route IGroupRoute */
if ($route instanceof IGroupRoute) {
$group = $route;
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
if (\count($route->getExceptionHandlers()) !== 0) {
if (count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers();
}
/* Only render partial group if it matches */
if ($route instanceof IPartialGroupRoute === true) {
$this->renderAndProcess($route);
if ($route instanceof IPartialGroupRoute) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
}
}
if ($route instanceof IPartialGroupRoute === false) {
$this->renderAndProcess($route);
if (($route instanceof IPartialGroupRoute) === false) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
}
continue;
}
if ($route instanceof ILoadableRoute === true) {
if ($route instanceof ILoadableRoute) {
/* Add the route to the map, so we can find the active one when all routes has been loaded */
$this->processedRoutes[] = $route;
}
if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
$this->routeStack = [];
/* Route any routes added to the stack */
$this->processRoutes($stack, $route, $group);
}
}
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
@@ -235,37 +200,27 @@ class Router
* @throws NotFoundHttpException
* @return void
*/
public function loadRoutes(): void
public function loadRoutes()
{
$this->debug('Loading routes');
/* Initialize boot-managers */
/* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) {
$this->debug('Rendering bootmanager %s', \get_class($manager));
$manager->boot($this->request);
$this->debug('Finished rendering bootmanager');
if (count($this->bootManagers) !== 0) {
$max = count($this->bootManagers) - 1;
/* @var $manager IRouterBootManager */
for ($i = $max; $i >= 0; $i--) {
$manager = $this->bootManagers[$i];
$manager->boot($this->request);
}
}
/* Loop through each route-request */
$this->processRoutes($this->routes);
$this->debug('Finished loading routes');
}
/**
* Routes the request
*
* @param bool $rewrite
* @return string|null
* @throws HttpException
* @throws \Exception
*/
public function routeRequest(bool $rewrite = false): ?string
public function routeRequest($rewrite = false)
{
$this->debug('Started routing request (rewrite: %s)', $rewrite === true ? 'yes' : 'no');
$methodNotAllowed = false;
$routeNotAllowed = false;
try {
@@ -279,45 +234,49 @@ class Router
}
}
$url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) {
for ($i = $max; $i >= 0; $i--) {
$this->debug('Matching route "%s"', \get_class($route));
$route = $this->processedRoutes[$i];
/* If the route matches */
if ($route->matchRoute($url, $this->request) === true) {
/* Check if request method matches */
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod());
$methodNotAllowed = true;
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
$routeNotAllowed = true;
continue;
}
$route->loadMiddleware($this->request, $this);
$route->loadMiddleware($this->request);
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
$rewriteRoute = $this->request->getRewriteRoute();
if ($rewriteRoute !== null) {
$rewriteRoute->loadMiddleware($this->request);
return $rewriteRoute->renderRoute($this->request);
}
/* If the request has changed */
$rewriteUrl = $this->request->getRewriteUrl();
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
unset($this->processedRoutes[$i]);
$this->processedRoutes = array_values($this->processedRoutes);
return $this->routeRequest(true);
}
/* Render route */
$methodNotAllowed = false;
$routeNotAllowed = false;
$this->request->setLoadedRoute($route);
$this->request->addLoadedRoute($route);
$output = $route->renderRoute($this->request, $this);
if ($output !== null) {
return $output;
}
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
}
return $route->renderRoute($this->request);
}
}
@@ -325,57 +284,22 @@ class Router
$this->handleException($e);
}
if ($methodNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
if ($routeNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUri()->getPath(), $this->request->getMethod());
$this->handleException(new HttpException($message, 403));
}
if (\count($this->request->getLoadedRoutes()) === 0) {
if ($this->request->getLoadedRoute() === null) {
$rewriteUrl = $this->request->getRewriteUrl();
if ($rewriteUrl !== null) {
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUrl()->getPath());
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUri()->getPath());
} else {
$message = sprintf('Route not found: "%s"', $this->request->getUrl()->getPath());
$message = sprintf('Route not found: "%s"', $this->request->getUri()->getPath());
}
$this->debug($message);
return $this->handleException(new NotFoundHttpException($message, 404));
}
return null;
}
/**
* Handle route-rewrite
*
* @param string $key
* @param string $url
* @return string|null
* @throws HttpException
* @throws \Exception
*/
protected function handleRouteRewrite($key, string $url): ?string
{
/* If the request has changed */
if ($this->request->hasRewrite() === false) {
return null;
}
$route = $this->request->getRewriteRoute();
if ($route !== null) {
/* Add rewrite route */
$this->processedRoutes[] = $route;
}
if ($this->request->getRewriteUrl() !== $url) {
unset($this->processedRoutes[$key]);
$this->request->setHasRewrite(false);
return $this->routeRequest(true);
$this->handleException(new NotFoundHttpException($message, 404));
}
return null;
@@ -385,53 +309,61 @@ class Router
* @param \Exception $e
* @throws HttpException
* @throws \Exception
* @return string|null
* @return string
*/
protected function handleException(\Exception $e): ?string
protected function handleException(\Exception $e)
{
$this->debug('Starting exception handling for "%s"', \get_class($e));
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
$max = count($this->exceptionHandlers);
/* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) {
for ($i = 0; $i < $max; $i++) {
if (\is_object($handler) === false) {
$handler = $this->exceptionHandlers[$i];
if (is_object($handler) === false) {
$handler = new $handler();
}
$this->debug('Processing exception-handler "%s"', \get_class($handler));
if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
}
try {
$this->debug('Start rendering exception handler');
$handler->handleError($this->request, $e);
$this->debug('Finished rendering exception-handler');
if ($handler->handleError($this->request, $e) !== null) {
if (isset($this->loadedExceptionHandlers[$key]) === false && $this->request->hasRewrite() === true) {
$this->loadedExceptionHandlers[$key] = $handler;
$rewriteRoute = $this->request->getRewriteRoute();
$this->debug('Exception handler contains rewrite, reloading routes');
if ($rewriteRoute !== null) {
$rewriteRoute->loadMiddleware($this->request);
return $this->routeRequest(true);
return $rewriteRoute->renderRoute($this->request);
}
$rewriteUrl = $this->request->getRewriteUrl();
/* If the request has changed */
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
unset($this->exceptionHandlers[$i]);
$this->exceptionHandlers = array_values($this->exceptionHandlers);
return $this->routeRequest(true);
}
}
} catch (\Exception $e) {
}
$this->debug('Finished processing');
}
$this->debug('Finished exception handling - exception not handled, throwing');
throw $e;
}
public function arrayToParams(array $getParams = [], bool $includeEmpty = true): string
public function arrayToParams(array $getParams = [], $includeEmpty = true)
{
if (\count($getParams) !== 0) {
if (count($getParams) !== 0) {
if ($includeEmpty === false) {
$getParams = array_filter($getParams, function ($item) {
@@ -451,60 +383,49 @@ class Router
* @param string $name
* @return ILoadableRoute|null
*/
public function findRoute(string $name): ?ILoadableRoute
public function findRoute($name)
{
$this->debug('Finding route by name "%s"', $name);
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
for ($i = $max; $i >= 0; $i--) {
$route = $this->processedRoutes[$i];
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
if ($route->hasName($name) === true) {
$this->debug('Found route "%s" by name "%s"', $route->getUrl(), $name);
if ($route->hasName($name)) {
return $route;
}
/* Direct match to controller */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) {
$this->debug('Found route "%s" by controller "%s"', $route->getUrl(), $name);
return $route;
}
/* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = array_map('strtolower', explode('@', $name));
if (is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
$this->debug('Found route "%s" by controller "%s" and method "%s"', $route->getUrl(), $controller, $method);
return $route;
}
}
/* Check if callback matches (if it's not a function) */
if (\is_string($name) === true && \is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && \is_callable($route->getCallback()) === false) {
if (is_string($name) === true && is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && is_callable($route->getCallback()) === false) {
/* Check if the entire callback is matching */
if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
$this->debug('Found route "%s" by callback "%s"', $route->getUrl(), $name);
return $route;
}
/* Check if the class part of the callback matches (class@method) */
if (strtolower($name) === strtolower($route->getClass())) {
$this->debug('Found route "%s" by class "%s"', $route->getUrl(), $name);
return $route;
}
}
}
$this->debug('Route not found');
return null;
}
@@ -523,15 +444,13 @@ class Router
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @throws InvalidArgumentException
* @throws \InvalidArgumentException
* @return string
*/
public function getUrl(?string $name = null, $parameters = null, $getParams = null): string
public function getUrl($name = null, $parameters = null, $getParams = null)
{
$this->debug('Finding url', \func_get_args());
if ($getParams !== null && \is_array($getParams) === false) {
throw new InvalidArgumentException('Invalid type for getParams. Must be array or null');
if ($getParams !== null && is_array($getParams) === false) {
throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null');
}
if ($name === '' && $parameters === '') {
@@ -547,7 +466,7 @@ class Router
/* Return current route if no options has been specified */
if ($name === null && $parameters === null) {
return $this->request->getUrl()->getPath() . $this->arrayToParams($getParams);
return $this->request->getUri()->getPath() . $this->arrayToParams($getParams);
}
$loadedRoute = $this->request->getLoadedRoute();
@@ -565,16 +484,20 @@ class Router
}
/* Using @ is most definitely a controller@method or alias@method */
if (\is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = explode('@', $name);
if (is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = explode('@', $name);
/* Loop through all the routes to see if we can find a match */
$max = count($this->processedRoutes) - 1;
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
for ($i = $max; $i >= 0; $i--) {
$route = $this->processedRoutes[$i];
/* Check if the route contains the name/alias */
if ($route->hasName($controller) === true) {
if ($route->hasName($controller)) {
return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams);
}
@@ -587,52 +510,42 @@ class Router
}
/* No result so we assume that someone is using a hardcoded url and join everything together. */
$url = trim(implode('/', array_merge((array)$name, (array)$parameters)), '/');
$url = trim(join('/', array_merge((array)$name, (array)$parameters)), '/');
return (($url === '') ? '/' : '/' . $url . '/') . $this->arrayToParams($getParams);
}
/**
* Get BootManagers
* Get bootmanagers
* @return array
*/
public function getBootManagers(): array
public function getBootManagers()
{
return $this->bootManagers;
}
/**
* Set BootManagers
* Set bootmanagers
* @param array $bootManagers
*/
public function setBootManagers(array $bootManagers): void
public function setBootManagers(array $bootManagers)
{
$this->bootManagers = $bootManagers;
}
/**
* Add BootManager
* Add bootmanager
* @param IRouterBootManager $bootManager
*/
public function addBootManager(IRouterBootManager $bootManager): void
public function addBootManager(IRouterBootManager $bootManager)
{
$this->bootManagers[] = $bootManager;
}
/**
* Get routes that has been processed.
*
* @return array
*/
public function getProcessedRoutes(): array
{
return $this->processedRoutes;
}
/**
* @return array
*/
public function getRoutes(): array
public function getRoutes()
{
return $this->routes;
}
@@ -641,9 +554,9 @@ class Router
* Set routes
*
* @param array $routes
* @return static
* @return static $this
*/
public function setRoutes(array $routes): self
public function setRoutes(array $routes)
{
$this->routes = $routes;
@@ -655,7 +568,7 @@ class Router
*
* @return Request
*/
public function getRequest(): Request
public function getRequest()
{
return $this->request;
}
@@ -664,7 +577,7 @@ class Router
* Get csrf verifier class
* @return BaseCsrfVerifier
*/
public function getCsrfVerifier(): ?BaseCsrfVerifier
public function getCsrfVerifier()
{
return $this->csrfVerifier;
}
@@ -682,47 +595,4 @@ class Router
return $this;
}
/**
* Add new debug message
* @param string $message
* @param array $args
*/
public function debug(string $message, ...$args): void
{
if ($this->debugEnabled === false) {
return;
}
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$this->debugList[] = [
'message' => vsprintf($message, $args),
'time' => number_format(microtime(true) - $this->debugStartTime, 10),
'trace' => end($trace),
];
}
/**
* Enable or disables debugging
*
* @param bool $boolean
*/
public function setDebugEnabled(bool $boolean): void
{
if ($boolean === true) {
$this->debugStartTime = microtime(true);
}
$this->debugEnabled = $boolean;
}
/**
* Get the list containing all debug messages.
*
* @return array
*/
public function getDebugLog(): array
{
return $this->debugList;
}
}
}
+40 -119
View File
@@ -10,18 +10,15 @@
namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\CallbackExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController;
use Pecee\SimpleRouter\Route\RouteGroup;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteResource;
use Pecee\SimpleRouter\Route\RouteUrl;
@@ -29,7 +26,7 @@ class SimpleRouter
{
/**
* Default namespace added to all routes
* @var string|null
* @var string
*/
protected static $defaultNamespace;
@@ -46,76 +43,22 @@ class SimpleRouter
protected static $router;
/**
* Start routing
* Start/route request
*
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws HttpException
* @throws \Exception
* @throws NotFoundHttpException
*/
public static function start(): void
public static function start()
{
echo static::router()->routeRequest();
}
/**
* Start the routing an return array with debugging-information
*
* @return array
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function startDebug(): array
{
$routerOutput = null;
try {
ob_start();
static::router()->setDebugEnabled(true);
static::start();
$routerOutput = ob_get_contents();
ob_end_clean();
} catch (\Exception $e) {
}
// Try to parse library version
$composerFile = \dirname(__DIR__, 3) . '/composer.lock';
$version = false;
if (is_file($composerFile) === true) {
$composerInfo = json_decode(file_get_contents($composerFile), true);
if (isset($composerInfo['packages']) === true && \is_array($composerInfo['packages']) === true) {
foreach ($composerInfo['packages'] as $package) {
if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') {
$version = $package['version'];
break;
}
}
}
}
return [
'url' => static::request()->getUrl(),
'method' => static::request()->getMethod(),
'host' => static::request()->getHost(),
'loaded_routes' => static::request()->getLoadedRoutes(),
'all_routes' => static::router()->getRoutes(),
'boot_managers' => static::router()->getBootManagers(),
'csrf_verifier' => static::router()->getCsrfVerifier(),
'log' => static::router()->getDebugLog(),
'router_output' => $routerOutput,
'library_version' => $version,
'php_version' => PHP_VERSION,
'server_params' => static::request()->getHeaders(),
];
}
/**
* Set default namespace which will be prepended to all routes.
*
* @param string $defaultNamespace
*/
public static function setDefaultNamespace(string $defaultNamespace): void
public static function setDefaultNamespace($defaultNamespace)
{
static::$defaultNamespace = $defaultNamespace;
}
@@ -124,9 +67,8 @@ class SimpleRouter
* Base CSRF verifier
*
* @param BaseCsrfVerifier $baseCsrfVerifier
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
{
static::router()->setCsrfVerifier($baseCsrfVerifier);
}
@@ -136,9 +78,8 @@ class SimpleRouter
* Perfect if you want to load pretty-urls from a file or database.
*
* @param IRouterBootManager $bootManager
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function addBootManager(IRouterBootManager $bootManager): void
public static function addBootManager(IRouterBootManager $bootManager)
{
static::router()->addBootManager($bootManager);
}
@@ -149,11 +90,9 @@ class SimpleRouter
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
*
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function get(string $url, $callback, array $settings = null): IRoute
public static function get($url, $callback, array $settings = null)
{
return static::match(['get'], $url, $callback, $settings);
}
@@ -165,9 +104,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function post(string $url, $callback, array $settings = null): IRoute
public static function post($url, $callback, array $settings = null)
{
return static::match(['post'], $url, $callback, $settings);
}
@@ -179,9 +117,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function put(string $url, $callback, array $settings = null): IRoute
public static function put($url, $callback, array $settings = null)
{
return static::match(['put'], $url, $callback, $settings);
}
@@ -193,9 +130,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function patch(string $url, $callback, array $settings = null): IRoute
public static function patch($url, $callback, array $settings = null)
{
return static::match(['patch'], $url, $callback, $settings);
}
@@ -207,9 +143,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function options(string $url, $callback, array $settings = null): IRoute
public static function options($url, $callback, array $settings = null)
{
return static::match(['options'], $url, $callback, $settings);
}
@@ -221,9 +156,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function delete(string $url, $callback, array $settings = null): IRoute
public static function delete($url, $callback, array $settings = null)
{
return static::match(['delete'], $url, $callback, $settings);
}
@@ -233,14 +167,13 @@ class SimpleRouter
*
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RouteGroup
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
public static function group(array $settings = [], \Closure $callback): IGroupRoute
public static function group(array $settings = [], \Closure $callback)
{
if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
if (is_callable($callback) === false) {
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
$group = new RouteGroup();
@@ -257,16 +190,15 @@ class SimpleRouter
* parameters and which are only rendered when the url matches.
*
* @param string $url
* @param \Closure $callback
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RoutePartialGroup
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException
*/
public static function partialGroup(string $url, \Closure $callback, array $settings = []): IPartialGroupRoute
public static function partialGroup($url, \Closure $callback, array $settings = [])
{
if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
if (is_callable($callback) === false) {
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
$settings['prefix'] = $url;
@@ -288,9 +220,8 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function basic(string $url, $callback, array $settings = null): IRoute
public static function basic($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
@@ -304,9 +235,8 @@ class SimpleRouter
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function form(string $url, $callback, array $settings = null): IRoute
public static function form($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
@@ -319,9 +249,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function match(array $requestMethods, string $url, $callback, array $settings = null)
public static function match(array $requestMethods, $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
@@ -343,9 +272,8 @@ class SimpleRouter
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function all(string $url, $callback, array $settings = null)
public static function all($url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route);
@@ -366,9 +294,8 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteController|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function controller(string $url, $controller, array $settings = null)
public static function controller($url, $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -389,9 +316,8 @@ class SimpleRouter
* @param string $controller
* @param array|null $settings
* @return RouteResource|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function resource(string $url, $controller, array $settings = null)
public static function resource($url, $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route);
@@ -410,9 +336,8 @@ class SimpleRouter
*
* @param \Closure $callback
* @return CallbackExceptionHandler $callbackHandler
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function error(\Closure $callback): CallbackExceptionHandler
public static function error(\Closure $callback)
{
$routes = static::router()->getRoutes();
@@ -443,11 +368,10 @@ class SimpleRouter
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @throws \Pecee\Exceptions\InvalidArgumentException
* @throws \Exception
* @return string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function getUrl(?string $name = null, $parameters = null, $getParams = null): string
public static function getUrl($name = null, $parameters = null, $getParams = null)
{
return static::router()->getUrl($name, $parameters, $getParams);
}
@@ -456,9 +380,8 @@ class SimpleRouter
* Get the request
*
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function request(): Request
public static function request()
{
return static::router()->getRequest();
}
@@ -467,9 +390,8 @@ class SimpleRouter
* Get the response object
*
* @return Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function response(): Response
public static function response()
{
if (static::$response === null) {
static::$response = new Response(static::request());
@@ -482,9 +404,8 @@ class SimpleRouter
* Returns the router instance
*
* @return Router
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function router(): Router
public static function router()
{
if (static::$router === null) {
static::$router = new Router();
@@ -499,14 +420,14 @@ class SimpleRouter
* @param IRoute $route
* @return IRoute
*/
public static function addDefaultNamespace(IRoute $route): IRoute
public static function addDefaultNamespace(IRoute $route)
{
if (static::$defaultNamespace !== null) {
$callback = $route->getCallback();
/* Only add default namespace on relative callbacks */
if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
if ($callback === null || (is_string($callback) === true && $callback[0] !== '\\')) {
$namespace = static::$defaultNamespace;
@@ -526,9 +447,9 @@ class SimpleRouter
/**
* Get default namespace
* @return string|null
* @return string
*/
public static function getDefaultNamespace(): ?string
public static function getDefaultNamespace()
{
return static::$defaultNamespace;
}
@@ -1,11 +1,11 @@
<?php
require_once 'Exception/MiddlewareLoadedException.php';
require_once 'Exceptions/MiddlewareLoadedException.php';
use Pecee\Http\Request;
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
{
public function handle(Request $request) : void
public function handle(Request $request)
{
throw new MiddlewareLoadedException('Middleware loaded!');
}
@@ -1,5 +1,4 @@
<?php
class ExceptionHandlerException extends \Exception
{
}
@@ -2,7 +2,7 @@
class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
echo $error->getMessage();
}
@@ -2,12 +2,13 @@
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
$request->setUrl('/');
$request->setUri(new \Pecee\Http\Uri('/'));
return $request;
}
}
@@ -2,12 +2,13 @@
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
$request->setUrl('/');
$request->setUri(new \Pecee\Http\Uri('/'));
return $request;
}
}
@@ -2,7 +2,7 @@
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
+39
View File
@@ -0,0 +1,39 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index()
{
echo 'index';
}
public function show($id)
{
echo 'show ' . $id;
}
public function store()
{
echo 'store';
}
public function create()
{
echo 'create';
}
public function edit($id)
{
echo 'edit ' . $id;
}
public function update($id)
{
echo 'update ' . $id;
}
public function destroy($id)
{
echo 'destroy ' . $id;
}
}
@@ -2,8 +2,9 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class GroupTest extends \PHPUnit\Framework\TestCase
class GroupTest extends PHPUnit_Framework_TestCase
{
protected $result;
@@ -36,7 +37,6 @@ class GroupTest extends \PHPUnit\Framework\TestCase
TestRouter::debug('/api/v1/test', 'get');
$this->assertTrue(true);
}
public function testMultipleRoutes()
@@ -61,8 +61,6 @@ class GroupTest extends \PHPUnit\Framework\TestCase
});
TestRouter::debug('/my/match', 'get');
$this->assertTrue(true);
}
public function testUrls()
@@ -3,18 +3,18 @@
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
{
public static function debugNoReset($testUrl, $testMethod = 'get')
public static function debugNoReset($testUri, $testMethod = 'get')
{
static::request()->setUrl($testUrl);
static::request()->setUri(new \Pecee\Http\Uri($testUri));
static::request()->setMethod($testMethod);
static::start();
}
public static function debug($testUrl, $testMethod = 'get')
public static function debug($testUri, $testMethod = 'get')
{
try {
static::debugNoReset($testUrl, $testMethod);
static::debugNoReset($testUri, $testMethod);
} catch(\Exception $e) {
static::router()->reset();
throw $e;
@@ -24,13 +24,13 @@ class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
}
public static function debugOutput($testUrl, $testMethod = 'get')
public static function debugOutput($testUri, $testMethod = 'get')
{
$response = null;
// Route request
ob_start();
static::debug($testUrl, $testMethod);
static::debug($testUri, $testMethod);
$response = ob_get_contents();
ob_end_clean();
@@ -3,12 +3,13 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class MiddlewareTest extends \PHPUnit\Framework\TestCase
class MiddlewareTest extends PHPUnit_Framework_TestCase
{
public function testMiddlewareFound()
{
$this->expectException(MiddlewareLoadedException::class);
$this->setExpectedException(MiddlewareLoadedException::class);
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
@@ -28,8 +29,6 @@ class MiddlewareTest extends \PHPUnit\Framework\TestCase
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
}
}
@@ -2,14 +2,15 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
{
public function testCallbackExceptionHandler()
{
$this->expectException(ExceptionHandlerException::class);
$this->setExpectedException(ExceptionHandlerException::class);
// Match normal route on alias
TestRouter::get('/my-new-url', 'DummyController@method2');
@@ -21,8 +22,6 @@ class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset();
$this->assertTrue(true);
}
}
@@ -1,8 +1,9 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class RouterControllerTest extends \PHPUnit\Framework\TestCase
class RouterControllerTest extends PHPUnit_Framework_TestCase
{
public function testGet()
@@ -3,8 +3,9 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterPartialGroupTest extends \PHPUnit\Framework\TestCase
class RouterPartialGroupTest extends PHPUnit_Framework_TestCase
{
public function testParameters()
@@ -1,8 +1,9 @@
<?php
require_once 'Dummy/ResourceController.php';
require_once 'Helpers/TestRouter.php';
class RouterResourceTest extends \PHPUnit\Framework\TestCase
class RouterResourceTest extends PHPUnit_Framework_TestCase
{
public function testResourceStore()
+78
View File
@@ -0,0 +1,78 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ResponseException.php';
require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php';
class RouteRewriteTest extends PHPUnit_Framework_TestCase
{
/**
* Redirects to another route through 3 exception handlers.
*
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
* the exceptionhandler is asking the router to reload.
*
* That means that the exceptionhandler is loaded again, but this time
* the router ignores the same rewrite-route to avoid loop - loads
* the second which have same behavior and is also ignored before
* throwing the final Exception in ExceptionHandler 3.
*
* So this tests:
* 1. If ExceptionHandlers loads
* 2. If ExceptionHandlers load in the correct order
* 3. If ExceptionHandlers can rewrite the page on error
* 4. If the router can avoid redirect-loop due to developer has started loop.
* 5. And finally if we reaches the last exception-handler and that the correct
* exception-type is being thrown.
*/
public function testExceptionHandlerRewrite()
{
global $stack;
$stack = [];
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () {
TestRouter::get('/my-path', 'DummyController@method1');
});
});
try {
TestRouter::debug('/my-non-existing-path', 'get');
} catch (\ResponseException $e) {
}
$expectedStack = [
ExceptionHandlerFirst::class,
ExceptionHandlerSecond::class,
ExceptionHandlerThird::class,
];
$this->assertEquals($expectedStack, $stack);
}
public function testRewriteExceptionMessage()
{
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
if (strtolower($request->getUri()->getPath()) == '/my/test') {
$request->setRewriteUrl('/another-non-existing');
return $request;
}
});
TestRouter::debug('/my/test', 'get');
}
}
@@ -2,9 +2,10 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterRouteTest extends \PHPUnit\Framework\TestCase
class RouterRouteTest extends PHPUnit_Framework_TestCase
{
protected $result = false;
@@ -26,7 +27,7 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
public function testNotFound()
{
$this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post');
}
@@ -35,32 +36,24 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
{
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
}
public function testPost()
{
TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post');
$this->assertTrue(true);
}
public function testPut()
{
TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'put');
$this->assertTrue(true);
}
public function testDelete()
{
TestRouter::delete('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'delete');
$this->assertTrue(true);
}
public function testMethodNotAllowed()
@@ -130,22 +123,6 @@ class RouterRouteTest extends \PHPUnit\Framework\TestCase
{
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get');
$this->assertTrue(true);
}
public function testParameterDefaultValue() {
$defaultVariable = null;
TestRouter::get('/my/{path?}', function($path = 'working') use(&$defaultVariable) {
$defaultVariable = $path;
});
TestRouter::debug('/my/');
$this->assertEquals('working', $defaultVariable);
}
public function testDefaultParameterRegex()
@@ -3,8 +3,9 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterUrlTest extends \PHPUnit\Framework\TestCase
class RouterUrlTest extends PHPUnit_Framework_TestCase
{
public function testIssue253()
@@ -31,22 +32,21 @@ class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
// Test spanish characters
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
TestRouter::debugNoReset('/test/Dermatología');
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
$this->assertEquals('Dermatología', $parameters['param']);
// Test danish characters
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
TestRouter::debugNoReset('/kategori/økse', 'get');
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
TestRouter::debugNoReset('/test/Dermatología');
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
$this->assertEquals('Dermatología', $parameters['param']);
TestRouter::router()->reset();
}
@@ -1,16 +0,0 @@
<?php
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware {
public function handle(Request $request) : void {
$request->setRewriteCallback(function() {
return 'ok';
});
}
}
@@ -1,46 +0,0 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index() : ?string
{
echo 'index';
return null;
}
public function show($id) : ?string
{
echo 'show ' . $id;
return null;
}
public function store() : ?string
{
echo 'store';
return null;
}
public function create() : ?string
{
echo 'create';
return null;
}
public function edit($id) : ?string
{
echo 'edit ' . $id;
return null;
}
public function update($id) : ?string
{
echo 'update ' . $id;
return null;
}
public function destroy($id) : ?string
{
echo 'destroy ' . $id;
return null;
}
}
@@ -1,176 +0,0 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exception/ResponseException.php';
require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Dummy/Middleware/RewriteMiddleware.php';
class RouteRewriteTest extends \PHPUnit\Framework\TestCase
{
/**
* Redirects to another route through 3 exception handlers.
*
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
* the exceptionhandler is asking the router to reload.
*
* That means that the exceptionhandler is loaded again, but this time
* the router ignores the same rewrite-route to avoid loop - loads
* the second which have same behavior and is also ignored before
* throwing the final Exception in ExceptionHandler 3.
*
* So this tests:
* 1. If ExceptionHandlers loads
* 2. If ExceptionHandlers load in the correct order
* 3. If ExceptionHandlers can rewrite the page on error
* 4. If the router can avoid redirect-loop due to developer has started loop.
* 5. And finally if we reaches the last exception-handler and that the correct
* exception-type is being thrown.
*/
public function testExceptionHandlerRewrite()
{
global $stack;
$stack = [];
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () use ($stack) {
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () use ($stack) {
TestRouter::get('/my-path', 'DummyController@method1');
});
});
try {
TestRouter::debug('/my-non-existing-path', 'get');
} catch (\ResponseException $e) {
}
$expectedStack = [
ExceptionHandlerFirst::class,
ExceptionHandlerSecond::class,
ExceptionHandlerThird::class,
];
$this->assertEquals($expectedStack, $stack);
}
public function testRewriteExceptionMessage()
{
$this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
if (strtolower($request->getUrl()->getPath()) === '/my/test/') {
$request->setRewriteUrl('/another-non-existing');
}
});
TestRouter::debug('/my/test', 'get');
}
public function testRewriteUrlFromRoute()
{
TestRouter::get('/old', function () {
TestRouter::request()->setRewriteUrl('/new');
});
TestRouter::get('/new', function () {
echo 'ok';
});
TestRouter::get('/new1', function () {
echo 'ok';
});
TestRouter::get('/new2', function () {
echo 'ok';
});
$output = TestRouter::debugOutput('/old');
$this->assertEquals('ok', $output);
}
public function testRewriteCallbackFromRoute()
{
TestRouter::get('/old', function () {
TestRouter::request()->setRewriteUrl('/new');
});
TestRouter::get('/new', function () {
return 'ok';
});
TestRouter::get('/new1', function () {
return 'fail';
});
TestRouter::get('/new/2', function () {
return 'fail';
});
$output = TestRouter::debugOutput('/old');
TestRouter::router()->reset();
$this->assertEquals('ok', $output);
}
public function testRewriteRouteFromRoute()
{
TestRouter::get('/match', function () {
TestRouter::request()->setRewriteRoute(new \Pecee\SimpleRouter\Route\RouteUrl('/match', function () {
return 'ok';
}));
});
TestRouter::get('/old1', function () {
return 'fail';
});
TestRouter::get('/old/2', function () {
return 'fail';
});
TestRouter::get('/new2', function () {
return 'fail';
});
$output = TestRouter::debugOutput('/match');
TestRouter::router()->reset();
$this->assertEquals('ok', $output);
}
public function testMiddlewareRewrite()
{
TestRouter::group(['middleware' => 'RewriteMiddleware'], function () {
TestRouter::get('/', function () {
return 'fail';
});
TestRouter::get('no/match', function () {
return 'fail';
});
});
$output = TestRouter::debugOutput('/');
$this->assertEquals('ok', $output);
}
}
-4
View File
@@ -1,4 +0,0 @@
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once 'TestRouter.php';
-9
View File
@@ -1,9 +0,0 @@
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
use \Pecee\SimpleRouter\SimpleRouter;
SimpleRouter::get('/user/{name}', 'UserController@show')->where(['name' => '[\w]+']);
$debugInfo = SimpleRouter::startDebug();
echo sprintf('<pre>%s</pre>', var_export($debugInfo, true));
exit;