Merge pull request #386 from skipperbent/v4-php7-port

Version 4
This commit is contained in:
Simon Sessingø
2018-03-26 23:57:54 +02:00
committed by GitHub
64 changed files with 1428 additions and 668 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
+399 -16
View File
@@ -1,5 +1,6 @@
# Simple PHP router
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expandability in mind.
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.
**Please note that this documentation is currently work-in-progress. Feel free to contribute.**
@@ -11,7 +12,6 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Notes](#notes-1)
- [Requirements](#requirements)
- [Feedback and development](#feedback-and-development)
- [Issues guidelines](#issues-guidelines)
- [Contribution development guidelines](#contribution-development-guidelines)
- [Features](#features)
- [Installation](#installation)
@@ -20,6 +20,14 @@ Simple, fast and yet powerful PHP router that is easy to get integrated and in a
- [Setting up IIS](#setting-up-iis)
- [Configuration](#configuration)
- [Helper functions](#helper-functions)
- [Help and support](#help-and-support)
- [How to debug](#how-to-debug)
- [Creating unit-tests](#creating-unit-tests)
- [Debug information](#debug-information)
- [Benchmark and log-info](#benchmark-and-log-info)
- [Reporting a new issue](#reporting-a-new-issue)
- [Procedure for reporting a new issue](#procedure-for-reporting-a-new-issue)
- [Issue template](#issue-template)
- [Routes](#routes)
- [Basic routing](#basic-routing)
- [Available methods](#available-methods)
@@ -118,18 +126,14 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
### 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.
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).
###### Issues guidelines
**Experiencing an issue?**
- 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.
Please refer to our [Help and support](#help-and-support) section in the documentation before reporting a new issue.
- 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
##### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
@@ -206,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.
```
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
@@ -308,6 +312,8 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param string|array|null $parameters
* @param array|null $getParams
* @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function url($name = null, $parameters = null, $getParams = null)
{
@@ -316,6 +322,7 @@ function url($name = null, $parameters = null, $getParams = null)
/**
* @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function response()
{
@@ -324,6 +331,7 @@ function response()
/**
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function request()
{
@@ -335,15 +343,16 @@ function request()
* @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string
* @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function input($index = null, $defaultValue = null, $methods = 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)
@@ -358,12 +367,13 @@ function redirect($url, $code = null)
/**
* Get current csrf-token
* @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function csrf_token()
{
$baseVerifier = Router::router()->getCsrfVerifier();
if ($baseVerifier !== null) {
return $baseVerifier->getToken();
return $baseVerifier->getTokenProvider()->getToken();
}
return null;
@@ -372,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
Remember the ```routes.php``` file you required in your ```index.php```? This file be where you place all your custom rules for routing.
+3 -2
View File
@@ -27,10 +27,11 @@
}
],
"require": {
"php": ">=5.4.0"
"php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "4.7.7"
"phpunit/phpunit": "^6.0",
"mockery/mockery": "^1"
},
"autoload": {
"psr-4": {
+8 -3
View File
@@ -19,6 +19,7 @@ use Pecee\SimpleRouter\SimpleRouter as Router;
* @param array|null $getParams
* @return string
* @throws \InvalidArgumentException
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function url($name = null, $parameters = null, $getParams = null)
{
@@ -27,6 +28,7 @@ function url($name = null, $parameters = null, $getParams = null)
/**
* @return \Pecee\Http\Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function response()
{
@@ -35,6 +37,7 @@ function response()
/**
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function request()
{
@@ -46,15 +49,16 @@ function request()
* @param string|null $index Parameter index name
* @param string|null $defaultValue Default return value
* @param string|array|null $methods Default method
* @return \Pecee\Http\Input\Input|string
* @return \Pecee\Http\Input\InputHandler|string
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
function input($index = null, $defaultValue = null, $methods = 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)
@@ -69,6 +73,7 @@ function redirect($url, $code = null)
/**
* Get current csrf-token
* @return string|null
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
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
namespace Pecee\Controllers;
interface IResourceController
{
/**
* @return void
* @return string|null
*/
public function index();
public function index(): ?string;
/**
* @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
* @param mixed $id
* @return void
* @return string|null
*/
public function edit($id);
public function edit($id): ?string;
/**
* @param mixed $id
* @return void
* @return string|null
*/
public function update($id);
public function update($id): ?string;
/**
* @param mixed $id
* @return void
* @return string|null
*/
public function destroy($id);
public function destroy($id): ?string;
}
@@ -1,6 +1,8 @@
<?php
namespace Pecee\Exceptions;
class InvalidArgumentException extends \InvalidArgumentException {
class InvalidArgumentException extends \InvalidArgumentException
{
}
@@ -25,12 +25,11 @@ class CallbackExceptionHandler implements IExceptionHandler
/**
* @param Request $request
* @param \Exception $error
* @return Request|null
*/
public function handleError(Request $request, \Exception $error)
public function handleError(Request $request, \Exception $error): void
{
/* Fire exceptions */
return call_user_func($this->callback,
\call_user_func($this->callback,
$request,
$error
);
+2 -2
View File
@@ -1,4 +1,5 @@
<?php
namespace Pecee\Handlers;
use Pecee\Http\Request;
@@ -8,8 +9,7 @@ interface IExceptionHandler
/**
* @param Request $request
* @param \Exception $error
* @return Request|null
*/
public function handleError(Request $request, \Exception $error);
public function handleError(Request $request, \Exception $error): void;
}
+6 -6
View File
@@ -5,17 +5,17 @@ namespace Pecee\Http\Input;
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($value);
public function setValue(string $value): self;
public function __toString();
+32 -32
View File
@@ -14,7 +14,7 @@ class InputFile implements IInputItem
public $errors;
public $tmpName;
public function __construct($index)
public function __construct(string $index)
{
$this->index = $index;
@@ -31,7 +31,7 @@ class InputFile implements IInputItem
* @throws InvalidArgumentException
* @return static
*/
public static function createFromArray(array $values)
public static function createFromArray(array $values): self
{
if (isset($values['index']) === false) {
throw new InvalidArgumentException('Index key is required');
@@ -48,7 +48,7 @@ class InputFile implements IInputItem
];
return (new static($values['index']))
->setSize($values['size'])
->setSize((int)$values['size'])
->setError($values['error'])
->setType($values['type'])
->setTmpName($values['tmp_name'])
@@ -59,7 +59,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getIndex()
public function getIndex(): string
{
return $this->index;
}
@@ -67,9 +67,9 @@ class InputFile implements IInputItem
/**
* Set input index
* @param string $index
* @return static $this
* @return static
*/
public function setIndex($index)
public function setIndex(string $index): IInputItem
{
$this->index = $index;
@@ -79,7 +79,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getSize()
public function getSize(): string
{
return $this->size;
}
@@ -87,9 +87,9 @@ class InputFile implements IInputItem
/**
* Set file size
* @param int $size
* @return static $this
* @return static
*/
public function setSize($size)
public function setSize(int $size): IInputItem
{
$this->size = $size;
@@ -100,7 +100,7 @@ class InputFile implements IInputItem
* Get mime-type of file
* @return string
*/
public function getMime()
public function getMime(): string
{
return $this->getType();
}
@@ -108,7 +108,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getType()
public function getType(): string
{
return $this->type;
}
@@ -116,9 +116,9 @@ class InputFile implements IInputItem
/**
* Set type
* @param string $type
* @return static $this
* @return static
*/
public function setType($type)
public function setType(string $type): IInputItem
{
$this->type = $type;
@@ -130,7 +130,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getExtension()
public function getExtension(): string
{
return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
}
@@ -140,7 +140,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -150,9 +150,9 @@ class InputFile implements IInputItem
* Useful for adding validation etc.
*
* @param string $name
* @return static $this
* @return static
*/
public function setName($name)
public function setName(string $name): IInputItem
{
$this->name = $name;
@@ -163,9 +163,9 @@ class InputFile implements IInputItem
* Set filename
*
* @param string $name
* @return static $this
* @return static
*/
public function setFilename($name)
public function setFilename($name): IInputItem
{
$this->filename = $name;
@@ -177,7 +177,7 @@ class InputFile implements IInputItem
*
* @return string mixed
*/
public function getFilename()
public function getFilename(): string
{
return $this->filename;
}
@@ -188,7 +188,7 @@ class InputFile implements IInputItem
* @param string $destination
* @return bool
*/
public function move($destination)
public function move($destination): bool
{
return move_uploaded_file($this->tmpName, $destination);
}
@@ -198,7 +198,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getContents()
public function getContents(): string
{
return file_get_contents($this->tmpName);
}
@@ -208,7 +208,7 @@ class InputFile implements IInputItem
*
* @return bool
*/
public function hasError()
public function hasError(): bool
{
return ($this->getError() !== 0);
}
@@ -218,7 +218,7 @@ class InputFile implements IInputItem
*
* @return string
*/
public function getError()
public function getError(): string
{
return $this->errors;
}
@@ -227,9 +227,9 @@ class InputFile implements IInputItem
* Set error
*
* @param int $error
* @return static $this
* @return static
*/
public function setError($error)
public function setError($error): IInputItem
{
$this->errors = (int)$error;
@@ -239,7 +239,7 @@ class InputFile implements IInputItem
/**
* @return string
*/
public function getTmpName()
public function getTmpName(): string
{
return $this->tmpName;
}
@@ -247,9 +247,9 @@ class InputFile implements IInputItem
/**
* Set file temp. name
* @param string $name
* @return static $this
* @return static
*/
public function setTmpName($name)
public function setTmpName($name): IInputItem
{
$this->tmpName = $name;
@@ -261,7 +261,7 @@ class InputFile implements IInputItem
return $this->getTmpName();
}
public function getValue()
public function getValue(): string
{
return $this->getFilename();
}
@@ -270,14 +270,14 @@ class InputFile implements IInputItem
* @param string $value
* @return static
*/
public function setValue($value)
public function setValue(string $value): IInputItem
{
$this->filename = $value;
return $this;
}
public function toArray()
public function toArray(): array
{
return [
'tmp_name' => $this->tmpName,
@@ -5,7 +5,7 @@ namespace Pecee\Http\Input;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Http\Request;
class Input
class InputHandler
{
/**
* @var array
@@ -42,26 +42,26 @@ class Input
* Parse input values
*
*/
public function parseInputs()
public function parseInputs(): void
{
/* Parse get requests */
if (count($_GET) !== 0) {
if (\count($_GET) !== 0) {
$this->get = $this->handleGetPost($_GET);
}
/* Parse post requests */
$postVars = $_POST;
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
if (\in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
if (count($postVars) !== 0) {
if (\count($postVars) !== 0) {
$this->post = $this->handleGetPost($postVars);
}
/* Parse get requests */
if (count($_FILES) !== 0) {
if (\count($_FILES) !== 0) {
$this->file = $this->parseFiles();
}
}
@@ -69,18 +69,18 @@ class Input
/**
* @return array
*/
public function parseFiles()
public function parseFiles(): array
{
$list = [];
foreach ((array)$_FILES as $key => $value) {
// Handle array input
if (is_array($value['name']) === false) {
if (\is_array($value['name']) === false) {
$values['index'] = $key;
try {
$list[$key] = InputFile::createFromArray($values + $value);
} catch(InvalidArgumentException $e ){
} catch (InvalidArgumentException $e) {
}
continue;
@@ -101,7 +101,7 @@ class Input
return $list;
}
protected function rearrangeFiles(array $values, &$index, $original)
protected function rearrangeFiles(array $values, &$index, $original): array
{
$originalIndex = $index[0];
@@ -111,7 +111,7 @@ class Input
foreach ($values as $key => $value) {
if (is_array($original['name'][$key]) === false) {
if (\is_array($original['name'][$key]) === false) {
try {
@@ -132,7 +132,7 @@ class Input
$output[$key] = $file;
continue;
} catch(InvalidArgumentException $e) {
} catch (InvalidArgumentException $e) {
}
}
@@ -152,14 +152,14 @@ class Input
return $output;
}
protected function handleGetPost(array $array)
protected function handleGetPost(array $array): array
{
$list = [];
foreach ($array as $key => $value) {
// Handle array input
if (is_array($value) === false) {
if (\is_array($value) === false) {
$list[$key] = new InputItem($key, $value);
continue;
}
@@ -179,9 +179,9 @@ class Input
* @param string|null $defaultValue
* @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
* @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
* @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
* @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];
}
$element = null;
if ($methods === null || in_array('get', $methods, false) === true) {
if ($methods === null || \in_array('get', $methods, true) === true) {
$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);
}
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);
}
return ($element !== null) ? $element : $defaultValue;
return $element ?? $defaultValue;
}
/**
@@ -247,7 +247,7 @@ class Input
* @param array|string|null $methods
* @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);
@@ -264,7 +264,7 @@ class Input
* @param string $index
* @return bool
*/
public function exists($index)
public function exists(string $index): bool
{
return ($this->getObject($index) !== null);
}
@@ -274,7 +274,7 @@ class Input
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null)
public function all(array $filter = null): array
{
$output = $_GET + $_POST;
+9 -9
View File
@@ -8,7 +8,7 @@ class InputItem implements IInputItem
public $name;
public $value;
public function __construct($index, $value = null)
public function __construct(string $index, ?string $value = null)
{
$this->index = $index;
$this->value = $value;
@@ -20,12 +20,12 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getIndex()
public function getIndex(): string
{
return $this->index;
}
public function setIndex($index)
public function setIndex(string $index): IInputItem
{
$this->index = $index;
@@ -35,7 +35,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -43,9 +43,9 @@ class InputItem implements IInputItem
/**
* Set input name
* @param string $name
* @return static $this
* @return static
*/
public function setName($name)
public function setName(string $name): IInputItem
{
$this->name = $name;
@@ -55,7 +55,7 @@ class InputItem implements IInputItem
/**
* @return string
*/
public function getValue()
public function getValue(): string
{
return $this->value;
}
@@ -63,9 +63,9 @@ class InputItem implements IInputItem
/**
* Set input value
* @param string $value
* @return static $this
* @return static
*/
public function setValue($value)
public function setValue(string $value): IInputItem
{
$this->value = $value;
+12 -12
View File
@@ -9,8 +9,8 @@ use Pecee\Http\Security\ITokenProvider;
class BaseCsrfVerifier implements IMiddleware
{
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
public const POST_KEY = 'csrf-token';
public const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $tokenProvider;
@@ -29,21 +29,21 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request
* @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;
}
$max = count($this->except) - 1;
$max = \count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
if ($url[\strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUrl()->getOriginalUrl(), $url) === 0);
$skip = $request->getUrl()->contains($url);
} else {
$skip = ($url === $request->getUrl()->getOriginalUrl());
}
@@ -62,12 +62,12 @@ class BaseCsrfVerifier implements IMiddleware
* @param Request $request
* @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 ($token === null) {
@@ -85,7 +85,7 @@ class BaseCsrfVerifier implements IMiddleware
}
public function getTokenProvider()
public function getTokenProvider(): ITokenProvider
{
return $this->tokenProvider;
}
@@ -94,7 +94,7 @@ class BaseCsrfVerifier implements IMiddleware
* Set token provider
* @param ITokenProvider $provider
*/
public function setTokenProvider(ITokenProvider $provider)
public function setTokenProvider(ITokenProvider $provider): void
{
$this->tokenProvider = $provider;
}
@@ -1,4 +1,5 @@
<?php
namespace Pecee\Http\Middleware\Exceptions;
class TokenMismatchException extends \Exception
+2 -2
View File
@@ -1,4 +1,5 @@
<?php
namespace Pecee\Http\Middleware;
use Pecee\Http\Request;
@@ -7,8 +8,7 @@ interface IMiddleware
{
/**
* @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;
use Pecee\Http\Input\Input;
use Pecee\Http\Input\InputHandler;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter;
@@ -10,11 +10,11 @@ use Pecee\SimpleRouter\SimpleRouter;
class Request
{
private $data = [];
protected $headers;
protected $headers = [];
protected $host;
protected $url;
protected $method;
protected $input;
protected $inputHandler;
protected $hasRewrite = false;
@@ -25,9 +25,9 @@ class Request
protected $rewriteUrl;
/**
* @var ILoadableRoute|null
* @var array
*/
protected $loadedRoute;
protected $loadedRoutes = [];
/**
* Request constructor.
@@ -35,28 +35,21 @@ class Request
*/
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) {
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
$this->setHost($this->getHeader('http-host'));
// Check if special IIS header exist, otherwise use default.
$this->setUrl($this->getHeader('unencoded-url', $this->getHeader('request-uri')));
$this->inputHandler = new InputHandler($this);
$this->method = strtolower($this->inputHandler->get('_method', $this->getHeader('request-method')));
}
public function isSecure()
public function isSecure(): bool
{
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
*/
public function getUrl()
public function getUrl(): Url
{
return $this->url;
}
/**
* @return string
* @return string|null
*/
public function getHost()
public function getHost(): ?string
{
return $this->host;
}
/**
* @return string
* @return string|null
*/
public function getMethod()
public function getMethod(): ?string
{
return $this->method;
}
@@ -89,7 +82,7 @@ class Request
* Get http basic auth user
* @return string|null
*/
public function getUser()
public function getUser(): ?string
{
return $this->getHeader('php-auth-user');
}
@@ -98,7 +91,7 @@ class Request
* Get http basic auth password
* @return string|null
*/
public function getPassword()
public function getPassword(): ?string
{
return $this->getHeader('php-auth-pw');
}
@@ -107,16 +100,16 @@ class Request
* Get all headers
* @return array
*/
public function getHeaders()
public function getHeaders(): array
{
return $this->headers;
}
/**
* Get id address
* @return string
* @return string|null
*/
public function getIp()
public function getIp(): ?string
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
@@ -133,27 +126,27 @@ class Request
* Get remote address/ip
*
* @alias static::getIp
* @return string
* @return string|null
*/
public function getRemoteAddr()
public function getRemoteAddr(): ?string
{
return $this->getIp();
}
/**
* Get referer
* @return string
* @return string|null
*/
public function getReferer()
public function getReferer(): ?string
{
return $this->getHeader('http-referer');
}
/**
* Get user agent
* @return string
* @return string|null
*/
public function getUserAgent()
public function getUserAgent(): ?string
{
return $this->getHeader('http-user-agent');
}
@@ -166,18 +159,18 @@ class Request
*
* @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
* @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
*/
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
*/
public function isAjax()
public function isAjax(): bool
{
return (strtolower($this->getHeader('http-x-requested-with')) === 'xmlhttprequest');
}
@@ -206,7 +199,7 @@ class Request
* Get accept formats
* @return array
*/
public function getAcceptFormats()
public function getAcceptFormats(): array
{
return explode(',', $this->getHeader('http-accept'));
}
@@ -215,15 +208,15 @@ class Request
* @param string|Url $url
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function setUrl($url)
public function setUrl($url): void
{
$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;
}
@@ -231,7 +224,7 @@ class Request
/**
* @param string $method
*/
public function setMethod($method)
public function setMethod(string $method): void
{
$this->method = $method;
}
@@ -242,7 +235,7 @@ class Request
* @param ILoadableRoute $route
* @return static
*/
public function setRewriteRoute(ILoadableRoute $route)
public function setRewriteRoute(ILoadableRoute $route): self
{
$this->hasRewrite = true;
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
@@ -255,7 +248,7 @@ class Request
*
* @return ILoadableRoute|null
*/
public function getRewriteRoute()
public function getRewriteRoute(): ?ILoadableRoute
{
return $this->rewriteRoute;
}
@@ -263,9 +256,9 @@ class Request
/**
* Get rewrite url
*
* @return string
* @return string|null
*/
public function getRewriteUrl()
public function getRewriteUrl(): ?string
{
return $this->rewriteUrl;
}
@@ -276,7 +269,7 @@ class Request
* @param string $rewriteUrl
* @return static
*/
public function setRewriteUrl($rewriteUrl)
public function setRewriteUrl(string $rewriteUrl): self
{
$this->hasRewrite = true;
$this->rewriteUrl = rtrim($rewriteUrl, '/') . '/';
@@ -286,10 +279,10 @@ class Request
/**
* Set rewrite callback
* @param string $callback
* @param string|\Closure $callback
* @return static
*/
public function setRewriteCallback($callback)
public function setRewriteCallback($callback): self
{
$this->hasRewrite = true;
@@ -300,44 +293,73 @@ class Request
* Get loaded route
* @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
* @return static
*/
public function setLoadedRoute(ILoadableRoute $route)
public function addLoadedRoute(ILoadableRoute $route): self
{
$this->loadedRoute = $route;
$this->loadedRoutes[] = $route;
return $this;
}
public function hasRewrite()
/**
* Returns true if the request contains a rewrite
*
* @return bool
*/
public function hasRewrite(): bool
{
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;
}
public function isRewrite($url)
{
return ($this->rewriteUrl === $url);
}
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)
@@ -347,7 +369,7 @@ class Request
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
* @return static
*/
public function httpCode($code)
public function httpCode(int $code): self
{
http_response_code($code);
@@ -32,7 +32,7 @@ class Response
* @param string $url
* @param int $httpCode
*/
public function redirect($url, $httpCode = null)
public function redirect(string $url, ?int $httpCode = null): void
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
@@ -42,7 +42,7 @@ class Response
exit(0);
}
public function refresh()
public function refresh(): void
{
$this->redirect($this->request->getUrl()->getOriginalUrl());
}
@@ -52,7 +52,7 @@ class Response
* @param string $name
* @return static
*/
public function auth($name = '')
public function auth(string $name = ''): self
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
@@ -62,23 +62,22 @@ class Response
return $this;
}
public function cache($eTag, $lastModified = 2592000)
public function cache(string $eTag, int $lastModifiedTime = 2592000): self
{
$this->headers([
'Cache-Control: public',
'Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT',
'Etag: ' . $eTag,
sprintf('Last-Modified: %s GMT', gmdate('D, d M Y H:i:s', $lastModifiedTime)),
sprintf('Etag: %s', $eTag),
]);
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) {
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModifiedTime)) {
$this->header('HTTP/1.1 304 Not Modified');
exit();
exit(0);
}
return $this;
@@ -91,9 +90,9 @@ class Response
* @param int $dept JSON debt.
* @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.');
}
@@ -107,7 +106,7 @@ class Response
* @param string $value
* @return static
*/
public function header($value)
public function header(string $value): self
{
header($value);
@@ -119,7 +118,7 @@ class Response
* @param array $headers
* @return static
*/
public function headers(array $headers)
public function headers(array $headers): self
{
foreach ($headers as $header) {
$this->header($header);
+16 -27
View File
@@ -6,7 +6,7 @@ use Pecee\Http\Security\Exceptions\SecurityException;
class CookieTokenProvider implements ITokenProvider
{
const CSRF_KEY = 'CSRF-TOKEN';
public const CSRF_KEY = 'CSRF-TOKEN';
protected $token;
protected $cookieTimeoutMinutes = 120;
@@ -30,24 +30,13 @@ class CookieTokenProvider implements ITokenProvider
* @return string
* @throws SecurityException
*/
public function generateToken()
public function generateToken(): string
{
if (function_exists('random_bytes') === true) {
try {
return bin2hex(random_bytes(32));
} catch(\Exception $e) {
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
try {
return bin2hex(random_bytes(32));
} catch (\Exception $e) {
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
$isSourceStrong = false;
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
if ($isSourceStrong === false || $random === false) {
throw new SecurityException('IV generation failed');
}
return $random;
}
/**
@@ -56,9 +45,9 @@ class CookieTokenProvider implements ITokenProvider
* @param string $token
* @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());
}
@@ -71,7 +60,7 @@ class CookieTokenProvider implements ITokenProvider
*
* @param string $token
*/
public function setToken($token)
public function setToken(string $token): void
{
$this->token = $token;
setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
@@ -82,17 +71,17 @@ class CookieTokenProvider implements ITokenProvider
* @param string|null $defaultValue
* @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;
return ($this->token !== null) ? $this->token : $defaultValue;
return $this->token ?? $defaultValue;
}
/**
* Refresh existing token
*/
public function refresh()
public function refresh(): void
{
if ($this->token !== null) {
$this->setToken($this->token);
@@ -103,7 +92,7 @@ class CookieTokenProvider implements ITokenProvider
* Returns whether the csrf token has been defined
* @return bool
*/
public function hasToken()
public function hasToken(): bool
{
return isset($_COOKIE[static::CSRF_KEY]);
}
@@ -112,16 +101,16 @@ class CookieTokenProvider implements ITokenProvider
* Get timeout for cookie in minutes
* @return int
*/
public function getCookieTimeoutMinutes()
public function getCookieTimeoutMinutes(): int
{
return $this->cookieTimeoutMinutes;
}
/**
* Set cookie timeout in minutes
* @param $minutes
* @param int $minutes
*/
public function setCookieTimeoutMinutes($minutes)
public function setCookieTimeoutMinutes(int $minutes): void
{
$this->cookieTimeoutMinutes = $minutes;
}
@@ -1,6 +1,8 @@
<?php
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
*/
public function refresh();
public function refresh(): void;
/**
* Validate valid CSRF token
@@ -16,6 +16,14 @@ interface ITokenProvider
* @param string $token
* @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
* @throws MalformedUrlException
*/
public function __construct($url)
public function __construct(?string $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'] !== '/') {
$this->data['path'] = rtrim($this->data['path'], '/') . '/';
if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
$this->data['path'] = rtrim($this->data['path'], '/') . '/';
}
}
}
/**
* Check if url is using a secure protocol like https
* @return bool
*/
public function isSecure()
public function isSecure(): bool
{
return (strtolower($this->getScheme()) === 'https');
}
@@ -47,7 +48,7 @@ class Url
* Checks if url is relative
* @return bool
*/
public function isRelative()
public function isRelative(): bool
{
return ($this->getHost() === null);
}
@@ -56,7 +57,7 @@ class Url
* Get url scheme
* @return string|null
*/
public function getScheme()
public function getScheme(): ?string
{
return $this->data['scheme'];
}
@@ -65,7 +66,7 @@ class Url
* Get url host
* @return string|null
*/
public function getHost()
public function getHost(): ?string
{
return $this->data['host'];
}
@@ -74,7 +75,7 @@ class Url
* Get url port
* @return int|null
*/
public function getPort()
public function getPort(): ?int
{
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
}
@@ -83,7 +84,7 @@ class Url
* Parse username from url
* @return string|null
*/
public function getUserName()
public function getUserName(): ?string
{
return $this->data['user'];
}
@@ -92,7 +93,7 @@ class Url
* Parse password from url
* @return string|null
*/
public function getPassword()
public function getPassword(): ?string
{
return $this->data['pass'];
}
@@ -101,16 +102,16 @@ class Url
* Get path from url
* @return string
*/
public function getPath()
public function getPath(): ?string
{
return $this->data['path'];
return $this->data['path'] ?? '/';
}
/**
* Get querystring from url
* @return string|null
*/
public function getQueryString()
public function getQueryString(): ?string
{
return $this->data['query'];
}
@@ -119,7 +120,7 @@ class Url
* Get fragment from url (everything after #)
* @return string|null
*/
public function getFragment()
public function getFragment(): ?string
{
return $this->data['fragment'];
}
@@ -127,7 +128,7 @@ class Url
/**
* @return string
*/
public function getOriginalUrl()
public function getOriginalUrl(): string
{
return $this->originalUrl;
}
@@ -139,7 +140,7 @@ class Url
* @throws MalformedUrlException
* @return array
*/
public function parseUrl($url, $component = -1)
public function parseUrl(string $url, int $component = -1): array
{
$encodedUrl = preg_replace_callback(
'/[^:\/@?&=#]+/u',
@@ -158,11 +159,36 @@ class Url
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
* @return array
*/
public function getData()
public function getData(): array
{
return $this->data;
}
@@ -1,4 +1,5 @@
<?php
namespace Pecee\SimpleRouter\Exceptions;
class HttpException extends \Exception
@@ -1,4 +1,5 @@
<?php
namespace Pecee\SimpleRouter\Exceptions;
class NotFoundHttpException extends HttpException
@@ -1,4 +1,5 @@
<?php
namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
@@ -9,7 +10,6 @@ interface IRouterBootManager
* Called when router loads it's routes
*
* @param Request $request
* @return Request
*/
public function boot(Request $request);
public function boot(Request $request): void;
}
@@ -1,4 +1,5 @@
<?php
namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute
@@ -8,7 +9,7 @@ interface IControllerRoute extends IRoute
*
* @return string
*/
public function getController();
public function getController(): string;
/**
* Set controller class-name
@@ -16,21 +17,6 @@ interface IControllerRoute extends IRoute
* @param string $controller
* @return static
*/
public function setController($controller);
/**
* Return active method
*
* @return string
*/
public function getMethod();
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method);
public function setController(string $controller): self;
}
+12 -12
View File
@@ -13,21 +13,21 @@ interface IGroupRoute extends IRoute
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request);
public function matchDomain(Request $request): bool;
/**
* Add exception handler
*
* @param IExceptionHandler|string $handler
* @return static $this;
* @return static
*/
public function addExceptionHandler($handler);
public function addExceptionHandler($handler): self;
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
* @return static
*/
public function setExceptionHandlers(array $handlers);
@@ -36,35 +36,35 @@ interface IGroupRoute extends IRoute
*
* @return array
*/
public function getExceptionHandlers();
public function getExceptionHandlers(): array;
/**
* Get domains for domain.
*
* @return array
*/
public function getDomains();
public function getDomains(): array;
/**
* Set allowed domains for group.
*
* @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.
*
* @param string $prefix
* @return string
* @return static
*/
public function setPrefix($prefix);
public function setPrefix($prefix): self;
/**
* Get prefix.
*
* @return string
* @return string|null
*/
public function getPrefix();
public function getPrefix(): ?string;
}
+24 -12
View File
@@ -1,7 +1,9 @@
<?php
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface ILoadableRoute extends IRoute
{
@@ -14,25 +16,35 @@ interface ILoadableRoute extends IRoute
* @param string|null $name
* @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 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.
*
* @return string
* @return string|null
*/
public function getName();
public function getName(): ?string;
/**
* Check if route has given name.
@@ -40,22 +52,22 @@ interface ILoadableRoute extends IRoute
* @param string $name
* @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.
*
* @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).
*
* @return string
*/
public function getMatch();
public function getMatch(): ?string;
/**
* Add regular expression match for the entire route.
@@ -63,6 +75,6 @@ interface ILoadableRoute extends IRoute
* @param string $regex
* @return static
*/
public function setMatch($regex);
public function setMatch($regex): self;
}
+58 -36
View File
@@ -3,6 +3,7 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Router;
interface IRoute
{
@@ -13,17 +14,18 @@ interface IRoute
* @param Request $request
* @return bool
*/
public function matchRoute($route, Request $request);
public function matchRoute($route, Request $request): bool;
/**
* Called when route is matched.
* Returns class to be rendered.
*
* @param Request $request
* @param Router $router
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return string
*/
public function renderRoute(Request $request);
public function renderRoute(Request $request, Router $router): ?string;
/**
* Returns callback name/identifier for the current route based on the callback.
@@ -32,50 +34,50 @@ interface IRoute
*
* @return string
*/
public function getIdentifier();
public function getIdentifier(): string;
/**
* Set allowed request methods
*
* @param array $methods
* @return static $this
* @return static
*/
public function setRequestMethods(array $methods);
public function setRequestMethods(array $methods): self;
/**
* Get allowed request methods
*
* @return array
*/
public function getRequestMethods();
public function getRequestMethods(): array;
/**
* @return IRoute|null
*/
public function getParent();
public function getParent(): ?IRoute;
/**
* Get the group for the route.
*
* @return IGroupRoute|null
*/
public function getGroup();
public function getGroup(): ?IGroupRoute;
/**
* Set group
*
* @param IGroupRoute $group
* @return static $this
* @return static
*/
public function setGroup(IGroupRoute $group);
public function setGroup(IGroupRoute $group): self;
/**
* Set parent route
*
* @param IRoute $parent
* @return static $this
* @return static
*/
public function setParent(IRoute $parent);
public function setParent(IRoute $parent): self;
/**
* Set callback
@@ -83,44 +85,64 @@ interface IRoute
* @param string $callback
* @return static
*/
public function setCallback($callback);
public function setCallback($callback): self;
/**
* @return string
* @return string|callable
*/
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
* @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
* @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.
*
* @return array
*/
public function getWhere();
public function getWhere(): array;
/**
* Set parameter names.
@@ -128,45 +150,45 @@ interface IRoute
* @param array $options
* @return static
*/
public function setWhere(array $options);
public function setWhere(array $options): self;
/**
* Get parameters
*
* @return array
*/
public function getParameters();
public function getParameters(): array;
/**
* Get 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.
*
* @param array $settings
* @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.
*
* @return array
*/
public function toArray();
public function toArray(): array;
/**
* Get middlewares array
*
* @return array
*/
public function getMiddlewares();
public function getMiddlewares(): array;
/**
* Set middleware class-name
@@ -174,14 +196,14 @@ interface IRoute
* @param string $middleware
* @return static
*/
public function addMiddleware($middleware);
public function addMiddleware($middleware): self;
/**
* Set middlewares array
*
* @param array $middlewares
* @return $this
* @return static
*/
public function setMiddlewares(array $middlewares);
public function setMiddlewares(array $middlewares): self;
}
+25 -17
View File
@@ -5,6 +5,7 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Router;
abstract class LoadableRoute extends Route implements ILoadableRoute
{
@@ -24,13 +25,16 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* Loads and renders middlewares-classes
*
* @param Request $request
* @param Router $router
* @throws HttpException
*/
public function loadMiddleware(Request $request)
public function loadMiddleware(Request $request, Router $router): void
{
$router->debug('Loading middlewares');
foreach ($this->getMiddlewares() as $middleware) {
if (is_object($middleware) === false) {
if (\is_object($middleware) === false) {
$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');
}
$router->debug('Loading middleware "%s"', \get_class($middleware));
$middleware->handle($request);
$router->debug('Finished loading middleware');
}
$router->debug('Finished loading middlewares');
}
public function matchRegex(Request $request, $url)
public function matchRegex(Request $request, $url): ?bool
{
/* Match on custom defined regular expression */
@@ -59,7 +67,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $url
* @return static
*/
public function setUrl($url)
public function setUrl(string $url): ILoadableRoute
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
@@ -75,7 +83,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return $this;
}
public function getUrl()
public function getUrl(): string
{
return $this->url;
}
@@ -89,13 +97,13 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null)
public function findUrl($method = null, $parameters = null, $name = null): string
{
$url = $this->getUrl();
$group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0) {
if ($group !== null && \count($group->getDomains()) !== 0) {
$url = '//' . $group->getDomains()[0] . $url;
}
@@ -114,7 +122,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
foreach (array_keys($params) as $param) {
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
if ($parameters === '' || (\is_array($parameters) === true && \count($parameters) === 0)) {
$value = '';
} else {
$p = (array)$parameters;
@@ -144,7 +152,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
public function getName()
public function getName(): string
{
return $this->name;
}
@@ -155,9 +163,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $name
* @return bool
*/
public function hasName($name)
public function hasName(string $name): bool
{
return (strtolower($this->name) === strtolower($name));
return strtolower($this->name) === strtolower($name);
}
/**
@@ -166,7 +174,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string $regex
* @return static
*/
public function setMatch($regex)
public function setMatch($regex): ILoadableRoute
{
$this->regex = $regex;
@@ -178,7 +186,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
*
* @return string
*/
public function getMatch()
public function getMatch(): string
{
return $this->regex;
}
@@ -191,7 +199,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param string|array $name
* @return static
*/
public function name($name)
public function name($name): ILoadableRoute
{
return $this->setName($name);
}
@@ -200,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.
*
* @param string $name
* @return static $this
* @return static
*/
public function setName($name)
public function setName(string $name): ILoadableRoute
{
$this->name = $name;
@@ -216,7 +224,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['as']) === true) {
+75 -64
View File
@@ -5,18 +5,19 @@ namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
use Pecee\SimpleRouter\Router;
abstract class Route implements IRoute
{
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
const PARAMETERS_DEFAULT_REGEX = '[\w]+';
protected const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
protected const PARAMETERS_DEFAULT_REGEX = '[\w]+';
const REQUEST_TYPE_GET = 'get';
const REQUEST_TYPE_POST = 'post';
const REQUEST_TYPE_PUT = 'put';
const REQUEST_TYPE_PATCH = 'patch';
const REQUEST_TYPE_OPTIONS = 'options';
const REQUEST_TYPE_DELETE = 'delete';
public const REQUEST_TYPE_GET = 'get';
public const REQUEST_TYPE_POST = 'post';
public const REQUEST_TYPE_PUT = 'put';
public const REQUEST_TYPE_PATCH = 'patch';
public const REQUEST_TYPE_OPTIONS = 'options';
public const REQUEST_TYPE_DELETE = 'delete';
public static $requestTypes = [
self::REQUEST_TYPE_GET,
@@ -59,10 +60,10 @@ abstract class Route implements IRoute
/**
* Load class by name
* @param string $name
* @return mixed
* @return object
* @throws NotFoundHttpException
*/
protected function loadClass($name)
protected function loadClass($name): object
{
if (class_exists($name) === false) {
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404);
@@ -75,21 +76,25 @@ abstract class Route implements IRoute
* Render route
*
* @param Request $request
* @return string|mixed
* @param Router $router
* @return string|null
* @throws NotFoundHttpException
*/
public function renderRoute(Request $request)
public function renderRoute(Request $request, Router $router): ?string
{
$router->debug('Starting rendering route');
$callback = $this->getCallback();
if ($callback === null) {
return null;
}
$router->debug('Parsing parameters');
$parameters = $this->getParameters();
$router->debug('Finished parsing parameters');
/* Filter parameters with null-value */
if ($this->filterEmptyParams === true) {
$parameters = array_filter($parameters, function ($var) {
return ($var !== null);
@@ -97,9 +102,12 @@ abstract class Route implements IRoute
}
/* Render callback function */
if (is_callable($callback) === true) {
if (\is_callable($callback) === true) {
$router->debug('Executing callback');
/* 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 */
@@ -109,6 +117,7 @@ abstract class Route implements IRoute
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
$router->debug('Loading class %s', $className);
$class = $this->loadClass($className);
$method = $controller[1];
@@ -116,7 +125,9 @@ abstract class Route implements IRoute
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)
@@ -138,7 +149,7 @@ abstract class Route implements IRoute
$regex = '';
if ($key < count($parameters[1])) {
if ($key < \count($parameters[1])) {
$name = $parameters[1][$key];
@@ -151,7 +162,7 @@ abstract class Route implements IRoute
if ($parameterRegex !== null) {
$regex = $parameterRegex;
} else {
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex;
$regex = $this->defaultParameterRegex ?? static::PARAMETERS_DEFAULT_REGEX;
}
}
@@ -189,9 +200,9 @@ abstract class Route implements IRoute
*
* @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;
}
@@ -202,9 +213,9 @@ abstract class Route implements IRoute
* Set allowed request methods
*
* @param array $methods
* @return static $this
* @return static
*/
public function setRequestMethods(array $methods)
public function setRequestMethods(array $methods): IRoute
{
$this->requestMethods = $methods;
@@ -216,7 +227,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getRequestMethods()
public function getRequestMethods(): array
{
return $this->requestMethods;
}
@@ -224,7 +235,7 @@ abstract class Route implements IRoute
/**
* @return IRoute|null
*/
public function getParent()
public function getParent(): ?IRoute
{
return $this->parent;
}
@@ -234,7 +245,7 @@ abstract class Route implements IRoute
*
* @return IGroupRoute|null
*/
public function getGroup()
public function getGroup(): ?IGroupRoute
{
return $this->group;
}
@@ -243,9 +254,9 @@ abstract class Route implements IRoute
* Set group
*
* @param IGroupRoute $group
* @return static $this
* @return static
*/
public function setGroup(IGroupRoute $group)
public function setGroup(IGroupRoute $group): IRoute
{
$this->group = $group;
@@ -259,9 +270,9 @@ abstract class Route implements IRoute
* Set parent route
*
* @param IRoute $parent
* @return static $this
* @return static
*/
public function setParent(IRoute $parent)
public function setParent(IRoute $parent): IRoute
{
$this->parent = $parent;
@@ -274,7 +285,7 @@ abstract class Route implements IRoute
* @param string $callback
* @return static
*/
public function setCallback($callback)
public function setCallback($callback): IRoute
{
$this->callback = $callback;
@@ -282,16 +293,16 @@ abstract class Route implements IRoute
}
/**
* @return string
* @return string|callable
*/
public function getCallback()
{
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);
return $tmp[1];
@@ -300,9 +311,9 @@ abstract class Route implements IRoute
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);
return $tmp[0];
@@ -311,14 +322,14 @@ abstract class Route implements IRoute
return null;
}
public function setMethod($method)
public function setMethod(string $method): IRoute
{
$this->callback = sprintf('%s@%s', $this->getClass(), $method);
return $this;
}
public function setClass($class)
public function setClass(string $class): IRoute
{
$this->callback = sprintf('%s@%s', $class, $this->getMethod());
@@ -327,9 +338,9 @@ abstract class Route implements IRoute
/**
* @param string $namespace
* @return static $this
* @return static
*/
public function setNamespace($namespace)
public function setNamespace(string $namespace): IRoute
{
$this->namespace = $namespace;
@@ -338,26 +349,26 @@ abstract class Route implements IRoute
/**
* @param string $namespace
* @return static $this
* @return static
*/
public function setDefaultNamespace($namespace)
public function setDefaultNamespace($namespace): IRoute
{
$this->defaultNamespace = $namespace;
return $this;
}
public function getDefaultNamespace()
public function getDefaultNamespace(): ?string
{
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;
}
/**
@@ -365,7 +376,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function toArray()
public function toArray(): array
{
$values = [];
@@ -373,15 +384,15 @@ abstract class Route implements IRoute
$values['namespace'] = $this->namespace;
}
if (count($this->requestMethods) !== 0) {
if (\count($this->requestMethods) !== 0) {
$values['method'] = $this->requestMethods;
}
if (count($this->where) !== 0) {
if (\count($this->where) !== 0) {
$values['where'] = $this->where;
}
if (count($this->middlewares) !== 0) {
if (\count($this->middlewares) !== 0) {
$values['middleware'] = $this->middlewares;
}
@@ -397,9 +408,9 @@ abstract class Route implements IRoute
*
* @param array $values
* @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) {
$this->setNamespace($values['namespace']);
@@ -434,7 +445,7 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getWhere()
public function getWhere(): array
{
return $this->where;
}
@@ -445,7 +456,7 @@ abstract class Route implements IRoute
* @param array $options
* @return static
*/
public function setWhere(array $options)
public function setWhere(array $options): IRoute
{
$this->where = $options;
@@ -470,12 +481,12 @@ abstract class Route implements IRoute
*
* @return array
*/
public function getParameters()
public function getParameters(): array
{
/* Sort the parameters after the user-defined param order, if any */
$parameters = [];
if (count($this->originalParameters) !== 0) {
if (\count($this->originalParameters) !== 0) {
$parameters = $this->originalParameters;
}
@@ -486,15 +497,15 @@ abstract class Route implements IRoute
* Get 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
* 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;
}
@@ -523,7 +534,7 @@ abstract class Route implements IRoute
* @param IMiddleware|string $middleware
* @return static
*/
public function addMiddleware($middleware)
public function addMiddleware($middleware): IRoute
{
$this->middlewares[] = $middleware;
@@ -534,9 +545,9 @@ abstract class Route implements IRoute
* Set middlewares array
*
* @param array $middlewares
* @return $this
* @return static
*/
public function setMiddlewares(array $middlewares)
public function setMiddlewares(array $middlewares): IRoute
{
$this->middlewares = $middlewares;
@@ -546,7 +557,7 @@ abstract class Route implements IRoute
/**
* @return array
*/
public function getMiddlewares()
public function getMiddlewares(): array
{
return $this->middlewares;
}
@@ -556,7 +567,7 @@ abstract class Route implements IRoute
* This is used when no custom parameter regex is found.
*
* @param string $regex
* @return static $this
* @return static
*/
public function setDefaultParameterRegex($regex)
{
@@ -570,7 +581,7 @@ abstract class Route implements IRoute
*
* @return string
*/
public function getDefaultParameterRegex()
public function getDefaultParameterRegex(): string
{
return $this->defaultParameterRegex;
}
@@ -24,7 +24,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
public function hasName($name)
public function hasName(string $name): bool
{
if ($this->name === null) {
return false;
@@ -35,7 +35,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
if (in_array($method, $this->names, false) === true && strtolower($this->name) === strtolower($newName)) {
if (\in_array($method, $this->names, true) === true && strtolower($this->name) === strtolower($newName)) {
return true;
}
}
@@ -49,7 +49,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string|null $name
* @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) {
$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) {
if (stripos($method, $requestType) === 0) {
$method = (string)substr($method, strlen($requestType));
$method = (string)substr($method, \strlen($requestType));
break;
}
}
@@ -77,7 +77,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
$group = $this->getGroup();
if ($group !== null && count($group->getDomains()) !== 0) {
if ($group !== null && \count($group->getDomains()) !== 0) {
$url .= '//' . $group->getDomains()[0];
}
@@ -86,9 +86,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
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) {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -102,12 +102,12 @@ class RouteController extends LoadableRoute implements IControllerRoute
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl);
if (count($path) !== 0) {
if (\count($path) !== 0) {
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method);
$this->parameters = array_slice($path, 1);
$this->parameters = \array_slice($path, 1);
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
@@ -123,7 +123,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
*
* @return string
*/
public function getController()
public function getController(): string
{
return $this->controller;
}
@@ -134,7 +134,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
public function setController($controller)
public function setController(string $controller): IControllerRoute
{
$this->controller = $controller;
@@ -144,9 +144,9 @@ class RouteController extends LoadableRoute implements IControllerRoute
/**
* Return active method
*
* @return string
* @return string|null
*/
public function getMethod()
public function getMethod(): ?string
{
return $this->method;
}
@@ -157,7 +157,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param string $method
* @return static
*/
public function setMethod($method)
public function setMethod(string $method): IRoute
{
$this->method = $method;
@@ -171,7 +171,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['names']) === true) {
$this->names = $values['names'];
+19 -19
View File
@@ -18,9 +18,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @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;
}
@@ -28,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && count($parameters) !== 0) {
if ($parameters !== null && \count($parameters) !== 0) {
$this->parameters = $parameters;
@@ -46,9 +46,9 @@ class RouteGroup extends Route implements IGroupRoute
* @param Request $request
* @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) {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -64,9 +64,9 @@ class RouteGroup extends Route implements IGroupRoute
* Add exception handler
*
* @param IExceptionHandler|string $handler
* @return static $this
* @return static
*/
public function addExceptionHandler($handler)
public function addExceptionHandler($handler): IGroupRoute
{
$this->exceptionHandlers[] = $handler;
@@ -77,9 +77,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
* @return static
*/
public function setExceptionHandlers(array $handlers)
public function setExceptionHandlers(array $handlers): IGroupRoute
{
$this->exceptionHandlers = $handlers;
@@ -91,7 +91,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function getExceptionHandlers()
public function getExceptionHandlers(): array
{
return $this->exceptionHandlers;
}
@@ -101,7 +101,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function getDomains()
public function getDomains(): array
{
return $this->domains;
}
@@ -110,9 +110,9 @@ class RouteGroup extends Route implements IGroupRoute
* Set allowed domains for group.
*
* @param array $domains
* @return $this
* @return static
*/
public function setDomains(array $domains)
public function setDomains(array $domains): IGroupRoute
{
$this->domains = $domains;
@@ -123,7 +123,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param string $prefix
* @return static
*/
public function setPrefix($prefix)
public function setPrefix($prefix): IGroupRoute
{
$this->prefix = '/' . trim($prefix, '/');
@@ -133,9 +133,9 @@ class RouteGroup extends Route implements IGroupRoute
/**
* Set prefix that child-routes will inherit.
*
* @return string
* @return string|null
*/
public function getPrefix()
public function getPrefix(): ?string
{
return $this->prefix;
}
@@ -147,7 +147,7 @@ class RouteGroup extends Route implements IGroupRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['prefix']) === true) {
@@ -183,7 +183,7 @@ class RouteGroup extends Route implements IGroupRoute
*
* @return array
*/
public function toArray()
public function toArray(): array
{
$values = [];
@@ -195,7 +195,7 @@ class RouteGroup extends Route implements IGroupRoute
$values['as'] = $this->name;
}
if (count($this->parameters) !== 0) {
if (\count($this->parameters) !== 0) {
$values['parameters'] = $this->parameters;
}
@@ -15,12 +15,12 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
* @param Request $request
* @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) {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url);
+11 -11
View File
@@ -42,7 +42,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $name
* @return bool
*/
public function hasName($name)
public function hasName(string $name): bool
{
if ($this->name === null) {
return false;
@@ -60,7 +60,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
return (strtolower($this->name) === strtolower($name));
}
public function findUrl($method = null, $parameters = null, $name = null)
public function findUrl($method = null, $parameters = null, $name = null): string
{
$url = array_search($name, $this->names, false);
if ($url !== false) {
@@ -77,9 +77,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
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) {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
@@ -114,7 +114,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
}
// 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']);
}
@@ -145,7 +145,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* @return string
*/
public function getController()
public function getController(): string
{
return $this->controller;
}
@@ -154,14 +154,14 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param string $controller
* @return static
*/
public function setController($controller)
public function setController(string $controller): IControllerRoute
{
$this->controller = $controller;
return $this;
}
public function setName($name)
public function setName(string $name): ILoadableRoute
{
$this->name = $name;
@@ -194,9 +194,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
/**
* Get method names
*
* @return array $this
* @return array
*/
public function getMethodNames()
public function getMethodNames(): array
{
return $this->methodNames;
}
@@ -208,7 +208,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
public function setSettings(array $values, bool $merge = false): IRoute
{
if (isset($values['names']) === true) {
$this->names = $values['names'];
+2 -2
View File
@@ -12,9 +12,9 @@ class RouteUrl extends LoadableRoute
$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) {
if ($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
+204 -81
View File
@@ -66,6 +66,32 @@ class Router
*/
protected $exceptionHandlers;
/**
* List of loaded exception that has been loaded.
* Used to ensure that exception-handlers aren't loaded twice when rewriting route.
*
* @var array
*/
protected $loadedExceptionHandlers;
/**
* Enable or disabled debugging
* @var bool
*/
protected $debugEnabled = false;
/**
* The start time used when debugging is enabled
* @var float
*/
protected $debugStartTime;
/**
* List containing all debug messages
* @var array
*/
protected $debugList = [];
/**
* Router constructor.
* @throws \Pecee\Http\Exceptions\MalformedUrlException
@@ -78,7 +104,7 @@ class Router
/**
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public function reset()
public function reset(): void
{
$this->processingRoute = false;
$this->request = new Request();
@@ -87,6 +113,7 @@ class Router
$this->routeStack = [];
$this->processedRoutes = [];
$this->exceptionHandlers = [];
$this->loadedExceptionHandlers = [];
}
/**
@@ -94,7 +121,7 @@ class Router
* @param IRoute $route
* @return IRoute
*/
public function addRoute(IRoute $route)
public function addRoute(IRoute $route): IRoute
{
/*
* If a route is currently being processed, that means that the route being added are rendered from the parent
@@ -102,10 +129,12 @@ class Router
*/
if ($this->processingRoute === true) {
$this->routeStack[] = $route;
return $route;
}
$this->routes[] = $route;
return $route;
}
@@ -115,13 +144,14 @@ class Router
* @param IRoute $route
* @throws NotFoundHttpException
*/
protected function renderAndProcess(IRoute $route) {
protected function renderAndProcess(IRoute $route): void
{
$this->processingRoute = true;
$route->renderRoute($this->request);
$route->renderRoute($this->request, $this);
$this->processingRoute = false;
if (count($this->routeStack) !== 0) {
if (\count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
@@ -139,21 +169,27 @@ class Router
* @param IGroupRoute|null $group
* @throws NotFoundHttpException
*/
protected function processRoutes(array $routes, IGroupRoute $group = null)
protected function processRoutes(array $routes, ?IGroupRoute $group = null): void
{
$this->debug('Processing routes');
// Loop through each route-request
$exceptionHandlers = [];
// 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;
}
$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) {
$this->debug('Processing route "%s"', \get_class($route));
if ($group !== null) {
/* Add the parent group */
$route->setGroup($group);
@@ -165,7 +201,7 @@ class Router
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
if (count($route->getExceptionHandlers()) !== 0) {
if (\count($route->getExceptionHandlers()) !== 0) {
/** @noinspection AdditionOperationOnArraysInspection */
$exceptionHandlers += $route->getExceptionHandlers();
}
@@ -199,29 +235,37 @@ class Router
* @throws NotFoundHttpException
* @return void
*/
public function loadRoutes()
public function loadRoutes(): void
{
$this->debug('Loading routes');
/* Initialize boot-managers */
/* @var $manager IRouterBootManager */
foreach ($this->bootManagers as $manager) {
$this->debug('Rendering bootmanager %s', \get_class($manager));
$manager->boot($this->request);
$this->debug('Finished rendering bootmanager');
}
/* Loop through each route-request */
$this->processRoutes($this->routes);
$this->debug('Finished loading routes');
}
/**
* Routes the request
*
* @param bool $rewrite
* @return string|mixed
* @return string|null
* @throws HttpException
* @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 {
@@ -233,47 +277,46 @@ class Router
/* Verify csrf token for 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 */
foreach ($this->processedRoutes as $key => $route) {
$this->debug('Matching route "%s"', \get_class($route));
/* If the route matches */
if ($route->matchRoute($url, $this->request) === true) {
/* Check if request method matches */
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
$routeNotAllowed = true;
if (\count($route->getRequestMethods()) !== 0 && \in_array($this->request->getMethod(), $route->getRequestMethods(), true) === false) {
$this->debug('Method "%s" not allowed', $this->request->getMethod());
$methodNotAllowed = true;
continue;
}
$route->loadMiddleware($this->request);
$route->loadMiddleware($this->request, $this);
if ($this->hasRewrite($url) === true) {
unset($this->processedRoutes[$key]);
return $this->routeRequest(true);
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
}
/* 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) {
return $output;
}
if ($this->hasRewrite($url) === true) {
unset($this->processedRoutes[$key]);
return $this->routeRequest(true);
$output = $this->handleRouteRewrite($key, $url);
if ($output !== null) {
return $output;
}
}
}
@@ -282,12 +325,12 @@ class Router
$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());
$this->handleException(new HttpException($message, 403));
}
if ($this->request->getLoadedRoute() === null) {
if (\count($this->request->getLoadedRoutes()) === 0) {
$rewriteUrl = $this->request->getRewriteUrl();
@@ -297,63 +340,80 @@ class Router
$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;
}
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 ($this->request->hasRewrite() === true) {
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;
}
if ($this->request->hasRewrite() === false) {
return null;
}
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
* @throws HttpException
* @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 */
foreach ($this->exceptionHandlers as $key => $handler) {
if (is_object($handler) === false) {
if (\is_object($handler) === false) {
$handler = new $handler();
}
$this->debug('Processing exception-handler "%s"', \get_class($handler));
if (($handler instanceof IExceptionHandler) === false) {
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
}
try {
$this->debug('Start rendering exception handler');
$handler->handleError($this->request, $e);
$this->debug('Finished rendering exception-handler');
if ($this->request->hasRewrite() === true) {
unset($this->exceptionHandlers[$key]);
$this->exceptionHandlers = array_values($this->exceptionHandlers);
if (isset($this->loadedExceptionHandlers[$key]) === false && $this->request->hasRewrite() === true) {
$this->loadedExceptionHandlers[$key] = $handler;
$this->debug('Exception handler contains rewrite, reloading routes');
return $this->routeRequest(true);
}
@@ -361,14 +421,17 @@ class Router
} catch (\Exception $e) {
}
$this->debug('Finished processing');
}
$this->debug('Finished exception handling - exception not handled, throwing');
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) {
$getParams = array_filter($getParams, function ($item) {
@@ -388,45 +451,60 @@ class Router
* @param string $name
* @return ILoadableRoute|null
*/
public function findRoute($name)
public function findRoute(string $name): ?ILoadableRoute
{
$this->debug('Finding route by name "%s"', $name);
/* @var $route ILoadableRoute */
foreach ($this->processedRoutes as $route) {
/* 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;
}
/* Direct match to controller */
if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) {
$this->debug('Found route "%s" by controller "%s"', $route->getUrl(), $name);
return $route;
}
/* Using @ is most definitely a controller@method or alias@method */
if (is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = array_map('strtolower', explode('@', $name));
if (\is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = array_map('strtolower', explode('@', $name));
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
$this->debug('Found route "%s" by controller "%s" and method "%s"', $route->getUrl(), $controller, $method);
return $route;
}
}
/* Check if callback matches (if it's not a function) */
if (is_string($name) === true && is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && is_callable($route->getCallback()) === false) {
if (\is_string($name) === true && \is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && \is_callable($route->getCallback()) === false) {
/* Check if the entire callback is matching */
if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
$this->debug('Found route "%s" by callback "%s"', $route->getUrl(), $name);
return $route;
}
/* Check if the class part of the callback matches (class@method) */
if (strtolower($name) === strtolower($route->getClass())) {
$this->debug('Found route "%s" by class "%s"', $route->getUrl(), $name);
return $route;
}
}
}
$this->debug('Route not found');
return null;
}
@@ -448,9 +526,11 @@ class Router
* @throws InvalidArgumentException
* @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');
}
@@ -485,8 +565,8 @@ class Router
}
/* Using @ is most definitely a controller@method or alias@method */
if (is_string($name) === true && strpos($name, '@') !== false) {
list($controller, $method) = explode('@', $name);
if (\is_string($name) === true && strpos($name, '@') !== false) {
[$controller, $method] = explode('@', $name);
/* Loop through all the routes to see if we can find a match */
@@ -513,28 +593,28 @@ class Router
}
/**
* Get bootmanagers
* Get BootManagers
* @return array
*/
public function getBootManagers()
public function getBootManagers(): array
{
return $this->bootManagers;
}
/**
* Set bootmanagers
* Set BootManagers
* @param array $bootManagers
*/
public function setBootManagers(array $bootManagers)
public function setBootManagers(array $bootManagers): void
{
$this->bootManagers = $bootManagers;
}
/**
* Add bootmanager
* Add BootManager
* @param IRouterBootManager $bootManager
*/
public function addBootManager(IRouterBootManager $bootManager)
public function addBootManager(IRouterBootManager $bootManager): void
{
$this->bootManagers[] = $bootManager;
}
@@ -544,7 +624,7 @@ class Router
*
* @return array
*/
public function getProcessedRoutes()
public function getProcessedRoutes(): array
{
return $this->processedRoutes;
}
@@ -552,7 +632,7 @@ class Router
/**
* @return array
*/
public function getRoutes()
public function getRoutes(): array
{
return $this->routes;
}
@@ -561,9 +641,9 @@ class Router
* Set routes
*
* @param array $routes
* @return static $this
* @return static
*/
public function setRoutes(array $routes)
public function setRoutes(array $routes): self
{
$this->routes = $routes;
@@ -575,7 +655,7 @@ class Router
*
* @return Request
*/
public function getRequest()
public function getRequest(): Request
{
return $this->request;
}
@@ -584,7 +664,7 @@ class Router
* Get csrf verifier class
* @return BaseCsrfVerifier
*/
public function getCsrfVerifier()
public function getCsrfVerifier(): ?BaseCsrfVerifier
{
return $this->csrfVerifier;
}
@@ -602,4 +682,47 @@ class Router
return $this;
}
/**
* Add new debug message
* @param string $message
* @param array $args
*/
public function debug(string $message, ...$args): void
{
if ($this->debugEnabled === false) {
return;
}
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$this->debugList[] = [
'message' => vsprintf($message, $args),
'time' => number_format(microtime(true) - $this->debugStartTime, 10),
'trace' => end($trace),
];
}
/**
* Enable or disables debugging
*
* @param bool $boolean
*/
public function setDebugEnabled(bool $boolean): void
{
if ($boolean === true) {
$this->debugStartTime = microtime(true);
}
$this->debugEnabled = $boolean;
}
/**
* Get the list containing all debug messages.
*
* @return array
*/
public function getDebugLog(): array
{
return $this->debugList;
}
}
+89 -31
View File
@@ -13,12 +13,15 @@ namespace Pecee\SimpleRouter;
use Pecee\Exceptions\InvalidArgumentException;
use Pecee\Handlers\CallbackExceptionHandler;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use Pecee\Http\Request;
use Pecee\Http\Response;
use Pecee\SimpleRouter\Exceptions\HttpException;
use Pecee\SimpleRouter\Route\IGroupRoute;
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
use Pecee\SimpleRouter\Route\IRoute;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteController;
use Pecee\SimpleRouter\Route\RouteGroup;
use Pecee\SimpleRouter\Route\RoutePartialGroup;
use Pecee\SimpleRouter\Route\RouteResource;
use Pecee\SimpleRouter\Route\RouteUrl;
@@ -26,7 +29,7 @@ class SimpleRouter
{
/**
* Default namespace added to all routes
* @var string
* @var string|null
*/
protected static $defaultNamespace;
@@ -43,21 +46,76 @@ class SimpleRouter
protected static $router;
/**
* Start routing
*
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws HttpException
* @throws \Exception
*/
public static function start()
public static function start(): void
{
echo static::router()->routeRequest();
}
/**
* Start the routing an return array with debugging-information
*
* @return array
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function startDebug(): array
{
$routerOutput = null;
try {
ob_start();
static::router()->setDebugEnabled(true);
static::start();
$routerOutput = ob_get_contents();
ob_end_clean();
} catch (\Exception $e) {
}
// Try to parse library version
$composerFile = \dirname(__DIR__, 3) . '/composer.lock';
$version = false;
if (is_file($composerFile) === true) {
$composerInfo = json_decode(file_get_contents($composerFile), true);
if (isset($composerInfo['packages']) === true && \is_array($composerInfo['packages']) === true) {
foreach ($composerInfo['packages'] as $package) {
if (isset($package['name']) === true && strtolower($package['name']) === 'pecee/simple-router') {
$version = $package['version'];
break;
}
}
}
}
return [
'url' => static::request()->getUrl(),
'method' => static::request()->getMethod(),
'host' => static::request()->getHost(),
'loaded_routes' => static::request()->getLoadedRoutes(),
'all_routes' => static::router()->getRoutes(),
'boot_managers' => static::router()->getBootManagers(),
'csrf_verifier' => static::router()->getCsrfVerifier(),
'log' => static::router()->getDebugLog(),
'router_output' => $routerOutput,
'library_version' => $version,
'php_version' => PHP_VERSION,
'server_params' => static::request()->getHeaders(),
];
}
/**
* Set default namespace which will be prepended to all routes.
*
* @param string $defaultNamespace
*/
public static function setDefaultNamespace($defaultNamespace)
public static function setDefaultNamespace(string $defaultNamespace): void
{
static::$defaultNamespace = $defaultNamespace;
}
@@ -68,7 +126,7 @@ class SimpleRouter
* @param BaseCsrfVerifier $baseCsrfVerifier
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier): void
{
static::router()->setCsrfVerifier($baseCsrfVerifier);
}
@@ -80,7 +138,7 @@ class SimpleRouter
* @param IRouterBootManager $bootManager
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function addBootManager(IRouterBootManager $bootManager)
public static function addBootManager(IRouterBootManager $bootManager): void
{
static::router()->addBootManager($bootManager);
}
@@ -95,7 +153,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -109,7 +167,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -123,7 +181,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -137,7 +195,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -151,7 +209,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -165,7 +223,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -179,9 +237,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @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');
}
@@ -205,9 +263,9 @@ class SimpleRouter
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @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');
}
@@ -232,7 +290,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -248,7 +306,7 @@ class SimpleRouter
* @return RouteUrl
* @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);
}
@@ -263,7 +321,7 @@ class SimpleRouter
* @return RouteUrl|IRoute
* @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->setRequestMethods($requestMethods);
@@ -287,7 +345,7 @@ class SimpleRouter
* @return RouteUrl|IRoute
* @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 = static::addDefaultNamespace($route);
@@ -310,7 +368,7 @@ class SimpleRouter
* @return RouteController|IRoute
* @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 = static::addDefaultNamespace($route);
@@ -333,7 +391,7 @@ class SimpleRouter
* @return RouteResource|IRoute
* @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 = static::addDefaultNamespace($route);
@@ -354,7 +412,7 @@ class SimpleRouter
* @return CallbackExceptionHandler $callbackHandler
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function error(\Closure $callback)
public static function error(\Closure $callback): CallbackExceptionHandler
{
$routes = static::router()->getRoutes();
@@ -389,7 +447,7 @@ class SimpleRouter
* @return string
* @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);
}
@@ -400,7 +458,7 @@ class SimpleRouter
* @return \Pecee\Http\Request
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function request()
public static function request(): Request
{
return static::router()->getRequest();
}
@@ -411,7 +469,7 @@ class SimpleRouter
* @return Response
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function response()
public static function response(): Response
{
if (static::$response === null) {
static::$response = new Response(static::request());
@@ -426,7 +484,7 @@ class SimpleRouter
* @return Router
* @throws \Pecee\Http\Exceptions\MalformedUrlException
*/
public static function router()
public static function router(): Router
{
if (static::$router === null) {
static::$router = new Router();
@@ -441,14 +499,14 @@ class SimpleRouter
* @param IRoute $route
* @return IRoute
*/
public static function addDefaultNamespace(IRoute $route)
public static function addDefaultNamespace(IRoute $route): IRoute
{
if (static::$defaultNamespace !== null) {
$callback = $route->getCallback();
/* Only add default namespace on relative callbacks */
if ($callback === null || (is_string($callback) === true && $callback[0] !== '\\')) {
if ($callback === null || (\is_string($callback) === true && $callback[0] !== '\\')) {
$namespace = static::$defaultNamespace;
@@ -468,9 +526,9 @@ class SimpleRouter
/**
* Get default namespace
* @return string
* @return string|null
*/
public static function getDefaultNamespace()
public static function getDefaultNamespace(): ?string
{
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
require_once 'Exceptions/MiddlewareLoadedException.php';
require_once 'Exception/MiddlewareLoadedException.php';
use Pecee\Http\Request;
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
{
public function handle(Request $request)
public function handle(Request $request) : void
{
throw new MiddlewareLoadedException('Middleware loaded!');
}
@@ -1,4 +1,5 @@
<?php
class ExceptionHandlerException extends \Exception
{
}
@@ -2,7 +2,7 @@
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();
}
@@ -2,13 +2,12 @@
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;
$stack[] = static::class;
$request->setUrl('/');
return $request;
}
}
@@ -2,13 +2,12 @@
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;
$stack[] = static::class;
$request->setUrl('/');
return $request;
}
}
@@ -2,7 +2,7 @@
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;
$stack[] = static::class;
@@ -5,7 +5,7 @@ use Pecee\Http\Request;
class RewriteMiddleware implements IMiddleware {
public function handle(Request $request) {
public function handle(Request $request) : void {
$request->setRewriteCallback(function() {
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/DummyController.php';
require_once 'Helpers/TestRouter.php';
class GroupTest extends PHPUnit_Framework_TestCase
class GroupTest extends \PHPUnit\Framework\TestCase
{
protected $result;
@@ -37,6 +36,7 @@ class GroupTest extends PHPUnit_Framework_TestCase
TestRouter::debug('/api/v1/test', 'get');
$this->assertTrue(true);
}
public function testMultipleRoutes()
@@ -61,6 +61,8 @@ class GroupTest extends PHPUnit_Framework_TestCase
});
TestRouter::debug('/my/match', 'get');
$this->assertTrue(true);
}
public function testUrls()
@@ -3,13 +3,12 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class MiddlewareTest extends PHPUnit_Framework_TestCase
class MiddlewareTest extends \PHPUnit\Framework\TestCase
{
public function testMiddlewareFound()
{
$this->setExpectedException(MiddlewareLoadedException::class);
$this->expectException(MiddlewareLoadedException::class);
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
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::debug('/my/test/url', 'get');
$this->assertTrue(true);
}
}
@@ -2,15 +2,14 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
require_once 'Dummy/Exception/ExceptionHandlerException.php';
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
class RouterCallbackExceptionHandlerTest extends \PHPUnit\Framework\TestCase
{
public function testCallbackExceptionHandler()
{
$this->setExpectedException(ExceptionHandlerException::class);
$this->expectException(ExceptionHandlerException::class);
// Match normal route on alias
TestRouter::get('/my-new-url', 'DummyController@method2');
@@ -22,6 +21,8 @@ class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
TestRouter::debugNoReset('/404-url', 'get');
TestRouter::router()->reset();
$this->assertTrue(true);
}
}
@@ -1,9 +1,8 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class RouterControllerTest extends PHPUnit_Framework_TestCase
class RouterControllerTest extends \PHPUnit\Framework\TestCase
{
public function testGet()
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterPartialGroupTest extends PHPUnit_Framework_TestCase
class RouterPartialGroupTest extends \PHPUnit\Framework\TestCase
{
public function testParameters()
@@ -1,9 +1,8 @@
<?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()
@@ -1,13 +1,12 @@
<?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/ExceptionHandlerSecond.php';
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
require_once 'Helpers/TestRouter.php';
require_once 'Dummy/Middlewares/RewriteMiddleware.php';
require_once 'Dummy/Middleware/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()
{
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
$this->expectException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
@@ -2,10 +2,9 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
require_once 'Dummy/Exception/ExceptionHandlerException.php';
class RouterRouteTest extends PHPUnit_Framework_TestCase
class RouterRouteTest extends \PHPUnit\Framework\TestCase
{
protected $result = false;
@@ -27,7 +26,7 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
public function testNotFound()
{
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
$this->expectException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post');
}
@@ -36,24 +35,32 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
$this->assertTrue(true);
}
public function testPost()
{
TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post');
$this->assertTrue(true);
}
public function testPut()
{
TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'put');
$this->assertTrue(true);
}
public function testDelete()
{
TestRouter::delete('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'delete');
$this->assertTrue(true);
}
public function testMethodNotAllowed()
@@ -123,6 +130,8 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
{
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
TestRouter::debug('/my/custom-path', 'get');
$this->assertTrue(true);
}
public function testParameterDefaultValue() {
@@ -3,9 +3,8 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
require_once 'Helpers/TestRouter.php';
class RouterUrlTest extends PHPUnit_Framework_TestCase
class RouterUrlTest extends \PHPUnit\Framework\TestCase
{
public function testIssue253()
@@ -32,21 +31,22 @@ class RouterUrlTest extends PHPUnit_Framework_TestCase
{
// Test spanish characters
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
TestRouter::debugNoReset('/test/Dermatología');
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
$this->assertEquals('Dermatología', $parameters['param']);
// Test danish characters
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
TestRouter::debugNoReset('/kategori/økse', 'get');
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
TestRouter::debugNoReset('/test/Dermatología');
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
$this->assertEquals('Dermatología', $parameters['param']);
TestRouter::router()->reset();
}
+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;