Compare commits

..

4 Commits

Author SHA1 Message Date
Simon Sessingø 54ae830ec8 Merge pull request #386 from skipperbent/v4-php7-port
Version 4
2018-03-26 23:57:54 +02:00
Simon Sessingø 085f98cf08 Development
- Better php7 support.
- Added easier way to debug router.
- Improvements and bugfixes.
- Updated documentation.
2018-03-26 23:43:27 +02:00
Simon Sessingø f23d569757 Added support for PHP7 2018-03-20 03:38:55 +01:00
Simon Sessingo d279d5598d Development
- Fixed issue with subdomains on groups.
- Fixed issue with loadble routes sometimes mistakenly inheriting wrong group.
- Routes will now check if group matches before matching any custom regex.
- Added setValue method to IInputItem class to streamline the InputFile and InputItem classes.
- Other minor optimisations.
- Documentation: fixed broken links and cleaned it up.
2018-03-03 23:37:14 +01:00
64 changed files with 1529 additions and 738 deletions
+22
View File
@@ -0,0 +1,22 @@
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
@@ -0,0 +1,13 @@
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
@@ -0,0 +1,13 @@
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
+430 -45
View File
@@ -1,45 +1,18 @@
# Simple PHP router # 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.
**Note: this documentation is currently work-in-progress. Feel free to contribute.** 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.
### Notes **Please note that this documentation is currently work-in-progress. Feel free to contribute.**
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 ## Table of Contents
- [Getting started](#getting-started) - [Getting started](#getting-started)
- [Requirements](#requirements)
- [Notes](#notes-1) - [Notes](#notes-1)
- [Requirements](#requirements)
- [Feedback and development](#feedback-and-development)
- [Contribution development guidelines](#contribution-development-guidelines)
- [Features](#features) - [Features](#features)
- [Installation](#installation) - [Installation](#installation)
- [Setting up Apache](#setting-up-apache) - [Setting up Apache](#setting-up-apache)
@@ -47,7 +20,14 @@ For example when pushing changes to version 3, the pull request should use the `
- [Setting up IIS](#setting-up-iis) - [Setting up IIS](#setting-up-iis)
- [Configuration](#configuration) - [Configuration](#configuration)
- [Helper functions](#helper-functions) - [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) - [Routes](#routes)
- [Basic routing](#basic-routing) - [Basic routing](#basic-routing)
- [Available methods](#available-methods) - [Available methods](#available-methods)
@@ -99,8 +79,7 @@ For example when pushing changes to version 3, the pull request should use the `
- [Advanced](#advanced) - [Advanced](#advanced)
- [Url rewriting](#url-rewriting) - [Url rewriting](#url-rewriting)
- [Rewrite using callback](#rewrite-using-callback) - [Changing current route](#changing-current-route)
- [Rewrite using url](#rewrite-using-url)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically) - [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually) - [Adding routes manually](#adding-routes-manually)
- [Parameters](#parameters) - [Parameters](#parameters)
@@ -119,12 +98,10 @@ Add the latest version of Simple PHP Router running this command.
composer require pecee/simple-router composer require pecee/simple-router
``` ```
## Requirements
- PHP 5.5 or greater
## Notes ## 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.
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. 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.
Please note that the demo-project only covers how to integrate the `simple-php-router` in a project without an existing framework. If you are using a framework in your project, the implementation might vary. Please note that the demo-project only covers how to integrate the `simple-php-router` in a project without an existing framework. If you are using a framework in your project, the implementation might vary.
@@ -143,6 +120,32 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
- How to get ExceptionHandlers, Middlewares and Controllers working. - How to get ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers. - 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 ## Features
- Basic routing (`GET`, `POST`, `PUT`, `PATCH`, `UPDATE`, `DELETE`) with support for custom multiple verbs. - Basic routing (`GET`, `POST`, `PUT`, `PATCH`, `UPDATE`, `DELETE`) with support for custom multiple verbs.
@@ -207,7 +210,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. 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"?> <?xml version="1.0" encoding="UTF-8"?>
<configuration> <configuration>
<system.webServer> <system.webServer>
@@ -309,6 +312,8 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters * @param string|array|null $parameters
* @param array|null $getParams * @param array|null $getParams
* @return string * @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function url($name = null, $parameters = null, $getParams = null) function url($name = null, $parameters = null, $getParams = null)
{ {
@@ -317,6 +322,7 @@ function url($name = null, $parameters = null, $getParams = null)
/** /**
* @return \Pecee\Http\Response * @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function response() function response()
{ {
@@ -325,6 +331,7 @@ function response()
/** /**
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function request() function request()
{ {
@@ -336,15 +343,16 @@ function request()
* @param string|null $index Parameter index name * @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value * @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method * @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string * @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function input($index = null, $defaultValue = null, $methods = null) function input($index = null, $defaultValue = null, $methods = null)
{ {
if ($index !== null) { if ($index !== null) {
return request()->getInput()->get($index, $defaultValue, $methods); return request()->getInputHandler()->get($index, $defaultValue, $methods);
} }
return request()->getInput(); return request()->getInputHandler();
} }
function redirect($url, $code = null) function redirect($url, $code = null)
@@ -359,12 +367,13 @@ function redirect($url, $code = null)
/** /**
* Get current csrf-token * Get current csrf-token
* @return string|null * @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function csrf_token() function csrf_token()
{ {
$baseVerifier = Router::router()->getCsrfVerifier(); $baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) { if ($baseVerifier !== null) {
return $baseVerifier->getToken(); return $baseVerifier->getTokenProvider()->getToken();
} }
return null; return null;
@@ -373,6 +382,379 @@ 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 # Routes
Remember the ```routes.php``` file you required in your ```index.php```? This file be where you place all your custom rules for routing. Remember the ```routes.php``` file you required in your ```index.php```? This file be where you place all your custom rules for routing.
@@ -598,7 +980,7 @@ SimpleRouter::group(['namespace' => 'Admin'], function () {
}); });
``` ```
### Sub domain-routing ### Subdomain-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 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:
@@ -1135,6 +1517,9 @@ $siteId = input('site_id', 2, ['post', 'get']);
# Advanced # Advanced
## Url rewriting ## Url rewriting
### Changing current route
Sometimes it can be useful to manipulate the route about to be loaded. 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 manipulate and change the routes which are about to be rendered.
All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property. All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property.
+3 -2
View File
@@ -27,10 +27,11 @@
} }
], ],
"require": { "require": {
"php": ">=5.4.0" "php": ">=7.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "4.7.7" "phpunit/phpunit": "^6.0",
"mockery/mockery": "^1"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
+8 -3
View File
@@ -19,6 +19,7 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param array|null $getParams * @param array|null $getParams
* @return string * @return string
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function url($name = null, $parameters = null, $getParams = null) function url($name = null, $parameters = null, $getParams = null)
{ {
@@ -27,6 +28,7 @@ function url($name = null, $parameters = null, $getParams = null)
/** /**
* @return \Pecee\Http\Response * @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function response() function response()
{ {
@@ -35,6 +37,7 @@ function response()
/** /**
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function request() function request()
{ {
@@ -46,15 +49,16 @@ function request()
* @param string|null $index Parameter index name * @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value * @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method * @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string * @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function input($index = null, $defaultValue = null, $methods = null) function input($index = null, $defaultValue = null, $methods = null)
{ {
if ($index !== null) { if ($index !== null) {
return request()->getInput()->get($index, $defaultValue, $methods); return request()->getInputHandler()->get($index, $defaultValue, $methods);
} }
return request()->getInput(); return request()->getInputHandler();
} }
function redirect($url, $code = null) function redirect($url, $code = null)
@@ -69,6 +73,7 @@ function redirect($url, $code = null)
/** /**
* Get current csrf-token * Get current csrf-token
* @return string|null * @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
function csrf_token() function csrf_token()
{ {
+24
View File
@@ -0,0 +1,24 @@
<?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>
+15 -14
View File
@@ -1,47 +1,48 @@
<?php <?php
namespace Pecee\Controllers; namespace Pecee\Controllers;
interface IResourceController interface IResourceController
{ {
/** /**
* @return void * @return string|null
*/ */
public function index(); public function index(): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function show($id); public function show($id): ?string;
/** /**
* @return void * @return string|null
*/ */
public function store(); public function store(): ?string;
/** /**
* @return void * @return string|null
*/ */
public function create(); public function create(): ?string;
/** /**
* View * View
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function edit($id); public function edit($id): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function update($id); public function update($id): ?string;
/** /**
* @param mixed $id * @param mixed $id
* @return void * @return string|null
*/ */
public function destroy($id); public function destroy($id): ?string;
} }
@@ -1,6 +1,8 @@
<?php <?php
namespace Pecee\Exceptions; namespace Pecee\Exceptions;
class InvalidArgumentException extends \InvalidArgumentException { class InvalidArgumentException extends \InvalidArgumentException
{
} }
@@ -25,12 +25,11 @@ class CallbackExceptionHandler implements IExceptionHandler
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param \Exception $error
* @return Request|null
*/ */
public function handleError(Request $request, \Exception $error) public function handleError(Request $request, \Exception $error): void
{ {
/* Fire exceptions */ /* Fire exceptions */
return call_user_func($this->callback, \call_user_func($this->callback,
$request, $request,
$error $error
); );
+2 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Handlers; namespace Pecee\Handlers;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -8,8 +9,7 @@ interface IExceptionHandler
/** /**
* @param Request $request * @param Request $request
* @param \Exception $error * @param \Exception $error
* @return Request|null
*/ */
public function handleError(Request $request, \Exception $error); public function handleError(Request $request, \Exception $error): void;
} }
+8 -5
View File
@@ -1,18 +1,21 @@
<?php <?php
namespace Pecee\Http\Input; namespace Pecee\Http\Input;
interface IInputItem interface IInputItem
{ {
public function getIndex(); public function getIndex(): string;
public function setIndex($index); public function setIndex(string $index): self;
public function getName(); public function getName(): string;
public function setName($name); public function setName(string $name): self;
public function getValue(); public function getValue(): string;
public function setValue(string $value): self;
public function __toString(); public function __toString();
+42 -31
View File
@@ -14,7 +14,7 @@ class InputFile implements IInputItem
public $errors; public $errors;
public $tmpName; public $tmpName;
public function __construct($index) public function __construct(string $index)
{ {
$this->index = $index; $this->index = $index;
@@ -31,7 +31,7 @@ class InputFile implements IInputItem
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return static * @return static
*/ */
public static function createFromArray(array $values) public static function createFromArray(array $values): self
{ {
if (isset($values['index']) === false) { if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required'); throw new InvalidArgumentException('Index key is required');
@@ -48,7 +48,7 @@ class InputFile implements IInputItem
]; ];
return (new static($values['index'])) return (new static($values['index']))
->setSize($values['size']) ->setSize((int)$values['size'])
->setError($values['error']) ->setError($values['error'])
->setType($values['type']) ->setType($values['type'])
->setTmpName($values['tmp_name']) ->setTmpName($values['tmp_name'])
@@ -59,7 +59,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getIndex() public function getIndex(): string
{ {
return $this->index; return $this->index;
} }
@@ -67,9 +67,9 @@ class InputFile implements IInputItem
/** /**
* Set input index * Set input index
* @param string $index * @param string $index
* @return static $this * @return static
*/ */
public function setIndex($index) public function setIndex(string $index): IInputItem
{ {
$this->index = $index; $this->index = $index;
@@ -79,7 +79,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getSize() public function getSize(): string
{ {
return $this->size; return $this->size;
} }
@@ -87,9 +87,9 @@ class InputFile implements IInputItem
/** /**
* Set file size * Set file size
* @param int $size * @param int $size
* @return static $this * @return static
*/ */
public function setSize($size) public function setSize(int $size): IInputItem
{ {
$this->size = $size; $this->size = $size;
@@ -100,7 +100,7 @@ class InputFile implements IInputItem
* Get mime-type of file * Get mime-type of file
* @return string * @return string
*/ */
public function getMime() public function getMime(): string
{ {
return $this->getType(); return $this->getType();
} }
@@ -108,7 +108,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getType() public function getType(): string
{ {
return $this->type; return $this->type;
} }
@@ -116,9 +116,9 @@ class InputFile implements IInputItem
/** /**
* Set type * Set type
* @param string $type * @param string $type
* @return static $this * @return static
*/ */
public function setType($type) public function setType(string $type): IInputItem
{ {
$this->type = $type; $this->type = $type;
@@ -130,7 +130,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getExtension() public function getExtension(): string
{ {
return pathinfo($this->getFilename(), PATHINFO_EXTENSION); return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
} }
@@ -140,7 +140,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getName() public function getName(): string
{ {
return $this->name; return $this->name;
} }
@@ -150,9 +150,9 @@ class InputFile implements IInputItem
* Useful for adding validation etc. * Useful for adding validation etc.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name) public function setName(string $name): IInputItem
{ {
$this->name = $name; $this->name = $name;
@@ -163,9 +163,9 @@ class InputFile implements IInputItem
* Set filename * Set filename
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setFilename($name) public function setFilename($name): IInputItem
{ {
$this->filename = $name; $this->filename = $name;
@@ -177,7 +177,7 @@ class InputFile implements IInputItem
* *
* @return string mixed * @return string mixed
*/ */
public function getFilename() public function getFilename(): string
{ {
return $this->filename; return $this->filename;
} }
@@ -188,7 +188,7 @@ class InputFile implements IInputItem
* @param string $destination * @param string $destination
* @return bool * @return bool
*/ */
public function move($destination) public function move($destination): bool
{ {
return move_uploaded_file($this->tmpName, $destination); return move_uploaded_file($this->tmpName, $destination);
} }
@@ -198,7 +198,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getContents() public function getContents(): string
{ {
return file_get_contents($this->tmpName); return file_get_contents($this->tmpName);
} }
@@ -208,7 +208,7 @@ class InputFile implements IInputItem
* *
* @return bool * @return bool
*/ */
public function hasError() public function hasError(): bool
{ {
return ($this->getError() !== 0); return ($this->getError() !== 0);
} }
@@ -218,7 +218,7 @@ class InputFile implements IInputItem
* *
* @return string * @return string
*/ */
public function getError() public function getError(): string
{ {
return $this->errors; return $this->errors;
} }
@@ -227,9 +227,9 @@ class InputFile implements IInputItem
* Set error * Set error
* *
* @param int $error * @param int $error
* @return static $this * @return static
*/ */
public function setError($error) public function setError($error): IInputItem
{ {
$this->errors = (int)$error; $this->errors = (int)$error;
@@ -239,7 +239,7 @@ class InputFile implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getTmpName() public function getTmpName(): string
{ {
return $this->tmpName; return $this->tmpName;
} }
@@ -247,9 +247,9 @@ class InputFile implements IInputItem
/** /**
* Set file temp. name * Set file temp. name
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setTmpName($name) public function setTmpName($name): IInputItem
{ {
$this->tmpName = $name; $this->tmpName = $name;
@@ -261,12 +261,23 @@ class InputFile implements IInputItem
return $this->getTmpName(); return $this->getTmpName();
} }
public function getValue() public function getValue(): string
{ {
return $this->getFilename(); return $this->getFilename();
} }
public function toArray() /**
* @param string $value
* @return static
*/
public function setValue(string $value): IInputItem
{
$this->filename = $value;
return $this;
}
public function toArray(): array
{ {
return [ return [
'tmp_name' => $this->tmpName, 'tmp_name' => $this->tmpName,
@@ -5,7 +5,7 @@ namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request; use Pecee\Http\Request;
class Input class InputHandler
{ {
/** /**
* @var array * @var array
@@ -42,26 +42,26 @@ class Input
* Parse input values * Parse input values
* *
*/ */
public function parseInputs() public function parseInputs(): void
{ {
/* Parse get requests */ /* Parse get requests */
if (count($_GET) !== 0) { if (\count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET); $this->get = $this->handleGetPost($_GET);
} }
/* Parse post requests */ /* Parse post requests */
$postVars = $_POST; $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); parse_str(file_get_contents('php://input'), $postVars);
} }
if (count($postVars) !== 0) { if (\count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars); $this->post = $this->handleGetPost($postVars);
} }
/* Parse get requests */ /* Parse get requests */
if (count($_FILES) !== 0) { if (\count($_FILES) !== 0) {
$this->file = $this->parseFiles(); $this->file = $this->parseFiles();
} }
} }
@@ -69,18 +69,18 @@ class Input
/** /**
* @return array * @return array
*/ */
public function parseFiles() public function parseFiles(): array
{ {
$list = []; $list = [];
foreach ((array)$_FILES as $key => $value) { foreach ((array)$_FILES as $key => $value) {
// Handle array input // Handle array input
if (is_array($value['name']) === false) { if (\is_array($value['name']) === false) {
$values['index'] = $key; $values['index'] = $key;
try { try {
$list[$key] = InputFile::createFromArray($values + $value); $list[$key] = InputFile::createFromArray($values + $value);
} catch(InvalidArgumentException $e ){ } catch (InvalidArgumentException $e) {
} }
continue; continue;
@@ -101,7 +101,7 @@ class Input
return $list; return $list;
} }
protected function rearrangeFiles(array $values, &$index, $original) protected function rearrangeFiles(array $values, &$index, $original): array
{ {
$originalIndex = $index[0]; $originalIndex = $index[0];
@@ -111,7 +111,7 @@ class Input
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (is_array($original['name'][$key]) === false) { if (\is_array($original['name'][$key]) === false) {
try { try {
@@ -132,7 +132,7 @@ class Input
$output[$key] = $file; $output[$key] = $file;
continue; continue;
} catch(InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
} }
} }
@@ -152,14 +152,14 @@ class Input
return $output; return $output;
} }
protected function handleGetPost(array $array) protected function handleGetPost(array $array): array
{ {
$list = []; $list = [];
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
// Handle array input // Handle array input
if (is_array($value) === false) { if (\is_array($value) === false) {
$list[$key] = new InputItem($key, $value); $list[$key] = new InputItem($key, $value);
continue; continue;
} }
@@ -179,9 +179,9 @@ class Input
* @param string|null $defaultValue * @param string|null $defaultValue
* @return InputItem|string * @return InputItem|string
*/ */
public function findPost($index, $defaultValue = null) public function findPost(string $index, ?string $defaultValue = null)
{ {
return isset($this->post[$index]) ? $this->post[$index] : $defaultValue; return $this->post[$index] ?? $defaultValue;
} }
/** /**
@@ -191,9 +191,9 @@ class Input
* @param string|null $defaultValue * @param string|null $defaultValue
* @return InputFile|string * @return InputFile|string
*/ */
public function findFile($index, $defaultValue = null) public function findFile(string $index, ?string $defaultValue = null)
{ {
return isset($this->file[$index]) ? $this->file[$index] : $defaultValue; return $this->file[$index] ?? $defaultValue;
} }
/** /**
@@ -203,9 +203,9 @@ class Input
* @param string|null $defaultValue * @param string|null $defaultValue
* @return InputItem|string * @return InputItem|string
*/ */
public function findGet($index, $defaultValue = null) public function findGet(string $index, ?string $defaultValue = null)
{ {
return isset($this->get[$index]) ? $this->get[$index] : $defaultValue; return $this->get[$index] ?? $defaultValue;
} }
/** /**
@@ -216,27 +216,27 @@ class Input
* @param array|string|null $methods * @param array|string|null $methods
* @return IInputItem|string * @return IInputItem|string
*/ */
public function getObject($index, $defaultValue = null, $methods = null) public function getObject(string $index, ?string $defaultValue = null, $methods = null)
{ {
if ($methods !== null && is_string($methods) === true) { if ($methods !== null && \is_string($methods) === true) {
$methods = [$methods]; $methods = [$methods];
} }
$element = null; $element = null;
if ($methods === null || in_array('get', $methods, false) === true) { if ($methods === null || \in_array('get', $methods, true) === true) {
$element = $this->findGet($index); $element = $this->findGet($index);
} }
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) { if (($element === null && $methods === null) || ($methods !== null && \in_array('post', $methods, true) === true)) {
$element = $this->findPost($index); $element = $this->findPost($index);
} }
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) { if (($element === null && $methods === null) || ($methods !== null && \in_array('file', $methods, true) === true)) {
$element = $this->findFile($index); $element = $this->findFile($index);
} }
return ($element !== null) ? $element : $defaultValue; return $element ?? $defaultValue;
} }
/** /**
@@ -247,7 +247,7 @@ class Input
* @param array|string|null $methods * @param array|string|null $methods
* @return InputItem|string * @return InputItem|string
*/ */
public function get($index, $defaultValue = null, $methods = null) public function get(string $index, ?string $defaultValue = null, $methods = null)
{ {
$input = $this->getObject($index, $defaultValue, $methods); $input = $this->getObject($index, $defaultValue, $methods);
@@ -264,7 +264,7 @@ class Input
* @param string $index * @param string $index
* @return bool * @return bool
*/ */
public function exists($index) public function exists(string $index): bool
{ {
return ($this->getObject($index) !== null); return ($this->getObject($index) !== null);
} }
@@ -274,7 +274,7 @@ class Input
* @param array|null $filter Only take items in filter * @param array|null $filter Only take items in filter
* @return array * @return array
*/ */
public function all(array $filter = null) public function all(array $filter = null): array
{ {
$output = $_GET + $_POST; $output = $_GET + $_POST;
+10 -9
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Http\Input; namespace Pecee\Http\Input;
class InputItem implements IInputItem class InputItem implements IInputItem
@@ -7,7 +8,7 @@ class InputItem implements IInputItem
public $name; public $name;
public $value; public $value;
public function __construct($index, $value = null) public function __construct(string $index, ?string $value = null)
{ {
$this->index = $index; $this->index = $index;
$this->value = $value; $this->value = $value;
@@ -19,12 +20,12 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getIndex() public function getIndex(): string
{ {
return $this->index; return $this->index;
} }
public function setIndex($index) public function setIndex(string $index): IInputItem
{ {
$this->index = $index; $this->index = $index;
@@ -34,7 +35,7 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getName() public function getName(): string
{ {
return $this->name; return $this->name;
} }
@@ -42,9 +43,9 @@ class InputItem implements IInputItem
/** /**
* Set input name * Set input name
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name) public function setName(string $name): IInputItem
{ {
$this->name = $name; $this->name = $name;
@@ -54,7 +55,7 @@ class InputItem implements IInputItem
/** /**
* @return string * @return string
*/ */
public function getValue() public function getValue(): string
{ {
return $this->value; return $this->value;
} }
@@ -62,9 +63,9 @@ class InputItem implements IInputItem
/** /**
* Set input value * Set input value
* @param string $value * @param string $value
* @return static $this * @return static
*/ */
public function setValue($value) public function setValue(string $value): IInputItem
{ {
$this->value = $value; $this->value = $value;
+12 -12
View File
@@ -9,8 +9,8 @@ use Pecee\Http\Security\ITokenProvider;
class BaseCsrfVerifier implements IMiddleware class BaseCsrfVerifier implements IMiddleware
{ {
const POST_KEY = 'csrf-token'; public const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN'; public const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except; protected $except;
protected $tokenProvider; protected $tokenProvider;
@@ -29,21 +29,21 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
protected function skip(Request $request) protected function skip(Request $request): bool
{ {
if ($this->except === null || count($this->except) === 0) { if ($this->except === null || \count($this->except) === 0) {
return false; return false;
} }
$max = count($this->except) - 1; $max = \count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) { for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i]; $url = $this->except[$i];
$url = rtrim($url, '/'); $url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') { if ($url[\strlen($url) - 1] === '*') {
$url = rtrim($url, '*'); $url = rtrim($url, '*');
$skip = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0); $skip = $request->getUrl()->contains($url);
} else { } else {
$skip = ($url === $request->getUrl()->getOriginalUrl()); $skip = ($url === $request->getUrl()->getOriginalUrl());
} }
@@ -62,12 +62,12 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request * @param Request $request
* @throws TokenMismatchException * @throws TokenMismatchException
*/ */
public function handle(Request $request) public function handle(Request $request): void
{ {
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) { if ($this->skip($request) === false && \in_array($request->getMethod(), ['post', 'put', 'delete'], true) === true) {
$token = $request->getInput()->get(static::POST_KEY, null, 'post'); $token = $request->getInputHandler()->get(static::POST_KEY, null, 'post');
// If the token is not posted, check headers for valid x-csrf-token // If the token is not posted, check headers for valid x-csrf-token
if ($token === null) { if ($token === null) {
@@ -85,7 +85,7 @@ class BaseCsrfVerifier implements IMiddleware
} }
public function getTokenProvider() public function getTokenProvider(): ITokenProvider
{ {
return $this->tokenProvider; return $this->tokenProvider;
} }
@@ -94,7 +94,7 @@ class BaseCsrfVerifier implements IMiddleware
* Set token provider * Set token provider
* @param ITokenProvider $provider * @param ITokenProvider $provider
*/ */
public function setTokenProvider(ITokenProvider $provider) public function setTokenProvider(ITokenProvider $provider): void
{ {
$this->tokenProvider = $provider; $this->tokenProvider = $provider;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Http\Middleware\Exceptions; namespace Pecee\Http\Middleware\Exceptions;
class TokenMismatchException extends \Exception class TokenMismatchException extends \Exception
+2 -2
View File
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\Http\Middleware; namespace Pecee\Http\Middleware;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -7,8 +8,7 @@ interface IMiddleware
{ {
/** /**
* @param Request $request * @param Request $request
* @return Request|null
*/ */
public function handle(Request $request); public function handle(Request $request): void;
} }
+93 -71
View File
@@ -2,7 +2,7 @@
namespace Pecee\Http; namespace Pecee\Http;
use Pecee\Http\Input\Input; use Pecee\Http\Input\InputHandler;
use Pecee\SimpleRouter\Route\ILoadableRoute; use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl; use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter; use Pecee\SimpleRouter\SimpleRouter;
@@ -10,11 +10,11 @@ use Pecee\SimpleRouter\SimpleRouter;
class Request class Request
{ {
private $data = []; private $data = [];
protected $headers; protected $headers = [];
protected $host; protected $host;
protected $url; protected $url;
protected $method; protected $method;
protected $input; protected $inputHandler;
protected $hasRewrite = false; protected $hasRewrite = false;
@@ -25,9 +25,9 @@ class Request
protected $rewriteUrl; protected $rewriteUrl;
/** /**
* @var ILoadableRoute|null * @var array
*/ */
protected $loadedRoute; protected $loadedRoutes = [];
/** /**
* Request constructor. * Request constructor.
@@ -35,28 +35,21 @@ class Request
*/ */
public function __construct() public function __construct()
{ {
$this->parseHeaders();
$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->input = new Input($this);
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method')));
}
protected function parseHeaders()
{
$this->headers = [];
foreach ($_SERVER as $key => $value) { foreach ($_SERVER as $key => $value) {
$this->headers[strtolower($key)] = $value; $this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $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() public function isSecure(): bool
{ {
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443; return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
} }
@@ -64,23 +57,23 @@ class Request
/** /**
* @return Url * @return Url
*/ */
public function getUrl() public function getUrl(): Url
{ {
return $this->url; return $this->url;
} }
/** /**
* @return string * @return string|null
*/ */
public function getHost() public function getHost(): ?string
{ {
return $this->host; return $this->host;
} }
/** /**
* @return string * @return string|null
*/ */
public function getMethod() public function getMethod(): ?string
{ {
return $this->method; return $this->method;
} }
@@ -89,7 +82,7 @@ class Request
* Get http basic auth user * Get http basic auth user
* @return string|null * @return string|null
*/ */
public function getUser() public function getUser(): ?string
{ {
return $this->getHeader('php-auth-user'); return $this->getHeader('php-auth-user');
} }
@@ -98,7 +91,7 @@ class Request
* Get http basic auth password * Get http basic auth password
* @return string|null * @return string|null
*/ */
public function getPassword() public function getPassword(): ?string
{ {
return $this->getHeader('php-auth-pw'); return $this->getHeader('php-auth-pw');
} }
@@ -107,16 +100,16 @@ class Request
* Get all headers * Get all headers
* @return array * @return array
*/ */
public function getHeaders() public function getHeaders(): array
{ {
return $this->headers; return $this->headers;
} }
/** /**
* Get id address * Get id address
* @return string * @return string|null
*/ */
public function getIp() public function getIp(): ?string
{ {
if ($this->getHeader('http-cf-connecting-ip') !== null) { if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip'); return $this->getHeader('http-cf-connecting-ip');
@@ -133,27 +126,27 @@ class Request
* Get remote address/ip * Get remote address/ip
* *
* @alias static::getIp * @alias static::getIp
* @return string * @return string|null
*/ */
public function getRemoteAddr() public function getRemoteAddr(): ?string
{ {
return $this->getIp(); return $this->getIp();
} }
/** /**
* Get referer * Get referer
* @return string * @return string|null
*/ */
public function getReferer() public function getReferer(): ?string
{ {
return $this->getHeader('http-referer'); return $this->getHeader('http-referer');
} }
/** /**
* Get user agent * Get user agent
* @return string * @return string|null
*/ */
public function getUserAgent() public function getUserAgent(): ?string
{ {
return $this->getHeader('http-user-agent'); return $this->getHeader('http-user-agent');
} }
@@ -166,18 +159,18 @@ class Request
* *
* @return string|null * @return string|null
*/ */
public function getHeader($name, $defaultValue = null) public function getHeader($name, $defaultValue = null): ?string
{ {
return isset($this->headers[strtolower($name)]) ? $this->headers[strtolower($name)] : $defaultValue; return $this->headers[strtolower($name)] ?? $defaultValue;
} }
/** /**
* Get input class * Get input class
* @return Input * @return InputHandler
*/ */
public function getInput() public function getInputHandler(): InputHandler
{ {
return $this->input; return $this->inputHandler;
} }
/** /**
@@ -187,9 +180,9 @@ class Request
* *
* @return bool * @return bool
*/ */
public function isFormatAccepted($format) public function isFormatAccepted($format): bool
{ {
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1); return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) !== false);
} }
/** /**
@@ -197,7 +190,7 @@ class Request
* *
* @return bool * @return bool
*/ */
public function isAjax() public function isAjax(): bool
{ {
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest'); return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
} }
@@ -206,7 +199,7 @@ class Request
* Get accept formats * Get accept formats
* @return array * @return array
*/ */
public function getAcceptFormats() public function getAcceptFormats(): array
{ {
return explode(',', $this->getHeader('http-accept')); return explode(',', $this->getHeader('http-accept'));
} }
@@ -215,15 +208,15 @@ class Request
* @param string|Url $url * @param string|Url $url
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public function setUrl($url) public function setUrl($url): void
{ {
$this->url = ($url instanceof Url) ? $url : new Url($url); $this->url = ($url instanceof Url) ? $url : new Url($url);
} }
/** /**
* @param string $host * @param string|null $host
*/ */
public function setHost($host) public function setHost(?string $host): void
{ {
$this->host = $host; $this->host = $host;
} }
@@ -231,7 +224,7 @@ class Request
/** /**
* @param string $method * @param string $method
*/ */
public function setMethod($method) public function setMethod(string $method): void
{ {
$this->method = $method; $this->method = $method;
} }
@@ -242,7 +235,7 @@ class Request
* @param ILoadableRoute $route * @param ILoadableRoute $route
* @return static * @return static
*/ */
public function setRewriteRoute(ILoadableRoute $route) public function setRewriteRoute(ILoadableRoute $route): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route); $this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
@@ -255,7 +248,7 @@ class Request
* *
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function getRewriteRoute() public function getRewriteRoute(): ?ILoadableRoute
{ {
return $this->rewriteRoute; return $this->rewriteRoute;
} }
@@ -263,9 +256,9 @@ class Request
/** /**
* Get rewrite url * Get rewrite url
* *
* @return string * @return string|null
*/ */
public function getRewriteUrl() public function getRewriteUrl(): ?string
{ {
return $this->rewriteUrl; return $this->rewriteUrl;
} }
@@ -276,7 +269,7 @@ class Request
* @param string $rewriteUrl * @param string $rewriteUrl
* @return static * @return static
*/ */
public function setRewriteUrl($rewriteUrl) public function setRewriteUrl(string $rewriteUrl): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/'; $this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
@@ -286,10 +279,10 @@ class Request
/** /**
* Set rewrite callback * Set rewrite callback
* @param string $callback * @param string|\Closure $callback
* @return static * @return static
*/ */
public function setRewriteCallback($callback) public function setRewriteCallback($callback): self
{ {
$this->hasRewrite = true; $this->hasRewrite = true;
@@ -300,44 +293,73 @@ class Request
* Get loaded route * Get loaded route
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function getLoadedRoute() public function getLoadedRoute(): ?ILoadableRoute
{ {
return $this->loadedRoute; return (\count($this->loadedRoutes) > 0) ? end($this->loadedRoutes) : null;
} }
/** /**
* Set loaded route * 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
* *
* @param ILoadableRoute $route * @param ILoadableRoute $route
* @return static * @return static
*/ */
public function setLoadedRoute(ILoadableRoute $route) public function addLoadedRoute(ILoadableRoute $route): self
{ {
$this->loadedRoute = $route; $this->loadedRoutes[] = $route;
return $this; return $this;
} }
public function hasRewrite() /**
* Returns true if the request contains a rewrite
*
* @return bool
*/
public function hasRewrite(): bool
{ {
return $this->hasRewrite; return $this->hasRewrite;
} }
public function setHasRewrite($value) /**
* Defines if the current request contains a rewrite.
*
* @param bool $boolean
* @return Request
*/
public function setHasRewrite(bool $boolean): self
{ {
$this->hasRewrite = $value; $this->hasRewrite = $boolean;
return $this; return $this;
} }
public function isRewrite($url)
{
return ($this->rewriteUrl === $url);
}
public function __isset($name) public function __isset($name)
{ {
return array_key_exists($name, $this->data); return array_key_exists($name, $this->data) === true;
} }
public function __set($name, $value = null) public function __set($name, $value = null)
@@ -347,7 +369,7 @@ class Request
public function __get($name) public function __get($name)
{ {
return isset($this->data[$name]) ? $this->data[$name] : null; return $this->data[$name] ?? null;
} }
} }
+13 -14
View File
@@ -19,7 +19,7 @@ class Response
* @param int $code * @param int $code
* @return static * @return static
*/ */
public function httpCode($code) public function httpCode(int $code): self
{ {
http_response_code($code); http_response_code($code);
@@ -32,7 +32,7 @@ class Response
* @param string $url * @param string $url
* @param int $httpCode * @param int $httpCode
*/ */
public function redirect($url, $httpCode = null) public function redirect(string $url, ?int $httpCode = null): void
{ {
if ($httpCode !== null) { if ($httpCode !== null) {
$this->httpCode($httpCode); $this->httpCode($httpCode);
@@ -42,7 +42,7 @@ class Response
exit(0); exit(0);
} }
public function refresh() public function refresh(): void
{ {
$this->redirect($this->request->getUrl()->getOriginalUrl()); $this->redirect($this->request->getUrl()->getOriginalUrl());
} }
@@ -52,7 +52,7 @@ class Response
* @param string $name * @param string $name
* @return static * @return static
*/ */
public function auth($name = '') public function auth(string $name = ''): self
{ {
$this->headers([ $this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"', 'WWW-Authenticate: Basic realm="' . $name . '"',
@@ -62,23 +62,22 @@ class Response
return $this; return $this;
} }
public function cache($eTag, $lastModified = 2592000) public function cache(string $eTag, int $lastModifiedTime = 2592000): self
{ {
$this->headers([ $this->headers([
'Cache-Control: public', 'Cache-Control: public',
'Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT', sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
'Etag: ' . $eTag, sprintf('Etag: %s', $eTag),
]); ]);
$httpModified = $this->request->getHeader('http-if-modified-since'); $httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match'); $httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) { if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModifiedTime)) {
$this->header('HTTP/1.1 304 Not Modified'); $this->header('HTTP/1.1 304 Not Modified');
exit(0);
exit();
} }
return $this; return $this;
@@ -91,9 +90,9 @@ class Response
* @param int $dept JSON debt. * @param int $dept JSON debt.
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function json($value, $options = null, $dept = 512) public function json($value, ?int $options = null, int $dept = 512): void
{ {
if (($value instanceof \JsonSerializable) === false && is_array($value) === false) { 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.'); throw new InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
} }
@@ -107,7 +106,7 @@ class Response
* @param string $value * @param string $value
* @return static * @return static
*/ */
public function header($value) public function header(string $value): self
{ {
header($value); header($value);
@@ -119,7 +118,7 @@ class Response
* @param array $headers * @param array $headers
* @return static * @return static
*/ */
public function headers(array $headers) public function headers(array $headers): self
{ {
foreach ($headers as $header) { foreach ($headers as $header) {
$this->header($header); $this->header($header);
+16 -27
View File
@@ -6,7 +6,7 @@ use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider class CookieTokenProvider implements ITokenProvider
{ {
const CSRF_KEY = 'CSRF-TOKEN'; public const CSRF_KEY = 'CSRF-TOKEN';
protected $token; protected $token;
protected $cookieTimeoutMinutes = 120; protected $cookieTimeoutMinutes = 120;
@@ -30,24 +30,13 @@ class CookieTokenProvider implements ITokenProvider
* @return string * @return string
* @throws SecurityException * @throws SecurityException
*/ */
public function generateToken() public function generateToken(): string
{ {
if (function_exists('random_bytes') === true) { try {
try { return bin2hex(random_bytes(32));
return bin2hex(random_bytes(32)); } catch (\Exception $e) {
} catch(\Exception $e) { throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
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 SecurityException('IV generation failed');
}
return $random;
} }
/** /**
@@ -56,9 +45,9 @@ class CookieTokenProvider implements ITokenProvider
* @param string $token * @param string $token
* @return bool * @return bool
*/ */
public function validate($token) public function validate(string $token): bool
{ {
if ($token !== null && $this->getToken() !== null) { if ($this->getToken() !== null) {
return hash_equals($token, $this->getToken()); return hash_equals($token, $this->getToken());
} }
@@ -71,7 +60,7 @@ class CookieTokenProvider implements ITokenProvider
* *
* @param string $token * @param string $token
*/ */
public function setToken($token) public function setToken(string $token): void
{ {
$this->token = $token; $this->token = $token;
setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/'); setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
@@ -82,17 +71,17 @@ class CookieTokenProvider implements ITokenProvider
* @param string|null $defaultValue * @param string|null $defaultValue
* @return string|null * @return string|null
*/ */
public function getToken($defaultValue = null) public function getToken(?string $defaultValue = null): ?string
{ {
$this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null; $this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
return ($this->token !== null) ? $this->token : $defaultValue; return $this->token ?? $defaultValue;
} }
/** /**
* Refresh existing token * Refresh existing token
*/ */
public function refresh() public function refresh(): void
{ {
if ($this->token !== null) { if ($this->token !== null) {
$this->setToken($this->token); $this->setToken($this->token);
@@ -103,7 +92,7 @@ class CookieTokenProvider implements ITokenProvider
* Returns whether the csrf token has been defined * Returns whether the csrf token has been defined
* @return bool * @return bool
*/ */
public function hasToken() public function hasToken(): bool
{ {
return isset($_COOKIE[static::CSRF_KEY]); return isset($_COOKIE[static::CSRF_KEY]);
} }
@@ -112,16 +101,16 @@ class CookieTokenProvider implements ITokenProvider
* Get timeout for cookie in minutes * Get timeout for cookie in minutes
* @return int * @return int
*/ */
public function getCookieTimeoutMinutes() public function getCookieTimeoutMinutes(): int
{ {
return $this->cookieTimeoutMinutes; return $this->cookieTimeoutMinutes;
} }
/** /**
* Set cookie timeout in minutes * Set cookie timeout in minutes
* @param $minutes * @param int $minutes
*/ */
public function setCookieTimeoutMinutes($minutes) public function setCookieTimeoutMinutes(int $minutes): void
{ {
$this->cookieTimeoutMinutes = $minutes; $this->cookieTimeoutMinutes = $minutes;
} }
@@ -1,6 +1,8 @@
<?php <?php
namespace Pecee\Http\Security\Exceptions; namespace Pecee\Http\Security\Exceptions;
class SecurityException extends \Exception { class SecurityException extends \Exception
{
} }
+10 -2
View File
@@ -8,7 +8,7 @@ interface ITokenProvider
/** /**
* Refresh existing token * Refresh existing token
*/ */
public function refresh(); public function refresh(): void;
/** /**
* Validate valid CSRF token * Validate valid CSRF token
@@ -16,6 +16,14 @@ interface ITokenProvider
* @param string $token * @param string $token
* @return bool * @return bool
*/ */
public function validate($token); public function validate(string $token): bool;
/**
* Get token token
*
* @param string|null $defaultValue
* @return string|null
*/
public function getToken(?string $defaultValue = null): ?string;
} }
+45 -19
View File
@@ -23,22 +23,23 @@ class Url
* @param string $url * @param string $url
* @throws MalformedUrlException * @throws MalformedUrlException
*/ */
public function __construct($url) public function __construct(?string $url)
{ {
$this->originalUrl = $url; $this->originalUrl = $url;
$this->data = $this->parseUrl($url) + $this->data; if ($url !== null) {
$this->data = $this->parseUrl($url) + $this->data;
if (isset($this->data['path']) === true && $this->data['path'] !== '/') { if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
$this->data['path'] = rtrim($this->data['path'], '/') . '/'; $this->data['path'] = rtrim($this->data['path'], '/') . '/';
}
} }
} }
/** /**
* Check if url is using a secure protocol like https * Check if url is using a secure protocol like https
* @return bool * @return bool
*/ */
public function isSecure() public function isSecure(): bool
{ {
return (strtolower($this->getScheme()) === 'https'); return (strtolower($this->getScheme()) === 'https');
} }
@@ -47,7 +48,7 @@ class Url
* Checks if url is relative * Checks if url is relative
* @return bool * @return bool
*/ */
public function isRelative() public function isRelative(): bool
{ {
return ($this->getHost() === null); return ($this->getHost() === null);
} }
@@ -56,7 +57,7 @@ class Url
* Get url scheme * Get url scheme
* @return string|null * @return string|null
*/ */
public function getScheme() public function getScheme(): ?string
{ {
return $this->data['scheme']; return $this->data['scheme'];
} }
@@ -65,7 +66,7 @@ class Url
* Get url host * Get url host
* @return string|null * @return string|null
*/ */
public function getHost() public function getHost(): ?string
{ {
return $this->data['host']; return $this->data['host'];
} }
@@ -74,7 +75,7 @@ class Url
* Get url port * Get url port
* @return int|null * @return int|null
*/ */
public function getPort() public function getPort(): ?int
{ {
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null; return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
} }
@@ -83,7 +84,7 @@ class Url
* Parse username from url * Parse username from url
* @return string|null * @return string|null
*/ */
public function getUserName() public function getUserName(): ?string
{ {
return $this->data['user']; return $this->data['user'];
} }
@@ -92,7 +93,7 @@ class Url
* Parse password from url * Parse password from url
* @return string|null * @return string|null
*/ */
public function getPassword() public function getPassword(): ?string
{ {
return $this->data['pass']; return $this->data['pass'];
} }
@@ -101,16 +102,16 @@ class Url
* Get path from url * Get path from url
* @return string * @return string
*/ */
public function getPath() public function getPath(): ?string
{ {
return $this->data['path']; return $this->data['path'] ?? '/';
} }
/** /**
* Get querystring from url * Get querystring from url
* @return string|null * @return string|null
*/ */
public function getQueryString() public function getQueryString(): ?string
{ {
return $this->data['query']; return $this->data['query'];
} }
@@ -119,7 +120,7 @@ class Url
* Get fragment from url (everything after #) * Get fragment from url (everything after #)
* @return string|null * @return string|null
*/ */
public function getFragment() public function getFragment(): ?string
{ {
return $this->data['fragment']; return $this->data['fragment'];
} }
@@ -127,7 +128,7 @@ class Url
/** /**
* @return string * @return string
*/ */
public function getOriginalUrl() public function getOriginalUrl(): string
{ {
return $this->originalUrl; return $this->originalUrl;
} }
@@ -139,7 +140,7 @@ class Url
* @throws MalformedUrlException * @throws MalformedUrlException
* @return array * @return array
*/ */
public function parseUrl($url, $component = -1) public function parseUrl(string $url, int $component = -1): array
{ {
$encodedUrl = preg_replace_callback( $encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u', '/[^:\/@?&=#]+/u',
@@ -158,11 +159,36 @@ class Url
return array_map('urldecode', $parts); return array_map('urldecode', $parts);
} }
/**
* 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);
}
/** /**
* Returns data array with information about the url * Returns data array with information about the url
* @return array * @return array
*/ */
public function getData() public function getData(): array
{ {
return $this->data; return $this->data;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter\Exceptions; namespace Pecee\SimpleRouter\Exceptions;
class HttpException extends \Exception class HttpException extends \Exception
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter\Exceptions; namespace Pecee\SimpleRouter\Exceptions;
class NotFoundHttpException extends HttpException class NotFoundHttpException extends HttpException
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request; use Pecee\Http\Request;
@@ -9,7 +10,6 @@ interface IRouterBootManager
* Called when router loads it's routes * Called when router loads it's routes
* *
* @param Request $request * @param Request $request
* @return Request
*/ */
public function boot(Request $request); public function boot(Request $request): void;
} }
@@ -1,4 +1,5 @@
<?php <?php
namespace Pecee\SimpleRouter\Route; namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute interface IControllerRoute extends IRoute
@@ -8,7 +9,7 @@ interface IControllerRoute extends IRoute
* *
* @return string * @return string
*/ */
public function getController(); public function getController(): string;
/** /**
* Set controller class-name * Set controller class-name
@@ -16,21 +17,6 @@ interface IControllerRoute extends IRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller); public function setController(string $controller): self;
/**
* 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 * @param Request $request
* @return bool * @return bool
*/ */
public function matchDomain(Request $request); public function matchDomain(Request $request): bool;
/** /**
* Add exception handler * Add exception handler
* *
* @param IExceptionHandler|string $handler * @param IExceptionHandler|string $handler
* @return static $this; * @return static
*/ */
public function addExceptionHandler($handler); public function addExceptionHandler($handler): self;
/** /**
* Set exception-handlers for group * Set exception-handlers for group
* *
* @param array $handlers * @param array $handlers
* @return static $this * @return static
*/ */
public function setExceptionHandlers(array $handlers); public function setExceptionHandlers(array $handlers);
@@ -36,35 +36,35 @@ interface IGroupRoute extends IRoute
* *
* @return array * @return array
*/ */
public function getExceptionHandlers(); public function getExceptionHandlers(): array;
/** /**
* Get domains for domain. * Get domains for domain.
* *
* @return array * @return array
*/ */
public function getDomains(); public function getDomains(): array;
/** /**
* Set allowed domains for group. * Set allowed domains for group.
* *
* @param array $domains * @param array $domains
* @return $this * @return static
*/ */
public function setDomains(array $domains); public function setDomains(array $domains): self;
/** /**
* Set prefix that child-routes will inherit. * Set prefix that child-routes will inherit.
* *
* @param string $prefix * @param string $prefix
* @return string * @return static
*/ */
public function setPrefix($prefix); public function setPrefix($prefix): self;
/** /**
* Get prefix. * Get prefix.
* *
* @return string * @return string|null
*/ */
public function getPrefix(); public function getPrefix(): ?string;
} }
+24 -12
View File
@@ -1,7 +1,9 @@
<?php <?php
namespace Pecee\SimpleRouter\Route; namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface ILoadableRoute extends IRoute interface ILoadableRoute extends IRoute
{ {
@@ -14,25 +16,35 @@ interface ILoadableRoute extends IRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null); public function findUrl($method = null, $parameters = null, $name = null): string;
/** /**
* Loads and renders middlewares-classes * Loads and renders middleware-classes
* *
* @param Request $request * @param Request $request
* @param Router $router
*/ */
public function loadMiddleware(Request $request); public function loadMiddleware(Request $request, Router $router): void;
public function getUrl(); /**
* Get url
* @return string
*/
public function getUrl(): string;
public function setUrl($url); /**
* Set url
* @param string $url
* @return static
*/
public function setUrl(string $url): self;
/** /**
* Returns the provided name for the router. * Returns the provided name for the router.
* *
* @return string * @return string|null
*/ */
public function getName(); public function getName(): ?string;
/** /**
* Check if route has given name. * Check if route has given name.
@@ -40,22 +52,22 @@ interface ILoadableRoute extends IRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name); public function hasName(string $name): bool;
/** /**
* Sets the router name, which makes it easier to obtain the url or router at a later point. * Sets the router name, which makes it easier to obtain the url or router at a later point.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name); public function setName(string $name): self;
/** /**
* Get regular expression match used for matching route (if defined). * Get regular expression match used for matching route (if defined).
* *
* @return string * @return string
*/ */
public function getMatch(); public function getMatch(): ?string;
/** /**
* Add regular expression match for the entire route. * Add regular expression match for the entire route.
@@ -63,6 +75,6 @@ interface ILoadableRoute extends IRoute
* @param string $regex * @param string $regex
* @return static * @return static
*/ */
public function setMatch($regex); public function setMatch($regex): self;
} }
+58 -36
View File
@@ -3,6 +3,7 @@
namespace Pecee\SimpleRouter\Route; namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface IRoute interface IRoute
{ {
@@ -13,17 +14,18 @@ interface IRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($route, Request $request); public function matchRoute($route, Request $request): bool;
/** /**
* Called when route is matched. * Called when route is matched.
* Returns class to be rendered. * Returns class to be rendered.
* *
* @param Request $request * @param Request $request
* @param Router $router
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException * @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string * @return string
*/ */
public function renderRoute(Request $request); public function renderRoute(Request $request, Router $router): ?string;
/** /**
* Returns callback name/identifier for the current route based on the callback. * Returns callback name/identifier for the current route based on the callback.
@@ -32,50 +34,50 @@ interface IRoute
* *
* @return string * @return string
*/ */
public function getIdentifier(); public function getIdentifier(): string;
/** /**
* Set allowed request methods * Set allowed request methods
* *
* @param array $methods * @param array $methods
* @return static $this * @return static
*/ */
public function setRequestMethods(array $methods); public function setRequestMethods(array $methods): self;
/** /**
* Get allowed request methods * Get allowed request methods
* *
* @return array * @return array
*/ */
public function getRequestMethods(); public function getRequestMethods(): array;
/** /**
* @return IRoute|null * @return IRoute|null
*/ */
public function getParent(); public function getParent(): ?IRoute;
/** /**
* Get the group for the route. * Get the group for the route.
* *
* @return IGroupRoute|null * @return IGroupRoute|null
*/ */
public function getGroup(); public function getGroup(): ?IGroupRoute;
/** /**
* Set group * Set group
* *
* @param IGroupRoute $group * @param IGroupRoute $group
* @return static $this * @return static
*/ */
public function setGroup(IGroupRoute $group); public function setGroup(IGroupRoute $group): self;
/** /**
* Set parent route * Set parent route
* *
* @param IRoute $parent * @param IRoute $parent
* @return static $this * @return static
*/ */
public function setParent(IRoute $parent); public function setParent(IRoute $parent): self;
/** /**
* Set callback * Set callback
@@ -83,44 +85,64 @@ interface IRoute
* @param string $callback * @param string $callback
* @return static * @return static
*/ */
public function setCallback($callback); public function setCallback($callback): self;
/** /**
* @return string * @return string|callable
*/ */
public function getCallback(); public function getCallback();
public function getMethod(); /**
* Return active method
*
* @return string|null
*/
public function getMethod(): ?string;
public function getClass(); /**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod(string $method): self;
public function setMethod($method); /**
* Get class
*
* @return string|null
*/
public function getClass(): ?string;
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setNamespace($namespace); public function setNamespace(string $namespace): self;
/** /**
* @return string * @return string|null
*/ */
public function getNamespace(); public function getNamespace(): ?string;
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setDefaultNamespace($namespace); public function setDefaultNamespace($namespace): IRoute;
public function getDefaultNamespace(); /**
* Get default namespace
* @return string|null
*/
public function getDefaultNamespace(): ?string;
/** /**
* Get parameter names. * Get parameter names.
* *
* @return array * @return array
*/ */
public function getWhere(); public function getWhere(): array;
/** /**
* Set parameter names. * Set parameter names.
@@ -128,45 +150,45 @@ interface IRoute
* @param array $options * @param array $options
* @return static * @return static
*/ */
public function setWhere(array $options); public function setWhere(array $options): self;
/** /**
* Get parameters * Get parameters
* *
* @return array * @return array
*/ */
public function getParameters(); public function getParameters(): array;
/** /**
* Get parameters * Get parameters
* *
* @param array $parameters * @param array $parameters
* @return static $this * @return static
*/ */
public function setParameters(array $parameters); public function setParameters(array $parameters): self;
/** /**
* Merge with information from another route. * Merge with information from another route.
* *
* @param array $settings * @param array $settings
* @param bool $merge * @param bool $merge
* @return static $this * @return static
*/ */
public function setSettings(array $settings, $merge = false); public function setSettings(array $settings, bool $merge = false): self;
/** /**
* Export route settings to array so they can be merged with another route. * Export route settings to array so they can be merged with another route.
* *
* @return array * @return array
*/ */
public function toArray(); public function toArray(): array;
/** /**
* Get middlewares array * Get middlewares array
* *
* @return array * @return array
*/ */
public function getMiddlewares(); public function getMiddlewares(): array;
/** /**
* Set middleware class-name * Set middleware class-name
@@ -174,14 +196,14 @@ interface IRoute
* @param string $middleware * @param string $middleware
* @return static * @return static
*/ */
public function addMiddleware($middleware); public function addMiddleware($middleware): self;
/** /**
* Set middlewares array * Set middlewares array
* *
* @param array $middlewares * @param array $middlewares
* @return $this * @return static
*/ */
public function setMiddlewares(array $middlewares); public function setMiddlewares(array $middlewares): self;
} }
+29 -25
View File
@@ -5,6 +5,7 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware; use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Router;
abstract class LoadableRoute extends Route implements ILoadableRoute abstract class LoadableRoute extends Route implements ILoadableRoute
{ {
@@ -24,13 +25,16 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Loads and renders middlewares-classes * Loads and renders middlewares-classes
* *
* @param Request $request * @param Request $request
* @param Router $router
* @throws HttpException * @throws HttpException
*/ */
public function loadMiddleware(Request $request) public function loadMiddleware(Request $request, Router $router): void
{ {
$router->debug('Loading middlewares');
foreach ($this->getMiddlewares() as $middleware) { foreach ($this->getMiddlewares() as $middleware) {
if (is_object($middleware) === false) { if (\is_object($middleware) === false) {
$middleware = $this->loadClass($middleware); $middleware = $this->loadClass($middleware);
} }
@@ -38,11 +42,15 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
throw new HttpException($middleware . ' must be inherit the IMiddleware interface'); throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
} }
$router->debug('Loading middleware "%s"', \get_class($middleware));
$middleware->handle($request); $middleware->handle($request);
$router->debug('Finished loading middleware');
} }
$router->debug('Finished loading middlewares');
} }
public function matchRegex(Request $request, $url) public function matchRegex(Request $request, $url): ?bool
{ {
/* Match on custom defined regular expression */ /* Match on custom defined regular expression */
@@ -50,7 +58,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null; return null;
} }
return (preg_match($this->regex, $request->getHost() . $url) > 0); return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
} }
/** /**
@@ -59,7 +67,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $url * @param string $url
* @return static * @return static
*/ */
public function setUrl($url) public function setUrl(string $url): ILoadableRoute
{ {
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/'; $this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
@@ -67,7 +75,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]); $regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if (preg_match_all('/' . $regex . '/u', $this->url, $matches) > 0) { if ((bool)preg_match_all('/' . $regex . '/u', $this->url, $matches) !== false) {
$this->parameters = array_fill_keys($matches[1], null); $this->parameters = array_fill_keys($matches[1], null);
} }
} }
@@ -75,7 +83,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this; return $this;
} }
public function getUrl() public function getUrl(): string
{ {
return $this->url; return $this->url;
} }
@@ -89,13 +97,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null): string
{ {
$url = $this->getUrl(); $url = $this->getUrl();
$group = $this->getGroup(); $group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0) { if ($group !== null && \count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url; $url = '//' . $group->getDomains()[0] . $url;
} }
@@ -111,13 +119,10 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/* Replace any {parameter} in the url with the correct value */ /* Replace any {parameter} in the url with the correct value */
$params = $this->getParameters(); $params = $this->getParameters();
$max = count($params) - 1;
$keys = array_keys($params);
for ($i = $max; $i >= 0; $i--) { foreach (array_keys($params) as $param) {
$param = $keys[$i];
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) { if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) {
$value = ''; $value = '';
} else { } else {
$p = (array)$parameters; $p = (array)$parameters;
@@ -137,8 +142,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
} }
} }
$url = '/' . ltrim($url, '/'); $url = '/' . ltrim($url, '/') . implode('/', $unknownParams);
$url .= implode('/', $unknownParams);
return rtrim($url, '/') . '/'; return rtrim($url, '/') . '/';
} }
@@ -148,7 +152,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* *
* @return string * @return string
*/ */
public function getName() public function getName(): string
{ {
return $this->name; return $this->name;
} }
@@ -159,9 +163,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName(string $name): bool
{ {
return (strtolower($this->name) === strtolower($name)); return strtolower($this->name) === strtolower($name);
} }
/** /**
@@ -170,7 +174,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex * @param string $regex
* @return static * @return static
*/ */
public function setMatch($regex) public function setMatch($regex): ILoadableRoute
{ {
$this->regex = $regex; $this->regex = $regex;
@@ -182,7 +186,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* *
* @return string * @return string
*/ */
public function getMatch() public function getMatch(): string
{ {
return $this->regex; return $this->regex;
} }
@@ -195,7 +199,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|array $name * @param string|array $name
* @return static * @return static
*/ */
public function name($name) public function name($name): ILoadableRoute
{ {
return $this->setName($name); return $this->setName($name);
} }
@@ -204,9 +208,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. * Sets the router name, which makes it easier to obtain the url or router at a later point.
* *
* @param string $name * @param string $name
* @return static $this * @return static
*/ */
public function setName($name) public function setName(string $name): ILoadableRoute
{ {
$this->name = $name; $this->name = $name;
@@ -220,7 +224,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, bool $merge = false): IRoute
{ {
if (isset($values['as']) === true) { if (isset($values['as']) === true) {
+82 -69
View File
@@ -5,18 +5,19 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware; use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request; use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute abstract class Route implements IRoute
{ {
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s'; protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
const PARAMETERS_DEFAULT_REGEX = '[\w]+'; protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
const REQUEST_TYPE_GET = 'get'; public const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_POST = 'post'; public const REQUEST_TYPE_POST = 'post';
const REQUEST_TYPE_PUT = 'put'; public const REQUEST_TYPE_PUT = 'put';
const REQUEST_TYPE_PATCH = 'patch'; public const REQUEST_TYPE_PATCH = 'patch';
const REQUEST_TYPE_OPTIONS = 'options'; public const REQUEST_TYPE_OPTIONS = 'options';
const REQUEST_TYPE_DELETE = 'delete'; public const REQUEST_TYPE_DELETE = 'delete';
public static $requestTypes = [ public static $requestTypes = [
self::REQUEST_TYPE_GET, self::REQUEST_TYPE_GET,
@@ -59,10 +60,10 @@ abstract class Route implements IRoute
/** /**
* Load class by name * Load class by name
* @param string $name * @param string $name
* @return mixed * @return object
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
protected function loadClass($name) protected function loadClass($name): object
{ {
if (class_exists($name) === false) { if (class_exists($name) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404); throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404);
@@ -75,21 +76,25 @@ abstract class Route implements IRoute
* Render route * Render route
* *
* @param Request $request * @param Request $request
* @return string|mixed * @param Router $router
* @return string|null
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function renderRoute(Request $request) public function renderRoute(Request $request, Router $router): ?string
{ {
$router->debug('Starting rendering route');
$callback = $this->getCallback(); $callback = $this->getCallback();
if ($callback === null) { if ($callback === null) {
return null; return null;
} }
$router->debug('Parsing parameters');
$parameters = $this->getParameters(); $parameters = $this->getParameters();
$router->debug('Finished parsing parameters');
/* Filter parameters with null-value */ /* Filter parameters with null-value */
if ($this->filterEmptyParams === true) { if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) { $parameters = array_filter($parameters, function ($var) {
return ($var !== null); return ($var !== null);
@@ -97,9 +102,12 @@ abstract class Route implements IRoute
} }
/* Render callback function */ /* Render callback function */
if (is_callable($callback) === true) { if (\is_callable($callback) === true) {
$router->debug('Executing callback');
/* When the callback is a function */ /* When the callback is a function */
return call_user_func_array($callback, $parameters);
return \call_user_func_array($callback, $parameters);
} }
/* When the callback is a class + method */ /* When the callback is a class + method */
@@ -109,6 +117,7 @@ abstract class Route implements IRoute
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0]; $className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
$router->debug('Loading class %s', $className);
$class = $this->loadClass($className); $class = $this->loadClass($className);
$method = $controller[1]; $method = $controller[1];
@@ -116,7 +125,9 @@ abstract class Route implements IRoute
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404); throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
} }
return call_user_func_array([$class, $method], $parameters); $router->debug('Executing callback');
return \call_user_func_array([$class, $method], $parameters);
} }
protected function parseParameters($route, $url, $parameterRegex = null) protected function parseParameters($route, $url, $parameterRegex = null)
@@ -128,7 +139,9 @@ abstract class Route implements IRoute
// Ensures that hostnames/domains will work with parameters // Ensures that hostnames/domains will work with parameters
$url = '/' . ltrim($url, '/'); $url = '/' . ltrim($url, '/');
if (preg_match_all('/' . $regex . '/u', $route, $parameters) !== 0) { if ((bool)preg_match_all('/' . $regex . '/u', $route, $parameters) === false) {
$urlRegex = preg_quote($route, '/');
} else {
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route); $urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route);
@@ -136,7 +149,7 @@ abstract class Route implements IRoute
$regex = ''; $regex = '';
if ($key < count($parameters[1])) { if ($key < \count($parameters[1])) {
$name = $parameters[1][$key]; $name = $parameters[1][$key];
@@ -149,12 +162,11 @@ abstract class Route implements IRoute
if ($parameterRegex !== null) { if ($parameterRegex !== null) {
$regex = $parameterRegex; $regex = $parameterRegex;
} else { } else {
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex; $regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
} }
} }
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex); $regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
} }
$urlParts[$key] = preg_quote($t, '/') . $regex; $urlParts[$key] = preg_quote($t, '/') . $regex;
@@ -162,11 +174,9 @@ abstract class Route implements IRoute
$urlRegex = implode('', $urlParts); $urlRegex = implode('', $urlParts);
} else {
$urlRegex = preg_quote($route, '/');
} }
if (preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === 0) { if ((bool)preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === false) {
return null; return null;
} }
@@ -190,9 +200,9 @@ abstract class Route implements IRoute
* *
* @return string * @return string
*/ */
public function getIdentifier() public function getIdentifier(): string
{ {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
return $this->callback; return $this->callback;
} }
@@ -203,9 +213,9 @@ abstract class Route implements IRoute
* Set allowed request methods * Set allowed request methods
* *
* @param array $methods * @param array $methods
* @return static $this * @return static
*/ */
public function setRequestMethods(array $methods) public function setRequestMethods(array $methods): IRoute
{ {
$this->requestMethods = $methods; $this->requestMethods = $methods;
@@ -217,7 +227,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getRequestMethods() public function getRequestMethods(): array
{ {
return $this->requestMethods; return $this->requestMethods;
} }
@@ -225,7 +235,7 @@ abstract class Route implements IRoute
/** /**
* @return IRoute|null * @return IRoute|null
*/ */
public function getParent() public function getParent(): ?IRoute
{ {
return $this->parent; return $this->parent;
} }
@@ -235,7 +245,7 @@ abstract class Route implements IRoute
* *
* @return IGroupRoute|null * @return IGroupRoute|null
*/ */
public function getGroup() public function getGroup(): ?IGroupRoute
{ {
return $this->group; return $this->group;
} }
@@ -244,12 +254,15 @@ abstract class Route implements IRoute
* Set group * Set group
* *
* @param IGroupRoute $group * @param IGroupRoute $group
* @return static $this * @return static
*/ */
public function setGroup(IGroupRoute $group) public function setGroup(IGroupRoute $group): IRoute
{ {
$this->group = $group; $this->group = $group;
/* Add/merge parent settings with child */
$this->setSettings($group->toArray(), true);
return $this; return $this;
} }
@@ -257,9 +270,9 @@ abstract class Route implements IRoute
* Set parent route * Set parent route
* *
* @param IRoute $parent * @param IRoute $parent
* @return static $this * @return static
*/ */
public function setParent(IRoute $parent) public function setParent(IRoute $parent): IRoute
{ {
$this->parent = $parent; $this->parent = $parent;
@@ -272,7 +285,7 @@ abstract class Route implements IRoute
* @param string $callback * @param string $callback
* @return static * @return static
*/ */
public function setCallback($callback) public function setCallback($callback): IRoute
{ {
$this->callback = $callback; $this->callback = $callback;
@@ -280,16 +293,16 @@ abstract class Route implements IRoute
} }
/** /**
* @return string * @return string|callable
*/ */
public function getCallback() public function getCallback()
{ {
return $this->callback; return $this->callback;
} }
public function getMethod() public function getMethod(): ?string
{ {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback); $tmp = explode('@', $this->callback);
return $tmp[1]; return $tmp[1];
@@ -298,9 +311,9 @@ abstract class Route implements IRoute
return null; return null;
} }
public function getClass() public function getClass(): ?string
{ {
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) { if (\is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback); $tmp = explode('@', $this->callback);
return $tmp[0]; return $tmp[0];
@@ -309,14 +322,14 @@ abstract class Route implements IRoute
return null; return null;
} }
public function setMethod($method) public function setMethod(string $method): IRoute
{ {
$this->callback = sprintf('%s@%s', $this->getClass(), $method); $this->callback = sprintf('%s@%s', $this->getClass(), $method);
return $this; return $this;
} }
public function setClass($class) public function setClass(string $class): IRoute
{ {
$this->callback = sprintf('%s@%s', $class, $this->getMethod()); $this->callback = sprintf('%s@%s', $class, $this->getMethod());
@@ -325,9 +338,9 @@ abstract class Route implements IRoute
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setNamespace($namespace) public function setNamespace(string $namespace): IRoute
{ {
$this->namespace = $namespace; $this->namespace = $namespace;
@@ -336,26 +349,26 @@ abstract class Route implements IRoute
/** /**
* @param string $namespace * @param string $namespace
* @return static $this * @return static
*/ */
public function setDefaultNamespace($namespace) public function setDefaultNamespace($namespace): IRoute
{ {
$this->defaultNamespace = $namespace; $this->defaultNamespace = $namespace;
return $this; return $this;
} }
public function getDefaultNamespace() public function getDefaultNamespace(): ?string
{ {
return $this->defaultNamespace; return $this->defaultNamespace;
} }
/** /**
* @return string * @return string|null
*/ */
public function getNamespace() public function getNamespace(): ?string
{ {
return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace; return $this->namespace ?? $this->defaultNamespace;
} }
/** /**
@@ -363,7 +376,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function toArray() public function toArray(): array
{ {
$values = []; $values = [];
@@ -371,15 +384,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace; $values['namespace'] = $this->namespace;
} }
if (count($this->requestMethods) !== 0) { if (\count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods; $values['method'] = $this->requestMethods;
} }
if (count($this->where) !== 0) { if (\count($this->where) !== 0) {
$values['where'] = $this->where; $values['where'] = $this->where;
} }
if (count($this->middlewares) !== 0) { if (\count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares; $values['middleware'] = $this->middlewares;
} }
@@ -395,9 +408,9 @@ abstract class Route implements IRoute
* *
* @param array $values * @param array $values
* @param bool $merge * @param bool $merge
* @return static $this * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, bool $merge = false): IRoute
{ {
if ($this->namespace === null && isset($values['namespace']) === true) { if ($this->namespace === null && isset($values['namespace']) === true) {
$this->setNamespace($values['namespace']); $this->setNamespace($values['namespace']);
@@ -432,7 +445,7 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getWhere() public function getWhere(): array
{ {
return $this->where; return $this->where;
} }
@@ -443,7 +456,7 @@ abstract class Route implements IRoute
* @param array $options * @param array $options
* @return static * @return static
*/ */
public function setWhere(array $options) public function setWhere(array $options): IRoute
{ {
$this->where = $options; $this->where = $options;
@@ -468,12 +481,12 @@ abstract class Route implements IRoute
* *
* @return array * @return array
*/ */
public function getParameters() public function getParameters(): array
{ {
/* Sort the parameters after the user-defined param order, if any */ /* Sort the parameters after the user-defined param order, if any */
$parameters = []; $parameters = [];
if (count($this->originalParameters) !== 0) { if (\count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters; $parameters = $this->originalParameters;
} }
@@ -484,15 +497,15 @@ abstract class Route implements IRoute
* Get parameters * Get parameters
* *
* @param array $parameters * @param array $parameters
* @return static $this * @return static
*/ */
public function setParameters(array $parameters) public function setParameters(array $parameters): IRoute
{ {
/* /*
* If this is the first time setting parameters we store them so we * 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. * 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; $this->originalParameters = $parameters;
} }
@@ -521,7 +534,7 @@ abstract class Route implements IRoute
* @param IMiddleware|string $middleware * @param IMiddleware|string $middleware
* @return static * @return static
*/ */
public function addMiddleware($middleware) public function addMiddleware($middleware): IRoute
{ {
$this->middlewares[] = $middleware; $this->middlewares[] = $middleware;
@@ -532,9 +545,9 @@ abstract class Route implements IRoute
* Set middlewares array * Set middlewares array
* *
* @param array $middlewares * @param array $middlewares
* @return $this * @return static
*/ */
public function setMiddlewares(array $middlewares) public function setMiddlewares(array $middlewares): IRoute
{ {
$this->middlewares = $middlewares; $this->middlewares = $middlewares;
@@ -544,7 +557,7 @@ abstract class Route implements IRoute
/** /**
* @return array * @return array
*/ */
public function getMiddlewares() public function getMiddlewares(): array
{ {
return $this->middlewares; return $this->middlewares;
} }
@@ -554,7 +567,7 @@ abstract class Route implements IRoute
* This is used when no custom parameter regex is found. * This is used when no custom parameter regex is found.
* *
* @param string $regex * @param string $regex
* @return static $this * @return static
*/ */
public function setDefaultParameterRegex($regex) public function setDefaultParameterRegex($regex)
{ {
@@ -568,7 +581,7 @@ abstract class Route implements IRoute
* *
* @return string * @return string
*/ */
public function getDefaultParameterRegex() public function getDefaultParameterRegex(): string
{ {
return $this->defaultParameterRegex; return $this->defaultParameterRegex;
} }
@@ -24,7 +24,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName(string $name): bool
{ {
if ($this->name === null) { if ($this->name === null) {
return false; return false;
@@ -35,7 +35,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1); $method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.')); $newName = substr($name, 0, strrpos($name, '.'));
if (in_array($method, $this->names, false) === true && strtolower($this->name) === strtolower($newName)) { if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true; return true;
} }
} }
@@ -49,7 +49,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string|null $name * @param string|null $name
* @return string * @return string
*/ */
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null): string
{ {
if (strpos($name, '.') !== false) { if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false); $found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
@@ -67,7 +67,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
foreach (static::$requestTypes as $requestType) { foreach (static::$requestTypes as $requestType) {
if (stripos($method, $requestType) === 0) { if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, strlen($requestType)); $method = (string)substr($method, \strlen($requestType));
break; break;
} }
} }
@@ -77,7 +77,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup(); $group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0) { if ($group !== null && \count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0]; $url .= '//' . $group->getDomains()[0];
} }
@@ -86,8 +86,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
return '/' . trim($url, '/') . '/'; return '/' . trim($url, '/') . '/';
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */ /* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url); $regexMatch = $this->matchRegex($request, $url);
@@ -98,12 +102,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/'); $strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl); $path = explode('/', $strippedUrl);
if (count($path) !== 0) { if (\count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0]; $method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method); $this->method = $request->getMethod() . ucfirst($method);
$this->parameters = array_slice($path, 1); $this->parameters = \array_slice($path, 1);
// Set callback // Set callback
$this->setCallback($this->controller . '@' . $this->method); $this->setCallback($this->controller . '@' . $this->method);
@@ -119,7 +123,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* *
* @return string * @return string
*/ */
public function getController() public function getController(): string
{ {
return $this->controller; return $this->controller;
} }
@@ -130,7 +134,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller) public function setController(string $controller): IControllerRoute
{ {
$this->controller = $controller; $this->controller = $controller;
@@ -140,9 +144,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
/** /**
* Return active method * Return active method
* *
* @return string * @return string|null
*/ */
public function getMethod() public function getMethod(): ?string
{ {
return $this->method; return $this->method;
} }
@@ -153,7 +157,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $method * @param string $method
* @return static * @return static
*/ */
public function setMethod($method) public function setMethod(string $method): IRoute
{ {
$this->method = $method; $this->method = $method;
@@ -167,7 +171,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, bool $merge = false): IRoute
{ {
if (isset($values['names']) === true) { if (isset($values['names']) === true) {
$this->names = $values['names']; $this->names = $values['names'];
+22 -18
View File
@@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchDomain(Request $request) public function matchDomain(Request $request): bool
{ {
if ($this->domains === null || count($this->domains) === 0) { if ($this->domains === null || \count($this->domains) === 0) {
return true; return true;
} }
@@ -28,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute
$parameters = $this->parseParameters($domain, $request->getHost(), '.*'); $parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && count($parameters) !== 0) { if ($parameters !== null && \count($parameters) !== 0) {
$this->parameters = $parameters; $this->parameters = $parameters;
@@ -46,8 +46,12 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Skip if prefix doesn't match */ /* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) { if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
return false; return false;
@@ -60,9 +64,9 @@ class RouteGroup extends Route implements IGroupRoute
* Add exception handler * Add exception handler
* *
* @param IExceptionHandler|string $handler * @param IExceptionHandler|string $handler
* @return static $this * @return static
*/ */
public function addExceptionHandler($handler) public function addExceptionHandler($handler): IGroupRoute
{ {
$this->exceptionHandlers[] = $handler; $this->exceptionHandlers[] = $handler;
@@ -73,9 +77,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set exception-handlers for group * Set exception-handlers for group
* *
* @param array $handlers * @param array $handlers
* @return static $this * @return static
*/ */
public function setExceptionHandlers(array $handlers) public function setExceptionHandlers(array $handlers): IGroupRoute
{ {
$this->exceptionHandlers = $handlers; $this->exceptionHandlers = $handlers;
@@ -87,7 +91,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function getExceptionHandlers() public function getExceptionHandlers(): array
{ {
return $this->exceptionHandlers; return $this->exceptionHandlers;
} }
@@ -97,7 +101,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function getDomains() public function getDomains(): array
{ {
return $this->domains; return $this->domains;
} }
@@ -106,9 +110,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set allowed domains for group. * Set allowed domains for group.
* *
* @param array $domains * @param array $domains
* @return $this * @return static
*/ */
public function setDomains(array $domains) public function setDomains(array $domains): IGroupRoute
{ {
$this->domains = $domains; $this->domains = $domains;
@@ -119,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix * @param string $prefix
* @return static * @return static
*/ */
public function setPrefix($prefix) public function setPrefix($prefix): IGroupRoute
{ {
$this->prefix = '/' . trim($prefix, '/'); $this->prefix = '/' . trim($prefix, '/');
@@ -129,9 +133,9 @@ class RouteGroup extends Route implements IGroupRoute
/** /**
* Set prefix that child-routes will inherit. * Set prefix that child-routes will inherit.
* *
* @return string * @return string|null
*/ */
public function getPrefix() public function getPrefix(): ?string
{ {
return $this->prefix; return $this->prefix;
} }
@@ -143,7 +147,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, bool $merge = false): IRoute
{ {
if (isset($values['prefix']) === true) { if (isset($values['prefix']) === true) {
@@ -179,7 +183,7 @@ class RouteGroup extends Route implements IGroupRoute
* *
* @return array * @return array
*/ */
public function toArray() public function toArray(): array
{ {
$values = []; $values = [];
@@ -191,7 +195,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name; $values['as'] = $this->name;
} }
if (count($this->parameters) !== 0) { if (\count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters; $values['parameters'] = $this->parameters;
} }
@@ -15,8 +15,12 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request * @param Request $request
* @return bool * @return bool
*/ */
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
if ($this->prefix !== null) { if ($this->prefix !== null) {
/* Parse parameters from current route */ /* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url); $parameters = $this->parseParameters($this->prefix, $url);
+14 -10
View File
@@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $name * @param string $name
* @return bool * @return bool
*/ */
public function hasName($name) public function hasName(string $name): bool
{ {
if ($this->name === null) { if ($this->name === null) {
return false; return false;
@@ -60,7 +60,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return (strtolower($this->name) === strtolower($name)); return (strtolower($this->name) === strtolower($name));
} }
public function findUrl($method = null, $parameters = null, $name = null) public function findUrl($method = null, $parameters = null, $name = null): string
{ {
$url = array_search($name, $this->names, false); $url = array_search($name, $this->names, false);
if ($url !== false) { if ($url !== false) {
@@ -77,8 +77,12 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return true; return true;
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */ /* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url); $regexMatch = $this->matchRegex($request, $url);
@@ -110,7 +114,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
} }
// Update // Update
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) { if ($id !== null && \in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], true) === true) {
return $this->call($this->methodNames['update']); return $this->call($this->methodNames['update']);
} }
@@ -141,7 +145,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/** /**
* @return string * @return string
*/ */
public function getController() public function getController(): string
{ {
return $this->controller; return $this->controller;
} }
@@ -150,14 +154,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $controller * @param string $controller
* @return static * @return static
*/ */
public function setController($controller) public function setController(string $controller): IControllerRoute
{ {
$this->controller = $controller; $this->controller = $controller;
return $this; return $this;
} }
public function setName($name) public function setName(string $name): ILoadableRoute
{ {
$this->name = $name; $this->name = $name;
@@ -190,9 +194,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/** /**
* Get method names * Get method names
* *
* @return array $this * @return array
*/ */
public function getMethodNames() public function getMethodNames(): array
{ {
return $this->methodNames; return $this->methodNames;
} }
@@ -204,7 +208,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param bool $merge * @param bool $merge
* @return static * @return static
*/ */
public function setSettings(array $values, $merge = false) public function setSettings(array $values, bool $merge = false): IRoute
{ {
if (isset($values['names']) === true) { if (isset($values['names']) === true) {
$this->names = $values['names']; $this->names = $values['names'];
+5 -1
View File
@@ -12,8 +12,12 @@ class RouteUrl extends LoadableRoute
$this->setCallback($callback); $this->setCallback($callback);
} }
public function matchRoute($url, Request $request) public function matchRoute($url, Request $request): bool
{ {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */ /* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url); $regexMatch = $this->matchRegex($request, $url);
+236 -117
View File
@@ -66,6 +66,32 @@ class Router
*/ */
protected $exceptionHandlers; 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. * Router constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
@@ -78,7 +104,7 @@ class Router
/** /**
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public function reset() public function reset(): void
{ {
$this->processingRoute = false; $this->processingRoute = false;
$this->request = new Request(); $this->request = new Request();
@@ -87,6 +113,7 @@ class Router
$this->routeStack = []; $this->routeStack = [];
$this->processedRoutes = []; $this->processedRoutes = [];
$this->exceptionHandlers = []; $this->exceptionHandlers = [];
$this->loadedExceptionHandlers = [];
} }
/** /**
@@ -94,57 +121,76 @@ class Router
* @param IRoute $route * @param IRoute $route
* @return IRoute * @return IRoute
*/ */
public function addRoute(IRoute $route) public function addRoute(IRoute $route): IRoute
{ {
/* /*
* If a route is currently being processed, that means that the * If a route is currently being processed, that means that the route being added are rendered from the parent
* route being added are rendered from the parent routes callback, * routes callback, so we add them to the stack instead.
* so we add them to the stack instead.
*/ */
if ($this->processingRoute === true) { if ($this->processingRoute === true) {
$this->routeStack[] = $route; $this->routeStack[] = $route;
} else {
$this->routes[] = $route; return $route;
} }
$this->routes[] = $route;
return $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. * Process added routes.
* *
* @param array $routes * @param array $routes
* @param IGroupRoute|null $group * @param IGroupRoute|null $group
* @param IRoute|null $parent
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null) protected function processRoutes(array $routes, ?IGroupRoute $group = null): void
{ {
// Loop through each route-request $this->debug('Processing routes');
// Loop through each route-request
$exceptionHandlers = []; $exceptionHandlers = [];
// Stop processing routes if no valid route is found. // Stop processing routes if no valid route is found.
if($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) { if ($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
$this->debug('Halted route-processing as no valid route was found');
return; return;
} }
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath(); $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route IRoute */
foreach ($routes as $route) { foreach ($routes as $route) {
if ($parent !== null) { $this->debug('Processing route "%s"', \get_class($route));
/* Add the parent route */
$route->setParent($parent);
/* Add/merge parent settings with child */
$route->setSettings($parent->toArray(), true);
}
if ($group !== null) { if ($group !== null) {
/* Add the parent group */ /* Add the parent group */
$route->setGroup($group); $route->setGroup($group);
} }
@@ -152,47 +198,33 @@ class Router
/* @var $route IGroupRoute */ /* @var $route IGroupRoute */
if ($route instanceof IGroupRoute) { if ($route instanceof IGroupRoute) {
$group = $route;
if ($route->matchRoute($url, $this->request) === true) { if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */ /* Add exception handlers */
if (count($route->getExceptionHandlers()) !== 0) { if (\count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */ /** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers(); $exceptionHandlers += $route->getExceptionHandlers();
} }
/* Only render partial group if it matches */ /* Only render partial group if it matches */
if ($route instanceof IPartialGroupRoute) { if ($route instanceof IPartialGroupRoute === true) {
$this->processingRoute = true; $this->renderAndProcess($route);
$route->renderRoute($this->request);
$this->processingRoute = false;
} }
} }
if (($route instanceof IPartialGroupRoute) === false) { if ($route instanceof IPartialGroupRoute === false) {
$this->processingRoute = true; $this->renderAndProcess($route);
$route->renderRoute($this->request);
$this->processingRoute = false;
} }
continue;
} }
if ($route instanceof ILoadableRoute) { if ($route instanceof ILoadableRoute === true) {
/* Add the route to the map, so we can find the active one when all routes has been loaded */ /* Add the route to the map, so we can find the active one when all routes has been loaded */
$this->processedRoutes[] = $route; $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); $this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
@@ -203,29 +235,37 @@ class Router
* @throws NotFoundHttpException * @throws NotFoundHttpException
* @return void * @return void
*/ */
public function loadRoutes() public function loadRoutes(): void
{ {
$this->debug('Loading routes');
/* Initialize boot-managers */ /* Initialize boot-managers */
/* @var $manager IRouterBootManager */ /* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) { foreach ($this->bootManagers as $manager) {
$this->debug('Rendering bootmanager %s', \get_class($manager));
$manager->boot($this->request); $manager->boot($this->request);
$this->debug('Finished rendering bootmanager');
} }
/* Loop through each route-request */ /* Loop through each route-request */
$this->processRoutes($this->routes); $this->processRoutes($this->routes);
$this->debug('Finished loading routes');
} }
/** /**
* Routes the request * Routes the request
* *
* @param bool $rewrite * @param bool $rewrite
* @return string|mixed * @return string|null
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
*/ */
public function routeRequest($rewrite = false) public function routeRequest(bool $rewrite = false): ?string
{ {
$routeNotAllowed = false; $this->debug('Started routing request (rewrite: %s)', $rewrite === true ? 'yes' : 'no');
$methodNotAllowed = false;
try { try {
@@ -237,47 +277,46 @@ class Router
/* Verify csrf token for request */ /* Verify csrf token for request */
$this->csrfVerifier->handle($this->request); $this->csrfVerifier->handle($this->request);
} }
} else {
$this->request->setHasRewrite(false);
} }
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath(); $url = $this->request->getRewriteUrl() ?? $this->request->getUrl()->getPath();
/* @var $route ILoadableRoute */ /* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $key => $route) { foreach ($this->processedRoutes as $key => $route) {
$this->debug('Matching route "%s"', \get_class($route));
/* If the route matches */ /* If the route matches */
if ($route->matchRoute($url, $this->request) === true) { if ($route->matchRoute($url, $this->request) === true) {
/* Check if request method matches */ /* Check if request method matches */
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) { if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$routeNotAllowed = true; $this->debug('Method "%s" not allowed', $this->request->getMethod());
$methodNotAllowed = true;
continue; continue;
} }
$route->loadMiddleware($this->request); $route->loadMiddleware($this->request, $this);
if ($this->hasRewrite($url) === true) { $output = $this->handleRouteRewrite($key, $url);
unset($this->processedRoutes[$key]); if ($output !== null) {
return $output;
return $this->routeRequest(true);
} }
/* Render route */ /* Render route */
$routeNotAllowed = false; $methodNotAllowed = false;
$this->request->setLoadedRoute($route); $this->request->addLoadedRoute($route);
$output = $route->renderRoute($this->request); $output = $route->renderRoute($this->request, $this);
if ($output !== null) { if ($output !== null) {
return $output; return $output;
} }
if ($this->hasRewrite($url) === true) { $output = $this->handleRouteRewrite($key, $url);
unset($this->processedRoutes[$key]); if ($output !== null) {
return $output;
return $this->routeRequest(true);
} }
} }
} }
@@ -286,12 +325,12 @@ class Router
$this->handleException($e); $this->handleException($e);
} }
if ($routeNotAllowed === true) { if ($methodNotAllowed === true) {
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod()); $message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUrl()->getPath(), $this->request->getMethod());
$this->handleException(new HttpException($message, 403)); $this->handleException(new HttpException($message, 403));
} }
if ($this->request->getLoadedRoute() === null) { if (\count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl(); $rewriteUrl = $this->request->getRewriteUrl();
@@ -301,63 +340,80 @@ class Router
$message = sprintf('Route not found: "%s"', $this->request->getUrl()->getPath()); $message = sprintf('Route not found: "%s"', $this->request->getUrl()->getPath());
} }
$this->handleException(new NotFoundHttpException($message, 404)); $this->debug($message);
return $this->handleException(new NotFoundHttpException($message, 404));
} }
return null; return null;
} }
protected function hasRewrite($url) /**
* 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 the request has changed */
if ($this->request->hasRewrite() === true) { if ($this->request->hasRewrite() === false) {
return null;
if ($this->request->getRewriteRoute() !== null) {
/* Render rewrite-route */
$this->processedRoutes[] = $this->request->getRewriteRoute();
return true;
}
if ($this->request->isRewrite($url) === false) {
/* Render rewrite-url */
$this->processedRoutes = array_values($this->processedRoutes);
return true;
}
} }
return false; $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);
}
return null;
} }
/** /**
* @param \Exception $e * @param \Exception $e
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
* @return string * @return string|null
*/ */
protected function handleException(\Exception $e) protected function handleException(\Exception $e): ?string
{ {
$this->debug('Starting exception handling for "%s"', \get_class($e));
/* @var $handler IExceptionHandler */ /* @var $handler IExceptionHandler */
foreach ($this->exceptionHandlers as $key => $handler) { foreach ($this->exceptionHandlers as $key => $handler) {
if (is_object($handler) === false) { if (\is_object($handler) === false) {
$handler = new $handler(); $handler = new $handler();
} }
$this->debug('Processing exception-handler "%s"', \get_class($handler));
if (($handler instanceof IExceptionHandler) === false) { if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500); throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
} }
try { try {
$this->debug('Start rendering exception handler');
$handler->handleError($this->request, $e); $handler->handleError($this->request, $e);
$this->debug('Finished rendering exception-handler');
if ($this->request->hasRewrite() === true) { if (isset($this->loadedExceptionHandlers[$key]) === false && $this->request->hasRewrite() === true) {
unset($this->exceptionHandlers[$key]); $this->loadedExceptionHandlers[$key] = $handler;
$this->exceptionHandlers = array_values($this->exceptionHandlers);
$this->debug('Exception handler contains rewrite, reloading routes');
return $this->routeRequest(true); return $this->routeRequest(true);
} }
@@ -365,14 +421,17 @@ class Router
} catch (\Exception $e) { } catch (\Exception $e) {
} }
$this->debug('Finished processing');
} }
$this->debug('Finished exception handling - exception not handled, throwing');
throw $e; throw $e;
} }
public function arrayToParams(array $getParams = [], $includeEmpty = true) public function arrayToParams(array $getParams = [], bool $includeEmpty = true): string
{ {
if (count($getParams) !== 0) { if (\count($getParams) !== 0) {
if ($includeEmpty === false) { if ($includeEmpty === false) {
$getParams = array_filter($getParams, function ($item) { $getParams = array_filter($getParams, function ($item) {
@@ -392,45 +451,60 @@ class Router
* @param string $name * @param string $name
* @return ILoadableRoute|null * @return ILoadableRoute|null
*/ */
public function findRoute($name) public function findRoute(string $name): ?ILoadableRoute
{ {
$this->debug('Finding route by name "%s"', $name);
/* @var $route ILoadableRoute */ /* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) { foreach ($this->processedRoutes as $route) {
/* Check if the name matches with a name on the route. Should match either router alias or controller alias. */ /* Check if the name matches with a name on the route. Should match either router alias or controller alias. */
if ($route->hasName($name)) { if ($route->hasName($name) === true) {
$this->debug('Found route "%s" by name "%s"', $route->getUrl(), $name);
return $route; return $route;
} }
/* Direct match to controller */ /* Direct match to controller */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) { if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) {
$this->debug('Found route "%s" by controller "%s"', $route->getUrl(), $name);
return $route; return $route;
} }
/* Using @ is most definitely a controller@method or alias@method */ /* Using @ is most definitely a controller@method or alias@method */
if (is_string($name) === true && strpos($name, '@') !== false) { if (\is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = array_map('strtolower', explode('@', $name)); [$controller, $method] = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) { 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; return $route;
} }
} }
/* Check if callback matches (if it's not a function) */ /* 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 */ /* Check if the entire callback is matching */
if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) { if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
$this->debug('Found route "%s" by callback "%s"', $route->getUrl(), $name);
return $route; return $route;
} }
/* Check if the class part of the callback matches (class@method) */ /* Check if the class part of the callback matches (class@method) */
if (strtolower($name) === strtolower($route->getClass())) { if (strtolower($name) === strtolower($route->getClass())) {
$this->debug('Found route "%s" by class "%s"', $route->getUrl(), $name);
return $route; return $route;
} }
} }
} }
$this->debug('Route not found');
return null; return null;
} }
@@ -452,9 +526,11 @@ class Router
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return string * @return string
*/ */
public function getUrl($name = null, $parameters = null, $getParams = null) public function getUrl(?string $name = null, $parameters = null, $getParams = null): string
{ {
if ($getParams !== null && is_array($getParams) === false) { $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'); throw new InvalidArgumentException('Invalid type for getParams. Must be array or null');
} }
@@ -489,8 +565,8 @@ class Router
} }
/* Using @ is most definitely a controller@method or alias@method */ /* Using @ is most definitely a controller@method or alias@method */
if (is_string($name) === true && strpos($name, '@') !== false) { if (\is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = explode('@', $name); [$controller, $method] = explode('@', $name);
/* Loop through all the routes to see if we can find a match */ /* Loop through all the routes to see if we can find a match */
@@ -517,28 +593,28 @@ class Router
} }
/** /**
* Get bootmanagers * Get BootManagers
* @return array * @return array
*/ */
public function getBootManagers() public function getBootManagers(): array
{ {
return $this->bootManagers; return $this->bootManagers;
} }
/** /**
* Set bootmanagers * Set BootManagers
* @param array $bootManagers * @param array $bootManagers
*/ */
public function setBootManagers(array $bootManagers) public function setBootManagers(array $bootManagers): void
{ {
$this->bootManagers = $bootManagers; $this->bootManagers = $bootManagers;
} }
/** /**
* Add bootmanager * Add BootManager
* @param IRouterBootManager $bootManager * @param IRouterBootManager $bootManager
*/ */
public function addBootManager(IRouterBootManager $bootManager) public function addBootManager(IRouterBootManager $bootManager): void
{ {
$this->bootManagers[] = $bootManager; $this->bootManagers[] = $bootManager;
} }
@@ -548,7 +624,7 @@ class Router
* *
* @return array * @return array
*/ */
public function getProcessedRoutes() public function getProcessedRoutes(): array
{ {
return $this->processedRoutes; return $this->processedRoutes;
} }
@@ -556,7 +632,7 @@ class Router
/** /**
* @return array * @return array
*/ */
public function getRoutes() public function getRoutes(): array
{ {
return $this->routes; return $this->routes;
} }
@@ -565,9 +641,9 @@ class Router
* Set routes * Set routes
* *
* @param array $routes * @param array $routes
* @return static $this * @return static
*/ */
public function setRoutes(array $routes) public function setRoutes(array $routes): self
{ {
$this->routes = $routes; $this->routes = $routes;
@@ -579,7 +655,7 @@ class Router
* *
* @return Request * @return Request
*/ */
public function getRequest() public function getRequest(): Request
{ {
return $this->request; return $this->request;
} }
@@ -588,7 +664,7 @@ class Router
* Get csrf verifier class * Get csrf verifier class
* @return BaseCsrfVerifier * @return BaseCsrfVerifier
*/ */
public function getCsrfVerifier() public function getCsrfVerifier(): ?BaseCsrfVerifier
{ {
return $this->csrfVerifier; return $this->csrfVerifier;
} }
@@ -606,4 +682,47 @@ class Router
return $this; 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;
}
}
+89 -31
View File
@@ -13,12 +13,15 @@ namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException; use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\CallbackExceptionHandler; use Pecee\Handlers\CallbackExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier; use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response; use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException; use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Route\IRoute; use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController; use Pecee\SimpleRouter\Route\RouteController;
use Pecee\SimpleRouter\Route\RouteGroup; use Pecee\SimpleRouter\Route\RouteGroup;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteResource; use Pecee\SimpleRouter\Route\RouteResource;
use Pecee\SimpleRouter\Route\RouteUrl; use Pecee\SimpleRouter\Route\RouteUrl;
@@ -26,7 +29,7 @@ class SimpleRouter
{ {
/** /**
* Default namespace added to all routes * Default namespace added to all routes
* @var string * @var string|null
*/ */
protected static $defaultNamespace; protected static $defaultNamespace;
@@ -43,21 +46,76 @@ class SimpleRouter
protected static $router; protected static $router;
/** /**
* Start routing
*
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws HttpException * @throws HttpException
* @throws \Exception * @throws \Exception
*/ */
public static function start() public static function start(): void
{ {
echo static::router()->routeRequest(); 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. * Set default namespace which will be prepended to all routes.
* *
* @param string $defaultNamespace * @param string $defaultNamespace
*/ */
public static function setDefaultNamespace($defaultNamespace) public static function setDefaultNamespace(string $defaultNamespace): void
{ {
static::$defaultNamespace = $defaultNamespace; static::$defaultNamespace = $defaultNamespace;
} }
@@ -68,7 +126,7 @@ class SimpleRouter
* @param BaseCsrfVerifier $baseCsrfVerifier * @param BaseCsrfVerifier $baseCsrfVerifier
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void
{ {
static::router()->setCsrfVerifier($baseCsrfVerifier); static::router()->setCsrfVerifier($baseCsrfVerifier);
} }
@@ -80,7 +138,7 @@ class SimpleRouter
* @param IRouterBootManager $bootManager * @param IRouterBootManager $bootManager
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function addBootManager(IRouterBootManager $bootManager) public static function addBootManager(IRouterBootManager $bootManager): void
{ {
static::router()->addBootManager($bootManager); static::router()->addBootManager($bootManager);
} }
@@ -95,7 +153,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function get($url, $callback, array $settings = null) public static function get(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get'], $url, $callback, $settings); return static::match(['get'], $url, $callback, $settings);
} }
@@ -109,7 +167,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function post($url, $callback, array $settings = null) public static function post(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['post'], $url, $callback, $settings); return static::match(['post'], $url, $callback, $settings);
} }
@@ -123,7 +181,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function put($url, $callback, array $settings = null) public static function put(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['put'], $url, $callback, $settings); return static::match(['put'], $url, $callback, $settings);
} }
@@ -137,7 +195,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function patch($url, $callback, array $settings = null) public static function patch(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['patch'], $url, $callback, $settings); return static::match(['patch'], $url, $callback, $settings);
} }
@@ -151,7 +209,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function options($url, $callback, array $settings = null) public static function options(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['options'], $url, $callback, $settings); return static::match(['options'], $url, $callback, $settings);
} }
@@ -165,7 +223,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function delete($url, $callback, array $settings = null) public static function delete(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['delete'], $url, $callback, $settings); return static::match(['delete'], $url, $callback, $settings);
} }
@@ -179,9 +237,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function group(array $settings = [], \Closure $callback) public static function group(array $settings = [], \Closure $callback): IGroupRoute
{ {
if (is_callable($callback) === false) { if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
} }
@@ -205,9 +263,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function partialGroup($url, \Closure $callback, array $settings = []) public static function partialGroup(string $url, \Closure $callback, array $settings = []): IPartialGroupRoute
{ {
if (is_callable($callback) === false) { if (\is_callable($callback) === false) {
throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); throw new InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
} }
@@ -232,7 +290,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function basic($url, $callback, array $settings = null) public static function basic(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get', 'post'], $url, $callback, $settings); return static::match(['get', 'post'], $url, $callback, $settings);
} }
@@ -248,7 +306,7 @@ class SimpleRouter
* @return RouteUrl * @return RouteUrl
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function form($url, $callback, array $settings = null) public static function form(string $url, $callback, array $settings = null): IRoute
{ {
return static::match(['get', 'post'], $url, $callback, $settings); return static::match(['get', 'post'], $url, $callback, $settings);
} }
@@ -263,7 +321,7 @@ class SimpleRouter
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function match(array $requestMethods, $url, $callback, array $settings = null) public static function match(array $requestMethods, string $url, $callback, array $settings = null)
{ {
$route = new RouteUrl($url, $callback); $route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods); $route->setRequestMethods($requestMethods);
@@ -287,7 +345,7 @@ class SimpleRouter
* @return RouteUrl|IRoute * @return RouteUrl|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function all($url, $callback, array $settings = null) public static function all(string $url, $callback, array $settings = null)
{ {
$route = new RouteUrl($url, $callback); $route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -310,7 +368,7 @@ class SimpleRouter
* @return RouteController|IRoute * @return RouteController|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function controller($url, $controller, array $settings = null) public static function controller(string $url, $controller, array $settings = null)
{ {
$route = new RouteController($url, $controller); $route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -333,7 +391,7 @@ class SimpleRouter
* @return RouteResource|IRoute * @return RouteResource|IRoute
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function resource($url, $controller, array $settings = null) public static function resource(string $url, $controller, array $settings = null)
{ {
$route = new RouteResource($url, $controller); $route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route); $route = static::addDefaultNamespace($route);
@@ -354,7 +412,7 @@ class SimpleRouter
* @return CallbackExceptionHandler $callbackHandler * @return CallbackExceptionHandler $callbackHandler
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function error(\Closure $callback) public static function error(\Closure $callback): CallbackExceptionHandler
{ {
$routes = static::router()->getRoutes(); $routes = static::router()->getRoutes();
@@ -389,7 +447,7 @@ class SimpleRouter
* @return string * @return string
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function getUrl($name = null, $parameters = null, $getParams = null) public static function getUrl(?string $name = null, $parameters = null, $getParams = null): string
{ {
return static::router()->getUrl($name, $parameters, $getParams); return static::router()->getUrl($name, $parameters, $getParams);
} }
@@ -400,7 +458,7 @@ class SimpleRouter
* @return \Pecee\Http\Request * @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function request() public static function request(): Request
{ {
return static::router()->getRequest(); return static::router()->getRequest();
} }
@@ -411,7 +469,7 @@ class SimpleRouter
* @return Response * @return Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function response() public static function response(): Response
{ {
if (static::$response === null) { if (static::$response === null) {
static::$response = new Response(static::request()); static::$response = new Response(static::request());
@@ -426,7 +484,7 @@ class SimpleRouter
* @return Router * @return Router
* @throws \Pecee\Http\Exceptions\MalformedUrlException * @throws \Pecee\Http\Exceptions\MalformedUrlException
*/ */
public static function router() public static function router(): Router
{ {
if (static::$router === null) { if (static::$router === null) {
static::$router = new Router(); static::$router = new Router();
@@ -441,14 +499,14 @@ class SimpleRouter
* @param IRoute $route * @param IRoute $route
* @return IRoute * @return IRoute
*/ */
public static function addDefaultNamespace(IRoute $route) public static function addDefaultNamespace(IRoute $route): IRoute
{ {
if (static::$defaultNamespace !== null) { if (static::$defaultNamespace !== null) {
$callback = $route->getCallback(); $callback = $route->getCallback();
/* Only add default namespace on relative callbacks */ /* 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; $namespace = static::$defaultNamespace;
@@ -468,9 +526,9 @@ class SimpleRouter
/** /**
* Get default namespace * Get default namespace
* @return string * @return string|null
*/ */
public static function getDefaultNamespace() public static function getDefaultNamespace(): ?string
{ {
return static::$defaultNamespace; return static::$defaultNamespace;
} }
-39
View File
@@ -1,39 +0,0 @@
<?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;
}
}
@@ -1,11 +1,11 @@
<?php <?php
require_once 'Exceptions/MiddlewareLoadedException.php'; require_once 'Exception/MiddlewareLoadedException.php';
use Pecee\Http\Request; use Pecee\Http\Request;
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
{ {
public function handle(Request $request) public function handle(Request $request) : void
{ {
throw new MiddlewareLoadedException('Middleware loaded!'); throw new MiddlewareLoadedException('Middleware loaded!');
} }
@@ -1,4 +1,5 @@
<?php <?php
class ExceptionHandlerException extends \Exception class ExceptionHandlerException extends \Exception
{ {
} }
@@ -2,7 +2,7 @@
class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
echo $error->getMessage(); echo $error->getMessage();
} }
@@ -2,13 +2,12 @@
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
$request->setUrl('/'); $request->setUrl('/');
return $request;
} }
} }
@@ -2,13 +2,12 @@
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
$request->setUrl('/'); $request->setUrl('/');
return $request;
} }
} }
@@ -2,7 +2,7 @@
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{ {
public function handleError(\Pecee\Http\Request $request, \Exception $error) public function handleError(\Pecee\Http\Request $request, \Exception $error) : void
{ {
global $stack; global $stack;
$stack[] = static::class; $stack[] = static::class;
@@ -5,7 +5,7 @@ use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware { class RewriteMiddleware implements IMiddleware {
public function handle(Request $request) { public function handle(Request $request) : void {
$request->setRewriteCallback(function() { $request->setRewriteCallback(function() {
return 'ok'; return 'ok';
@@ -0,0 +1,46 @@
<?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;
}
}
@@ -2,9 +2,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.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; protected $result;
@@ -37,6 +36,7 @@ class GroupTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/api/v1/test', 'get'); TestRouter::debug('/api/v1/test', 'get');
$this->assertTrue(true);
} }
public function testMultipleRoutes() public function testMultipleRoutes()
@@ -61,6 +61,8 @@ class GroupTest extends PHPUnit_Framework_TestCase
}); });
TestRouter::debug('/my/match', 'get'); TestRouter::debug('/my/match', 'get');
$this->assertTrue(true);
} }
public function testUrls() public function testUrls()
@@ -3,13 +3,12 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.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() public function testMiddlewareFound()
{ {
$this->setExpectedException(MiddlewareLoadedException::class); $this->expectException(MiddlewareLoadedException::class);
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () { TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']); TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
@@ -29,6 +28,8 @@ class MiddlewareTest extends PHPUnit_Framework_TestCase
TestRouter::get('/my/test/url', 'DummyController@method1'); TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get'); TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
} }
} }
@@ -2,15 +2,14 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
{ {
public function testCallbackExceptionHandler() public function testCallbackExceptionHandler()
{ {
$this->setExpectedException(ExceptionHandlerException::class); $this->expectException(ExceptionHandlerException::class);
// Match normal route on alias // Match normal route on alias
TestRouter::get('/my-new-url', 'DummyController@method2'); TestRouter::get('/my-new-url', 'DummyController@method2');
@@ -22,6 +21,8 @@ class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
TestRouter::debugNoReset('/404-url', 'get'); TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset(); TestRouter::router()->reset();
$this->assertTrue(true);
} }
} }
@@ -1,9 +1,8 @@
<?php <?php
require_once 'Dummy/DummyController.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() public function testGet()
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.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() public function testParameters()
@@ -1,9 +1,8 @@
<?php <?php
require_once 'Dummy/ResourceController.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() public function testResourceStore()
@@ -1,13 +1,12 @@
<?php <?php
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ResponseException.php'; require_once 'Dummy/Exception/ResponseException.php';
require_once 'Dummy/Handler/ExceptionHandlerFirst.php'; require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
require_once 'Dummy/Handler/ExceptionHandlerSecond.php'; require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php'; require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php'; require_once 'Dummy/Middleware/RewriteMiddleware.php';
require_once 'Dummy/Middlewares/RewriteMiddleware.php';
class RouteRewriteTest extends PHPUnit_Framework_TestCase class RouteRewriteTest extends \PHPUnit\Framework\TestCase
{ {
/** /**
@@ -61,7 +60,7 @@ class RouteRewriteTest extends PHPUnit_Framework_TestCase
public function testRewriteExceptionMessage() public function testRewriteExceptionMessage()
{ {
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class); $this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) { TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
@@ -2,10 +2,9 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php'; require_once 'Dummy/Exception/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterRouteTest extends PHPUnit_Framework_TestCase class RouterRouteTest extends \PHPUnit\Framework\TestCase
{ {
protected $result = false; protected $result = false;
@@ -27,7 +26,7 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testNotFound() public function testNotFound()
{ {
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException'); $this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1'); TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post'); TestRouter::debug('/test-param1-param2', 'post');
} }
@@ -36,24 +35,32 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{ {
TestRouter::get('/my/test/url', 'DummyController@method1'); TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get'); TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
} }
public function testPost() public function testPost()
{ {
TestRouter::post('/my/test/url', 'DummyController@method1'); TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post'); TestRouter::debug('/my/test/url', 'post');
$this->assertTrue(true);
} }
public function testPut() public function testPut()
{ {
TestRouter::put('/my/test/url', 'DummyController@method1'); TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'put'); TestRouter::debug('/my/test/url', 'put');
$this->assertTrue(true);
} }
public function testDelete() public function testDelete()
{ {
TestRouter::delete('/my/test/url', 'DummyController@method1'); TestRouter::delete('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'delete'); TestRouter::debug('/my/test/url', 'delete');
$this->assertTrue(true);
} }
public function testMethodNotAllowed() public function testMethodNotAllowed()
@@ -123,6 +130,8 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{ {
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']); TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get'); TestRouter::debug('/my/custom-path', 'get');
$this->assertTrue(true);
} }
public function testParameterDefaultValue() { public function testParameterDefaultValue() {
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php'; require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php'; require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.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() public function testIssue253()
@@ -32,21 +31,22 @@ class RouterUrlTest extends PHPUnit_Framework_TestCase
{ {
// Test spanish characters // Test spanish characters
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']); 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'); TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl()); $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 // Test danish characters
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']); TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
TestRouter::debugNoReset('/kategori/økse', 'get'); TestRouter::debugNoReset('/kategori/økse', 'get');
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl()); $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(); TestRouter::router()->reset();
} }
+4
View File
@@ -0,0 +1,4 @@
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once 'TestRouter.php';
+9
View File
@@ -0,0 +1,9 @@
<?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;