mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
209 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0090c167bb | |||
| ae68598024 | |||
| 7362b748af | |||
| 4fe85d6568 | |||
| c82d91375c | |||
| e774122b1e | |||
| e8aceb291c | |||
| 957a382248 | |||
| 48e2e3f9bc | |||
| f95e12c49c | |||
| 9f509ac818 | |||
| 3b4d23e9ae | |||
| b3e99a2283 | |||
| c1aa5782a1 | |||
| 387d9710d8 | |||
| fd098266f7 | |||
| c7473938c5 | |||
| 65c811356d | |||
| ea255baec3 | |||
| acf37c4023 | |||
| 6fb92d7cae | |||
| e84c8c2f02 | |||
| 7c970c442c | |||
| 4cd1e8e069 | |||
| 8720e732e1 | |||
| 7e8cb91f68 | |||
| bc67038e11 | |||
| e31d8af2f7 | |||
| 9f285fd0ce | |||
| b7f5d31544 | |||
| 5086347802 | |||
| 26f89213a2 | |||
| bb7991afdc | |||
| 796d01bc25 | |||
| 74187ee326 | |||
| f090d6c038 | |||
| 6e859e11ab | |||
| 6aa38cfa4c | |||
| 62f0075cf3 | |||
| 6890b60737 | |||
| a40f81d5fc | |||
| a5527a0e8c | |||
| 3c73de866e | |||
| 883d8a6b0e | |||
| 3a7b27796a | |||
| 1e07140865 | |||
| 4cca5186f3 | |||
| 5437420175 | |||
| 410fa3c9f5 | |||
| be20fe4dd1 | |||
| bc03490100 | |||
| 0947f6746e | |||
| 31c8710ce7 | |||
| 1ac7761d35 | |||
| 9eb7c5c13c | |||
| 5151461a02 | |||
| b07348a3df | |||
| d411b31cc2 | |||
| ca381d445f | |||
| 2c61cef7ad | |||
| 98ee60859f | |||
| 9dd80dd1d9 | |||
| 3f9ab73f7f | |||
| fef997422e | |||
| 8901e7c125 | |||
| 50e8926272 | |||
| e44d6bc30b | |||
| 27ff761d18 | |||
| 0a58d36606 | |||
| db024b9588 | |||
| 3f61c90749 | |||
| 94d0764631 | |||
| ff3f1bdcdd | |||
| e4e632dca9 | |||
| a5c4a1f721 | |||
| 0bc7fa7bd5 | |||
| eb036ded3b | |||
| debe080181 | |||
| dd99e1d488 | |||
| 1c07311c5d | |||
| 801c84eb05 | |||
| ed98519152 | |||
| 55d031e152 | |||
| 8509062e00 | |||
| 4b4ab906fb | |||
| 9617cacc31 | |||
| 54a824ce44 | |||
| 99088719ed | |||
| 2062ff4189 | |||
| 3e41ee28b6 | |||
| 13a5f40cd0 | |||
| 751b4444ae | |||
| 351f7a01e8 | |||
| 8cd42a2c4b | |||
| 1496878ae9 | |||
| e8e1471bab | |||
| b3f2e5f812 | |||
| 4de1498723 | |||
| a60fa9f919 | |||
| ea243f2c89 | |||
| ce6f34f4d4 | |||
| 56653568e4 | |||
| 2868ffe023 | |||
| 5d330643e7 | |||
| 8ab52364da | |||
| 57aa8eac1e | |||
| 110bc2afcf | |||
| 4efc72d013 | |||
| a92a4cdf0d | |||
| 49fc991f9a | |||
| 0a4c78cf64 | |||
| 20353c6e4d | |||
| 6706d86784 | |||
| 4c62f86a26 | |||
| 20c1e0ef69 | |||
| 6445746324 | |||
| 1a2921acb4 | |||
| fe560a9ba5 | |||
| 258d9d05c7 | |||
| c522801c28 | |||
| 7e7319de06 | |||
| 9d275d6d3b | |||
| 531b35532b | |||
| e6dd9f3f55 | |||
| c258f937e8 | |||
| e803b1ca5c | |||
| 88d58cd7b7 | |||
| 45faf9830e | |||
| d04c74ccad | |||
| c915c0386a | |||
| 02809a4daf | |||
| 30479b15ca | |||
| da6b5af19f | |||
| 4dde51e833 | |||
| 914ec9d1b7 | |||
| 961a4d0e94 | |||
| 5f72755a98 | |||
| 2216090a5f | |||
| 41d15d3acd | |||
| d467f60e55 | |||
| ded9c8ebe0 | |||
| c30ae6b098 | |||
| 394f7beb8b | |||
| c93308c8e1 | |||
| baab004482 | |||
| c3241012af | |||
| 00c0cad211 | |||
| 9e2ba2674b | |||
| c6e85676da | |||
| 4d18f33a81 | |||
| 5a74c9d27d | |||
| 9d98b2da4c | |||
| b5eef6f3ee | |||
| 6930864e7e | |||
| ad0eceb814 | |||
| f3f129ae0b | |||
| 4bec2bc5fb | |||
| 85b9fac21e | |||
| 4f47463497 | |||
| 0c93633d13 | |||
| e5c86c1822 | |||
| 973344e46e | |||
| 32c305bd2c | |||
| 4a03005c68 | |||
| 52034411cf | |||
| 4c8ed5bb3d | |||
| 9fed6ffb3f | |||
| 15da599e82 | |||
| 9274acb591 | |||
| 5c7759ab72 | |||
| c7b8593185 | |||
| fb478f475c | |||
| 1142d9d4ce | |||
| 5d5c96e802 | |||
| bfdaf8ac52 | |||
| 71dc6e172f | |||
| 6ee172927f | |||
| bb5e629199 | |||
| 0cc0a59fd5 | |||
| 498fd6b07d | |||
| 96ab22a4f8 | |||
| 7f528c133b | |||
| 5a50190293 | |||
| 355ef01d63 | |||
| d3162b5a2b | |||
| 810b80487d | |||
| 18a9df56ca | |||
| 6e14ded03f | |||
| 899081f8d8 | |||
| e7b9206bc9 | |||
| cd6e800984 | |||
| 11bd5a7d11 | |||
| be32796b01 | |||
| 8b3d71a328 | |||
| 1fae638aaf | |||
| 37c8bc9f32 | |||
| 75029b330a | |||
| fd5d893040 | |||
| c1512740af | |||
| 212ae133de | |||
| ae58231fa1 | |||
| 358b25d4f1 | |||
| 3d45851d9b | |||
| ee5c2207f8 | |||
| b1ca3fc9ef | |||
| 253c0c70d4 | |||
| 53ba2d7ac5 | |||
| 315fe05769 | |||
| a57113309a |
+1
-2
@@ -1,4 +1,3 @@
|
||||
.idea
|
||||
composer.lock
|
||||
vendor/
|
||||
demo-project/vendor
|
||||
vendor/
|
||||
@@ -22,6 +22,7 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
- [Installation](#installation)
|
||||
- [Setting up Apache](#setting-up-apache)
|
||||
- [Setting up Nginx](#setting-up-nginx)
|
||||
- [Setting up IIS](#setting-up-iis)
|
||||
- [Configuration](#configuration)
|
||||
- [Helper functions](#helper-functions)
|
||||
|
||||
@@ -34,6 +35,7 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
- [Optional parameters](#optional-parameters)
|
||||
- [Regular expression constraints](#regular-expression-constraints)
|
||||
- [Regular expression route-match](#regular-expression-route-match)
|
||||
- [Custom regex for matching parameters](#custom-regex-for-matching-parameters)
|
||||
- [Named routes](#named-routes)
|
||||
- [Generating URLs To Named Routes](#generating-urls-to-named-routes)
|
||||
- [Router groups](#router-groups)
|
||||
@@ -51,8 +53,9 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
|
||||
- [Middlewares](#middlewares)
|
||||
- [Example](#example)
|
||||
- [ExceptionHandler](#exceptionhandler)
|
||||
- [Example](#example-1)
|
||||
- [ExceptionHandlers](#exceptionhandlers)
|
||||
- [Handling 404, 403 and other errors](#handling-404-403-and-other-errors)
|
||||
- [Using custom exception handlers](#using-custom-exception-handlers)
|
||||
|
||||
- [Urls](#urls)
|
||||
- [Get by name (single route)](#get-by-name-single-route)
|
||||
@@ -70,12 +73,13 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
- [Get all parameters](#get-all-parameters)
|
||||
|
||||
- [Advanced](#advanced)
|
||||
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
|
||||
- [Url rewriting](#url-rewriting)
|
||||
- [Rewrite using callback](#rewrite-using-callback)
|
||||
- [Rewrite using url](#rewrite-using-url)
|
||||
|
||||
- [Adding routes manually](#adding-routes-manually)
|
||||
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
|
||||
- [Adding routes manually](#adding-routes-manually)
|
||||
- [Parameters](#parameters)
|
||||
- [Custom default regex for matching parameters](#custom-default-regex-for-matching-parameters)
|
||||
- [Extending](#extending)
|
||||
|
||||
- [Credits](#credits)
|
||||
@@ -155,6 +159,59 @@ location / {
|
||||
|
||||
Nothing special is required for Apache to work. We've include the `.htaccess` file in the `public` folder. If rewriting is not working for you, please check that the `mod_rewrite` module (htaccess support) is enabled in the Apache configuration.
|
||||
|
||||
#### .htaccess example
|
||||
|
||||
Below is an example of an working `.htaccess` file used by simple-php-router.
|
||||
|
||||
Simply create a new `.htaccess` 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).
|
||||
|
||||
```
|
||||
RewriteEngine on
|
||||
RewriteCond %{SCRIPT_FILENAME} !-f
|
||||
RewriteCond %{SCRIPT_FILENAME} !-d
|
||||
RewriteCond %{SCRIPT_FILENAME} !-l
|
||||
RewriteRule ^(.*)$ index.php/$1
|
||||
```
|
||||
|
||||
### Setting up IIS
|
||||
|
||||
On IIS you have to add some lines your `web.config` file in the `public` folder or create a new one. If rewriting is not working for you, please check that your IIS version have included the `url rewrite` module or download and install them from Microsoft web site.
|
||||
|
||||
#### web.config example
|
||||
|
||||
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 version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<system.webServer>
|
||||
<rewrite>
|
||||
<rules>
|
||||
<!-- Remove slash '/' from the en of the url -->
|
||||
<rule name="RewriteRequestsToPublic">
|
||||
<match url="^(.*)$" />
|
||||
<conditions logicalGrouping="MatchAll" trackAllCaptures="false">
|
||||
</conditions>
|
||||
<action type="Rewrite" url="/{R:0}" />
|
||||
</rule>
|
||||
|
||||
<!-- When requested file or folder don't exists, will request again through index.php -->
|
||||
<rule name="Imported Rule 1" stopProcessing="true">
|
||||
<match url="^(.*)$" ignoreCase="true" />
|
||||
<conditions logicalGrouping="MatchAll">
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
|
||||
</conditions>
|
||||
<action type="Rewrite" url="/index.php/{R:1}" appendQueryString="true" />
|
||||
</rule>
|
||||
</rules>
|
||||
</rewrite>
|
||||
</system.webServer>
|
||||
</configuration>
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
Create a new file, name it `routes.php` and place it in your library folder. This will be the file where you define all the routes for your project.
|
||||
@@ -187,9 +244,9 @@ SimpleRouter::start();
|
||||
|
||||
### Helper functions
|
||||
|
||||
We recommend that you add these helper functions to your project. Theese will allow you to access functionality of the router more easily.
|
||||
We recommend that you add these helper functions to your project. These will allow you to access functionality of the router more easily.
|
||||
|
||||
To implement the functions below, simply copy the code to a new file and require the file before initializing the router.
|
||||
To implement the functions below, simply copy the code to a new file and require the file before initializing the router or copy the `helpers.php` we've included in this library.
|
||||
|
||||
```php
|
||||
<?php
|
||||
@@ -233,10 +290,18 @@ function request()
|
||||
|
||||
/**
|
||||
* Get input class
|
||||
* @return \Pecee\Http\Input\Input
|
||||
* @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
|
||||
*/
|
||||
function input()
|
||||
function input($index = null, $defaultValue = null, $methods = null)
|
||||
{
|
||||
if($index !== null)
|
||||
{
|
||||
return request()->getInput()->get($index, $defaultValue, $methods);
|
||||
}
|
||||
|
||||
return request()->getInput();
|
||||
}
|
||||
|
||||
@@ -365,7 +430,7 @@ The example below is using the following regular expression: `/ajax/([\w]+)/?([0
|
||||
|
||||
**Matches:** `/ajax/abc/`, `/ajax/abc/123/`
|
||||
|
||||
**Doesn't match:** `/ajax/`
|
||||
**Won't match:** `/ajax/`
|
||||
|
||||
Match groups specified in the regex will be passed on as parameters:
|
||||
|
||||
@@ -376,13 +441,42 @@ SimpleRouter::all('/ajax/abc/123', function($param1, $param2) {
|
||||
})->setMatch('/\/ajax\/([\w]+)\/?([0-9]+)?\/?/is');
|
||||
```
|
||||
|
||||
### Custom regex for matching parameters
|
||||
|
||||
By default simple-php-router uses the `\w` regular expression when matching parameters.
|
||||
This decision was made with speed and reliability in mind, as this match will match both letters, number and most of the used symbols on the internet.
|
||||
|
||||
However, sometimes it can be necessary to add a custom regular expression to match more advanced characters like `-` etc.
|
||||
|
||||
Instead of adding a custom regular expression to all your parameters, you can simply add a global regular expression which will be used on all the parameters on the route.
|
||||
|
||||
**Note:** If you the regular expression to be available across, we recommend using the global parameter on a group as demonstrated in the examples below.
|
||||
|
||||
#### Example
|
||||
|
||||
This example will ensure that all parameters use the `[\w\-]+` regular expression when parsing.
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home', ['defaultParameterRegex' => '[\w\-]+']);
|
||||
```
|
||||
|
||||
You can also apply this setting to a group if you need multiple routes to use your custom regular expression when parsing parameters.
|
||||
|
||||
```php
|
||||
SimpleRouter::group(['defaultParameterRegex' => '[\w\-]+'], function() {
|
||||
|
||||
SimpleRouter::get('/path/{parameter}', 'VideoController@home');
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## Named routes
|
||||
|
||||
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition:
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/user/profile', function () {
|
||||
//
|
||||
// Your code here
|
||||
})->name('profile');
|
||||
```
|
||||
|
||||
@@ -611,13 +705,30 @@ class CustomMiddleware implements Middleware {
|
||||
|
||||
---
|
||||
|
||||
# ExceptionHandler
|
||||
# ExceptionHandlers
|
||||
|
||||
ExceptionHandler are classes that handles all exceptions. ExceptionsHandlers must implement the `IExceptionHandler` interface.
|
||||
|
||||
## Example
|
||||
## Handling 404, 403 and other errors
|
||||
|
||||
Resource controllers can implement the `IRestController` interface, but is not required.
|
||||
If you simply want to catch a 404 (page not found) etc. you can use the `Router::error($callback)` static helper method.
|
||||
|
||||
This will add a callback method which is fired whenever an error occurs on all routes.
|
||||
|
||||
The basic example below simply redirect the page to `/not-found` if an `NotFoundHttpException` (404) occurred.
|
||||
The code should be placed in the file that contains your routes.
|
||||
|
||||
```php
|
||||
Router::get('/not-found', 'PageController@notFound');
|
||||
|
||||
Router::error(function(Request $request, \Exception $exception) {
|
||||
if($exception instanceof NotFoundHttpException && $exception->getCode() == 404) {
|
||||
response()->redirect('/not-found');
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Using custom exception handlers
|
||||
|
||||
This is a basic example of an ExceptionHandler implementation (please see "[Easily overwrite route about to be loaded](#easily-overwrite-route-about-to-be-loaded)" for examples on how to change callback).
|
||||
|
||||
@@ -635,7 +746,7 @@ class CustomExceptionHandler implements IExceptionHandler
|
||||
|
||||
/* You can use the exception handler to format errors depending on the request and type. */
|
||||
|
||||
if (stripos($request->getUri(), '/api') !== false) {
|
||||
if (stripos($request->getUri()->getPath(), '/api') !== false) {
|
||||
|
||||
response()->json([
|
||||
'error' => $error->getMessage(),
|
||||
@@ -762,7 +873,7 @@ If items is grouped in the html, it will return an array of items.
|
||||
**Note:** `get` will automatically trim the value and ensure that it's not empty. If it's empty the `$defaultValue` will be returned.
|
||||
|
||||
```php
|
||||
$value = input()->get($index, $defaultValue, $methods);
|
||||
$value = input($index, $defaultValue, $methods);
|
||||
```
|
||||
|
||||
### Get parameter object
|
||||
@@ -771,11 +882,11 @@ Will return an instance of `InputItem` or `InputFile` depending on the type.
|
||||
|
||||
You can use this in your html as it will render the value of the item.
|
||||
However if you want to compare value in your if statements, you have to use
|
||||
the `getValue` or use the `input()->get()` instead.
|
||||
the `getValue` or use the `input()` instead.
|
||||
|
||||
If items is grouped in the html, it will return an array of items.
|
||||
|
||||
**Note:** `getObject` will only return `$defaultValue` if the item doesn't exist. If you want `$defaultValue` to be returned if the item is empty, please use `input()->get()` instead.
|
||||
**Note:** `getObject` will only return `$defaultValue` if the item doesn't exist. If you want `$defaultValue` to be returned if the item is empty, please use `input()` instead.
|
||||
|
||||
```php
|
||||
$object = input()->getObject($index, $defaultValue = null, $methods = null);
|
||||
@@ -792,13 +903,17 @@ $object = input()->getObject($index, $defaultValue = null, $methods = null);
|
||||
* $defaultValue is returned if the value is empty.
|
||||
*/
|
||||
|
||||
$id = input()->get($index, $defaultValue);
|
||||
$id = input()->get($index, $defaultValue, $method);
|
||||
|
||||
# -- shortcut to above --
|
||||
|
||||
$id = input($index, $defaultValue, $method);
|
||||
|
||||
# -- match specific --
|
||||
|
||||
$object = input()->get($index, $defaultValue, 'get');
|
||||
$object = input()->get($index, $defaultValue, 'post');
|
||||
$object = input()->get($index, $defaultValue, 'file');
|
||||
$object = input($index, $defaultValue, 'get');
|
||||
$object = input($index, $defaultValue, 'post');
|
||||
$object = input($index, $defaultValue, 'file');
|
||||
|
||||
# -- or --
|
||||
|
||||
@@ -817,7 +932,7 @@ $object = input()->findFile($index, $defaultValue);
|
||||
*/
|
||||
|
||||
/* @var $image \Pecee\Http\Input\InputFile */
|
||||
foreach(input()->get('images', []) as $image)
|
||||
foreach(input('images', []) as $image)
|
||||
{
|
||||
if($image->getMime() === 'image/jpeg') {
|
||||
|
||||
@@ -863,7 +978,7 @@ Below example requires you to have the helper functions added. Please refer to t
|
||||
|
||||
```php
|
||||
/* Get parameter site_id or default-value 2 from either post-value or query-string */
|
||||
$siteId = input()->get('site_id', 2, ['post', 'get']);
|
||||
$siteId = input('site_id', 2, ['post', 'get']);
|
||||
```
|
||||
|
||||
---
|
||||
@@ -888,11 +1003,9 @@ $request->setRewriteCallback('Example\MyCustomClass@hello');
|
||||
$request->setRewriteUrl('/my-rewrite-url');
|
||||
```
|
||||
|
||||
### Examples
|
||||
**Note:** It's only possible to change the route BEFORE the route has initially been rendered. You can use the `Request` object to manipulate the route which are about to be loaded.
|
||||
|
||||
It's only possible to change the route BEFORE the route has initially been rendered. You can use the `Request` object to manipulate the route which are about to be loaded.
|
||||
|
||||
#### Rewrite using callback
|
||||
### Rewrite using callback
|
||||
|
||||
This method is most efficient, as it will render the route immediately.
|
||||
|
||||
@@ -908,7 +1021,7 @@ The example below will render `DefaultController@notFound` regardless of the url
|
||||
|
||||
**NOTE: Use this method if you want to load another controller. No additional middlewares or rules will be loaded.**
|
||||
|
||||
#### Middleware example
|
||||
##### Middleware example
|
||||
|
||||
```php
|
||||
namespace Demo\Middlewares;
|
||||
@@ -928,7 +1041,7 @@ class CustomMiddleware implements IMiddleware {
|
||||
}
|
||||
```
|
||||
|
||||
#### Exception handler example
|
||||
##### Exception handler example
|
||||
|
||||
```php
|
||||
namespace Demo\Handlers;
|
||||
@@ -963,7 +1076,7 @@ class CustomExceptionHandler implements IExceptionHandler
|
||||
}
|
||||
```
|
||||
|
||||
#### Rewrite using url
|
||||
### Rewrite using url
|
||||
|
||||
The example below will cause the router to reload the request and reinitialize all the routes. This method is slower, but will ensure that all middlewares and rules for the route is loaded.
|
||||
|
||||
@@ -974,7 +1087,7 @@ We are using the `url()` helper function to get the uri to another route added i
|
||||
|
||||
**NOTE: Use this method if you want to fully load another route using it's settings (request method, middlewares etc).**
|
||||
|
||||
#### Middleware example
|
||||
##### Middleware example
|
||||
|
||||
The example below will redirect the request to the `home`-route.
|
||||
|
||||
@@ -995,7 +1108,7 @@ class CustomMiddleware implements IMiddleware {
|
||||
}
|
||||
```
|
||||
|
||||
# Bootmanager: loading routes dynamically
|
||||
### Bootmanager: loading routes dynamically
|
||||
|
||||
Sometimes it can be necessary to keep urls stored in the database, file or similar. In this example, we want the url ```/my-cat-is-beatiful``` to load the route ```/article/view/1``` which the router knows, because it's defined in the ```routes.php``` file.
|
||||
|
||||
@@ -1018,7 +1131,7 @@ class CustomRouterRules implement IRouterBootManager {
|
||||
|
||||
// If the current uri matches the url, we use our custom route
|
||||
|
||||
if($request->getUri() === $url) {
|
||||
if($request->getUri()->getPath() === $url) {
|
||||
$request->setRewriteUrl($rule);
|
||||
return $request;
|
||||
}
|
||||
@@ -1041,7 +1154,7 @@ The last thing we need to do, is to add our custom boot-manager to the ```routes
|
||||
SimpleRouter::addBootManager(new CustomRouterRules());
|
||||
```
|
||||
|
||||
## Adding routes manually
|
||||
### Adding routes manually
|
||||
|
||||
The ```SimpleRouter``` class referenced in the previous example, is just a simple helper class that knows how to communicate with the ```Router``` class.
|
||||
If you are up for a challenge, want the full control or simply just want to create your own ```Router``` helper class, this example is for you.
|
||||
@@ -1059,7 +1172,7 @@ $route = new RouteUrl('/answer/1', function() {
|
||||
|
||||
});
|
||||
|
||||
$route->setMiddleware(\Demo\Middlewares\AuthMiddleware::class);
|
||||
$route->addMiddleware(\Demo\Middlewares\AuthMiddleware::class);
|
||||
$route->setNamespace('\Demo\Controllers');
|
||||
$route->setPrefix('v1');
|
||||
|
||||
@@ -1067,6 +1180,10 @@ $route->setPrefix('v1');
|
||||
$router->addRoute($route);
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
This section contains advanced tips & tricks on extending the usage for parameters.
|
||||
|
||||
## Extending
|
||||
|
||||
This is a simple example of an integration into a framework.
|
||||
|
||||
+4
-1
@@ -2,11 +2,14 @@
|
||||
"name": "pecee/simple-router",
|
||||
"description": "Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.",
|
||||
"keywords": [
|
||||
"router",
|
||||
"router",
|
||||
"routing",
|
||||
"route",
|
||||
"simple-php-router",
|
||||
"laravel",
|
||||
"pecee",
|
||||
"route"
|
||||
"php"
|
||||
],
|
||||
"license": "MIT",
|
||||
"support": {
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as Router;
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
* The name parameter supports the following values:
|
||||
* - Route name
|
||||
* - Controller/resource name (with or without method)
|
||||
* - Controller class name
|
||||
*
|
||||
* When searching for controller/resource by name, you can use this syntax "route.name@method".
|
||||
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
|
||||
* If no arguments is specified, it will return the url for the current loaded route.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @param string|array|null $parameters
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
function url($name = null, $parameters = null, $getParams = null)
|
||||
{
|
||||
return Router::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Pecee\Http\Response
|
||||
*/
|
||||
function response()
|
||||
{
|
||||
return Router::response();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Pecee\Http\Request
|
||||
*/
|
||||
function request()
|
||||
{
|
||||
return Router::request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get input class
|
||||
* @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
|
||||
*/
|
||||
function input($index = null, $defaultValue = null, $methods = null)
|
||||
{
|
||||
if ($index !== null) {
|
||||
return request()->getInput()->get($index, $defaultValue, $methods);
|
||||
}
|
||||
|
||||
return request()->getInput();
|
||||
}
|
||||
|
||||
function redirect($url, $code = null)
|
||||
{
|
||||
if ($code !== null) {
|
||||
response()->httpCode($code);
|
||||
}
|
||||
|
||||
response()->redirect($url);
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
namespace Pecee\Controllers;
|
||||
|
||||
interface IRestController
|
||||
interface IResourceController
|
||||
{
|
||||
|
||||
/**
|
||||
+11
-3
@@ -3,13 +3,14 @@ namespace Pecee;
|
||||
|
||||
class CsrfToken
|
||||
{
|
||||
const CSRF_KEY = 'XSRF-TOKEN';
|
||||
const CSRF_KEY = 'CSRF-TOKEN';
|
||||
|
||||
protected $token;
|
||||
|
||||
/**
|
||||
* Generate random identifier for CSRF token
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return string
|
||||
*/
|
||||
public static function generateToken()
|
||||
@@ -18,7 +19,14 @@ class CsrfToken
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
return bin2hex(openssl_random_pseudo_bytes(32));
|
||||
$isSourceStrong = false;
|
||||
|
||||
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
|
||||
if ($isSourceStrong === false || $random === false) {
|
||||
throw new \RuntimeException('IV generation failed');
|
||||
}
|
||||
|
||||
return $random;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,7 +60,7 @@ class CsrfToken
|
||||
*/
|
||||
public function getToken()
|
||||
{
|
||||
if ($this->hasToken()) {
|
||||
if ($this->hasToken() === true) {
|
||||
return $_COOKIE[static::CSRF_KEY];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Handlers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
/**
|
||||
* Class CallbackExceptionHandler
|
||||
*
|
||||
* Class is used to create callbacks which are fired when an exception is reached.
|
||||
* This allows for easy handling 404-exception etc. without creating an custom ExceptionHandler.
|
||||
*
|
||||
* @package Pecee\Handlers
|
||||
*/
|
||||
class CallbackExceptionHandler implements IExceptionHandler
|
||||
{
|
||||
|
||||
protected $callback;
|
||||
|
||||
public function __construct(\Closure $callback)
|
||||
{
|
||||
$this->callback = $callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param \Exception $error
|
||||
* @return Request|null
|
||||
*/
|
||||
public function handleError(Request $request, \Exception $error)
|
||||
{
|
||||
/* Fire exceptions */
|
||||
return call_user_func($this->callback,
|
||||
$request,
|
||||
$error
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ class Input
|
||||
{
|
||||
$list = [];
|
||||
|
||||
foreach ($_FILES as $key => $value) {
|
||||
foreach ((array)$_FILES as $key => $value) {
|
||||
|
||||
// Handle array input
|
||||
if (is_array($value['name']) === false) {
|
||||
@@ -108,11 +108,11 @@ class Input
|
||||
|
||||
$file = InputFile::createFromArray([
|
||||
'index' => $key,
|
||||
'filename' => $getItem($key),
|
||||
'error' => $getItem($key, 'error'),
|
||||
'tmp_name' => $getItem($key, 'tmp_name'),
|
||||
'type' => $getItem($key, 'type'),
|
||||
'size' => $getItem($key, 'size'),
|
||||
'filename' => $getItem($key, 'name'),
|
||||
]);
|
||||
|
||||
if (isset($output[$key])) {
|
||||
@@ -283,15 +283,7 @@ class Input
|
||||
}
|
||||
}
|
||||
|
||||
$output = array_merge($_GET, $output);
|
||||
|
||||
if ($filter !== null) {
|
||||
$output = array_filter($output, function ($key) use ($filter) {
|
||||
return (in_array($key, $filter) === true);
|
||||
}, ARRAY_FILTER_USE_KEY);
|
||||
}
|
||||
|
||||
return $output;
|
||||
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : array_merge($_GET, $output);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -41,9 +41,9 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
$url = rtrim($url, '/');
|
||||
if ($url[strlen($url) - 1] === '*') {
|
||||
$url = rtrim($url, '*');
|
||||
$skip = (stripos($request->getUri(), $url) === 0);
|
||||
$skip = (stripos($request->getUri()->getPath(), $url) === 0);
|
||||
} else {
|
||||
$skip = ($url === rtrim($request->getUri(), '/'));
|
||||
$skip = ($url === $request->getUri()->getPath());
|
||||
}
|
||||
|
||||
if ($skip === true) {
|
||||
|
||||
@@ -8,7 +8,7 @@ use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
class Request
|
||||
{
|
||||
protected $data = [];
|
||||
private $data = [];
|
||||
protected $headers;
|
||||
protected $host;
|
||||
protected $uri;
|
||||
@@ -29,8 +29,11 @@ class Request
|
||||
public function __construct()
|
||||
{
|
||||
$this->parseHeaders();
|
||||
$this->host = $this->getHeader('http-host');
|
||||
$this->uri = $this->getHeader('request-uri');
|
||||
$this->setHost($this->getHeader('http-host'));
|
||||
|
||||
// Check if special IIS header exist, otherwise use default.
|
||||
$this->setUri(new Uri($this->getHeader('unencoded-url', $this->getHeader('request-uri'))));
|
||||
|
||||
$this->input = new Input($this);
|
||||
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'), 'post'));
|
||||
}
|
||||
@@ -58,7 +61,7 @@ class Request
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @return Uri
|
||||
*/
|
||||
public function getUri()
|
||||
{
|
||||
@@ -164,7 +167,7 @@ class Request
|
||||
*/
|
||||
public function getHeader($name, $defaultValue = null)
|
||||
{
|
||||
if (isset($this->headers[strtolower($name)])) {
|
||||
if (array_key_exists(strtolower($name), $this->headers) === true) {
|
||||
return $this->headers[strtolower($name)];
|
||||
}
|
||||
|
||||
@@ -215,9 +218,9 @@ class Request
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $uri
|
||||
* @param Uri $uri
|
||||
*/
|
||||
public function setUri($uri)
|
||||
public function setUri(Uri $uri)
|
||||
{
|
||||
$this->uri = $uri;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Response
|
||||
@@ -41,7 +42,7 @@ class Response
|
||||
|
||||
public function refresh()
|
||||
{
|
||||
$this->redirect($this->request->getUri());
|
||||
$this->redirect($this->request->getUri()->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,14 +83,19 @@ class Response
|
||||
}
|
||||
|
||||
/**
|
||||
* Json encode array
|
||||
* @param array $value
|
||||
* Json encode
|
||||
* @param array|\JsonSerializable $value
|
||||
* @throws \InvalidArgumentException;
|
||||
*/
|
||||
public function json(array $value)
|
||||
public function json($value)
|
||||
{
|
||||
$this->header('Content-Type: application/json');
|
||||
if (($value instanceof \JsonSerializable) === false && is_array($value) === false) {
|
||||
throw new \InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
|
||||
}
|
||||
|
||||
$this->header('Content-type: application/json');
|
||||
echo json_encode($value);
|
||||
die();
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Uri
|
||||
{
|
||||
private $originalUrl;
|
||||
private $data = [
|
||||
'scheme',
|
||||
'host',
|
||||
'port',
|
||||
'user',
|
||||
'pass',
|
||||
'path',
|
||||
'query',
|
||||
'fragment',
|
||||
];
|
||||
|
||||
public function __construct($url)
|
||||
{
|
||||
$this->originalUrl = $url;
|
||||
$this->data = array_merge($this->data, $this->parseUrl(urldecode($url)));
|
||||
|
||||
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()
|
||||
{
|
||||
return (strtolower($this->getScheme()) === 'https');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if url is relative
|
||||
* @return bool
|
||||
*/
|
||||
public function isRelative()
|
||||
{
|
||||
return ($this->getHost() === null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url scheme
|
||||
* @return string|null
|
||||
*/
|
||||
public function getScheme()
|
||||
{
|
||||
return $this->data['scheme'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url host
|
||||
* @return string|null
|
||||
*/
|
||||
public function getHost()
|
||||
{
|
||||
return $this->data['host'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url port
|
||||
* @return int|null
|
||||
*/
|
||||
public function getPort()
|
||||
{
|
||||
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse username from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUserName()
|
||||
{
|
||||
return $this->data['user'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse password from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getPassword()
|
||||
{
|
||||
return $this->data['pass'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get path from url
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
return $this->data['path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get querystring from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getQueryString()
|
||||
{
|
||||
return $this->data['query'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fragment from url (everything after #)
|
||||
* @return string|null
|
||||
*/
|
||||
public function getFragment()
|
||||
{
|
||||
return $this->data['fragment'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getOriginalUrl()
|
||||
{
|
||||
return $this->originalUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-8 aware parse_url() replacement.
|
||||
* @param string $url
|
||||
* @param int $component
|
||||
* @throws \InvalidArgumentException
|
||||
* @return array
|
||||
*/
|
||||
public function parseUrl($url, $component = -1)
|
||||
{
|
||||
$encodedUrl = preg_replace_callback(
|
||||
'%[^:/@?&=#]+%u',
|
||||
function ($matches) {
|
||||
return urlencode($matches[0]);
|
||||
},
|
||||
$url
|
||||
);
|
||||
|
||||
$parts = parse_url($encodedUrl, $component);
|
||||
|
||||
if ($parts === false) {
|
||||
throw new \InvalidArgumentException('Malformed URL: ' . $url);
|
||||
}
|
||||
|
||||
foreach ((array)$parts as $name => $value) {
|
||||
$parts[$name] = urldecode($value);
|
||||
}
|
||||
|
||||
return $parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns data array with information about the url
|
||||
* @return array
|
||||
*/
|
||||
public function getData()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return $this->getOriginalUrl();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
interface IGroupRoute extends IRoute
|
||||
@@ -13,6 +15,14 @@ interface IGroupRoute extends IRoute
|
||||
*/
|
||||
public function matchDomain(Request $request);
|
||||
|
||||
/**
|
||||
* Add exception handler
|
||||
*
|
||||
* @param IExceptionHandler|string $handler
|
||||
* @return static $this;
|
||||
*/
|
||||
public function addExceptionHandler($handler);
|
||||
|
||||
/**
|
||||
* Set exception-handlers for group
|
||||
*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -173,7 +174,7 @@ interface IRoute
|
||||
* @param string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function setMiddleware($middleware);
|
||||
public function addMiddleware($middleware);
|
||||
|
||||
/**
|
||||
* Set middlewares array
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
@@ -35,10 +36,12 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
$middleware = $this->getMiddlewares()[$i];
|
||||
|
||||
$middleware = $this->loadClass($middleware);
|
||||
if (is_object($middleware) === false) {
|
||||
$middleware = $this->loadClass($middleware);
|
||||
}
|
||||
|
||||
if (($middleware instanceof IMiddleware) === false) {
|
||||
throw new HttpException($middleware . ' must be instance of Middleware');
|
||||
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
|
||||
}
|
||||
|
||||
$middleware->handle($request);
|
||||
@@ -54,17 +57,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
return null;
|
||||
}
|
||||
|
||||
$parameters = [];
|
||||
|
||||
if (preg_match($this->regex, $request->getHost() . $url, $parameters) > 0) {
|
||||
|
||||
/* Remove global match */
|
||||
$this->parameters = array_slice($parameters, 1);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return (preg_match($this->regex, $request->getHost() . $url) > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,9 +72,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
if (strpos($this->url, $this->paramModifiers[0]) !== false) {
|
||||
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
if (preg_match_all('/' . $regex . '/', $this->url, $matches)) {
|
||||
if (preg_match_all('/' . $regex . '/u', $this->url, $matches)) {
|
||||
$this->parameters = array_fill_keys($matches[1], null);
|
||||
}
|
||||
}
|
||||
@@ -99,7 +92,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
* Used when calling the url() helper.
|
||||
*
|
||||
* @param string|null $method
|
||||
* @param array|null $parameters
|
||||
* @param string|array|null $parameters
|
||||
* @param string|null $name
|
||||
* @return string
|
||||
*/
|
||||
@@ -107,8 +100,10 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
{
|
||||
$url = $this->getUrl();
|
||||
|
||||
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
|
||||
$url = '//' . $this->getGroup()->getDomains()[0] . $url;
|
||||
$group = $this->getGroup();
|
||||
|
||||
if ($group !== null && count($group->getDomains()) > 0) {
|
||||
$url = '//' . $group->getDomains()[0] . $url;
|
||||
}
|
||||
|
||||
/* Contains parameters that aren't recognized and will be appended at the end of the url */
|
||||
@@ -128,11 +123,17 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$param = $keys[$i];
|
||||
$value = $value = ($parameters !== null && array_key_exists($param, $parameters)) ? $parameters[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
if ($parameters === '' || (is_array($parameters) && count($parameters) === 0)) {
|
||||
$value = '';
|
||||
} else {
|
||||
$p = (array)$parameters;
|
||||
$value = array_key_exists($param, $p) ? $p[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
}
|
||||
}
|
||||
|
||||
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
|
||||
@@ -143,6 +144,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
}
|
||||
}
|
||||
|
||||
$url = '/' . ltrim($url, '/');
|
||||
$url .= join('/', $unknownParams);
|
||||
|
||||
return rtrim($url, '/') . '/';
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
abstract class Route implements IRoute
|
||||
{
|
||||
const PARAMETERS_REGEX_MATCH = '%s([\w]+)(\%s?)%s';
|
||||
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
|
||||
const PARAMETERS_DEFAULT_REGEX = '[\w]+';
|
||||
|
||||
const REQUEST_TYPE_GET = 'get';
|
||||
const REQUEST_TYPE_POST = 'post';
|
||||
@@ -31,6 +34,12 @@ abstract class Route implements IRoute
|
||||
* @var bool
|
||||
*/
|
||||
protected $filterEmptyParams = false;
|
||||
|
||||
/**
|
||||
* Default regular expression used for parsing parameters.
|
||||
* @var string|null
|
||||
*/
|
||||
protected $defaultParameterRegex;
|
||||
protected $paramModifiers = '{}';
|
||||
protected $paramOptionalSymbol = '?';
|
||||
protected $group;
|
||||
@@ -49,7 +58,7 @@ abstract class Route implements IRoute
|
||||
protected function loadClass($name)
|
||||
{
|
||||
if (class_exists($name) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Class %s does not exist', $name), 404);
|
||||
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404);
|
||||
}
|
||||
|
||||
return new $name();
|
||||
@@ -59,48 +68,55 @@ abstract class Route implements IRoute
|
||||
{
|
||||
$callback = $this->getCallback();
|
||||
|
||||
if ($callback !== null && is_callable($callback)) {
|
||||
if ($callback === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* Render callback function */
|
||||
if (is_callable($callback) === true) {
|
||||
|
||||
/* When the callback is a function */
|
||||
call_user_func_array($callback, $this->getParameters());
|
||||
return call_user_func_array($callback, $this->getParameters());
|
||||
|
||||
} else {
|
||||
|
||||
/* When the callback is a method */
|
||||
$controller = explode('@', $callback);
|
||||
|
||||
$namespace = $this->getNamespace();
|
||||
|
||||
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $controller[1];
|
||||
|
||||
if (method_exists($class, $method) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
$parameters = $this->getParameters();
|
||||
|
||||
/* Filter parameters with null-value */
|
||||
|
||||
if ($this->filterEmptyParams === true) {
|
||||
$parameters = array_filter($parameters, function ($var) {
|
||||
return ($var !== null);
|
||||
});
|
||||
}
|
||||
|
||||
call_user_func_array([$class, $method], $parameters);
|
||||
}
|
||||
|
||||
/* When the callback is a class + method */
|
||||
$controller = explode('@', $callback);
|
||||
|
||||
$namespace = $this->getNamespace();
|
||||
|
||||
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $controller[1];
|
||||
|
||||
if (method_exists($class, $method) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
|
||||
}
|
||||
|
||||
$parameters = $this->getParameters();
|
||||
|
||||
/* Filter parameters with null-value */
|
||||
|
||||
if ($this->filterEmptyParams === true) {
|
||||
$parameters = array_filter($parameters, function ($var) {
|
||||
return ($var !== null);
|
||||
});
|
||||
}
|
||||
|
||||
return call_user_func_array([$class, $method], $parameters);
|
||||
}
|
||||
|
||||
protected function parseParameters($route, $url, $parameterRegex = '[\w]+')
|
||||
protected function parseParameters($route, $url, $parameterRegex = null)
|
||||
{
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
$parameters = [];
|
||||
|
||||
if (preg_match_all('/' . $regex . '/', $route, $parameters)) {
|
||||
// Ensures that hostnames/domains will work with parameters
|
||||
$url = '/' . ltrim($url, '/');
|
||||
|
||||
if (preg_match_all('/' . $regex . '/u', $route, $parameters)) {
|
||||
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', rtrim($route, '/'));
|
||||
|
||||
@@ -111,8 +127,21 @@ abstract class Route implements IRoute
|
||||
if ($key < count($parameters[1])) {
|
||||
|
||||
$name = $parameters[1][$key];
|
||||
$regex = isset($this->where[$name]) ? $this->where[$name] : $parameterRegex;
|
||||
$regex = sprintf('\-?\/?(?P<%s>%s)', $name, $regex) . $parameters[2][$key];
|
||||
|
||||
/* If custom regex is defined, use that */
|
||||
if (isset($this->where[$name]) === true) {
|
||||
$regex = $this->where[$name];
|
||||
} else {
|
||||
|
||||
/* If method specific regex is defined use that, otherwise use the default parameter regex */
|
||||
if ($parameterRegex !== null) {
|
||||
$regex = $parameterRegex;
|
||||
} else {
|
||||
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex;
|
||||
}
|
||||
}
|
||||
|
||||
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
|
||||
|
||||
}
|
||||
|
||||
@@ -125,11 +154,11 @@ abstract class Route implements IRoute
|
||||
$urlRegex = preg_quote($route, '/');
|
||||
}
|
||||
|
||||
if (preg_match('/^' . $urlRegex . '(\/?)$/', $url, $matches) > 0) {
|
||||
if (preg_match('/^' . $urlRegex . '\/?$/u', $url, $matches) > 0) {
|
||||
|
||||
$values = [];
|
||||
|
||||
if (isset($parameters[1])) {
|
||||
if (isset($parameters[1]) === true) {
|
||||
|
||||
/* Only take matched parameters with name */
|
||||
foreach ($parameters[1] as $name) {
|
||||
@@ -152,7 +181,7 @@ abstract class Route implements IRoute
|
||||
*/
|
||||
public function getIdentifier()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
return $this->callback;
|
||||
}
|
||||
|
||||
@@ -249,7 +278,7 @@ abstract class Route implements IRoute
|
||||
|
||||
public function getMethod()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[1];
|
||||
@@ -260,7 +289,7 @@ abstract class Route implements IRoute
|
||||
|
||||
public function getClass()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[0];
|
||||
@@ -343,6 +372,10 @@ abstract class Route implements IRoute
|
||||
$values['middleware'] = $this->middlewares;
|
||||
}
|
||||
|
||||
if ($this->defaultParameterRegex !== null) {
|
||||
$values['defaultParameterRegex'] = $this->defaultParameterRegex;
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
@@ -376,6 +409,10 @@ abstract class Route implements IRoute
|
||||
$this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares));
|
||||
}
|
||||
|
||||
if (isset($values['defaultParameterRegex'])) {
|
||||
$this->setDefaultParameterRegex($values['defaultParameterRegex']);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -454,9 +491,10 @@ abstract class Route implements IRoute
|
||||
}
|
||||
|
||||
/**
|
||||
* Set middleware class-name
|
||||
* Add middleware class-name
|
||||
*
|
||||
* @param string $middleware
|
||||
* @deprecated This method is deprecated and will be removed in the near future.
|
||||
* @param IMiddleware|string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function setMiddleware($middleware)
|
||||
@@ -466,6 +504,19 @@ abstract class Route implements IRoute
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add middleware class-name
|
||||
*
|
||||
* @param IMiddleware|string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function addMiddleware($middleware)
|
||||
{
|
||||
$this->middlewares[] = $middleware;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set middlewares array
|
||||
*
|
||||
@@ -487,4 +538,28 @@ abstract class Route implements IRoute
|
||||
return $this->middlewares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default regular expression used when matching parameters.
|
||||
* This is used when no custom parameter regex is found.
|
||||
*
|
||||
* @param string $regex
|
||||
* @return static $this
|
||||
*/
|
||||
public function setDefaultParameterRegex($regex)
|
||||
{
|
||||
$this->defaultParameterRegex = $regex;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default regular expression used when matching parameters.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getDefaultParameterRegex()
|
||||
{
|
||||
return $this->defaultParameterRegex;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -53,7 +53,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
if (strpos($name, '.') !== false) {
|
||||
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
|
||||
if ($found !== false) {
|
||||
$method = $found;
|
||||
$method = (string)$found;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
foreach (static::$requestTypes as $requestType) {
|
||||
|
||||
if (stripos($method, $requestType) === 0) {
|
||||
$method = substr($method, strlen($requestType));
|
||||
$method = (string)substr($method, strlen($requestType));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -74,8 +74,10 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
$method .= '/';
|
||||
}
|
||||
|
||||
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
|
||||
$url .= '//' . $this->getGroup()->getDomains()[0];
|
||||
$group = $this->getGroup();
|
||||
|
||||
if ($group !== null && count($group->getDomains()) > 0) {
|
||||
$url .= '//' . $group->getDomains()[0];
|
||||
}
|
||||
|
||||
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters);
|
||||
@@ -85,13 +87,10 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false || stripos($url, $this->url) !== 0 || strtolower($url) !== strtolower($this->url)) {
|
||||
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouteGroup extends Route implements IGroupRoute
|
||||
@@ -18,7 +20,7 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
*/
|
||||
public function matchDomain(Request $request)
|
||||
{
|
||||
if (count($this->domains) === 0) {
|
||||
if ($this->domains === null || count($this->domains) === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -54,6 +56,19 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
return $this->matchDomain($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add exception handler
|
||||
*
|
||||
* @param IExceptionHandler|string $handler
|
||||
* @return static $this
|
||||
*/
|
||||
public function addExceptionHandler($handler)
|
||||
{
|
||||
$this->exceptionHandlers[] = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set exception-handlers for group
|
||||
*
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -53,7 +54,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
/* Remove method/type */
|
||||
if (strpos($name, '.') !== false) {
|
||||
$name = substr($name, 0, strrpos($name, '.'));
|
||||
$name = (string)substr($name, 0, strrpos($name, '.'));
|
||||
}
|
||||
|
||||
return (strtolower($this->name) === strtolower($name));
|
||||
@@ -78,47 +79,48 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false || stripos($url, $this->url) !== 0 || strtolower($url) !== strtolower($this->url)) {
|
||||
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
|
||||
|
||||
$parameters = $this->parseParameters($route, $url);
|
||||
if ($parameters === null) {
|
||||
/* Parse parameters from current route */
|
||||
$this->parameters = $this->parseParameters($route, $url);
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($regexMatch === null && $this->parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->parameters = (array)$parameters;
|
||||
$action = strtolower(trim($this->parameters['action']));
|
||||
$id = $this->parameters['id'];
|
||||
|
||||
$action = isset($this->parameters['action']) ? $this->parameters['action'] : null;
|
||||
// Remove action parameter
|
||||
unset($this->parameters['action']);
|
||||
|
||||
$method = $request->getMethod();
|
||||
|
||||
// Delete
|
||||
if ($method === static::REQUEST_TYPE_DELETE && isset($this->parameters['id'])) {
|
||||
if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
|
||||
return $this->call($this->methodNames['destroy']);
|
||||
}
|
||||
|
||||
// Update
|
||||
if (isset($this->parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false)) {
|
||||
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
|
||||
return $this->call($this->methodNames['update']);
|
||||
}
|
||||
|
||||
// Edit
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id']) && strtolower($action) === 'edit') {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
|
||||
return $this->call($this->methodNames['edit']);
|
||||
}
|
||||
|
||||
// Create
|
||||
if ($method === static::REQUEST_TYPE_GET && strtolower($action) === 'create') {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
|
||||
return $this->call($this->methodNames['create']);
|
||||
}
|
||||
|
||||
@@ -128,7 +130,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
}
|
||||
|
||||
// Show
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id'])) {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null) {
|
||||
return $this->call($this->methodNames['show']);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -13,22 +14,23 @@ class RouteUrl extends LoadableRoute
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Make regular expression based on route */
|
||||
/* Parse parameters from current route */
|
||||
$parameters = $this->parseParameters($this->url, $url);
|
||||
if ($parameters === null) {
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($regexMatch === null && $parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->setParameters($parameters);
|
||||
/* Set the parameters */
|
||||
$this->setParameters((array)$parameters);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
@@ -121,7 +122,7 @@ class Router
|
||||
|
||||
$exceptionHandlers = [];
|
||||
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
/* @var $route IRoute */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
@@ -133,20 +134,18 @@ class Router
|
||||
|
||||
$group = $route;
|
||||
|
||||
if ($route->getCallback() !== null && is_callable($route->getCallback())) {
|
||||
$this->processingRoute = true;
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
|
||||
$this->processingRoute = true;
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
|
||||
/* Add exception handlers */
|
||||
if (count($route->getExceptionHandlers()) > 0) {
|
||||
$exceptionHandlers += $route->getExceptionHandlers();
|
||||
}
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
|
||||
/* Add exception handlers */
|
||||
if (count($route->getExceptionHandlers()) > 0) {
|
||||
/** @noinspection AdditionOperationOnArraysInspection */
|
||||
$exceptionHandlers += $route->getExceptionHandlers();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +182,7 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
$this->exceptionHandlers = array_unique(array_merge($exceptionHandlers, $this->exceptionHandlers));
|
||||
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -225,7 +224,7 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
$max = count($this->processedRoutes) - 1;
|
||||
|
||||
@@ -249,9 +248,8 @@ class Router
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
/* If the request has changed */
|
||||
@@ -268,7 +266,8 @@ class Router
|
||||
/* Render route */
|
||||
$routeNotAllowed = false;
|
||||
$this->request->setLoadedRoute($route);
|
||||
$route->renderRoute($this->request);
|
||||
|
||||
return $route->renderRoute($this->request);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -283,13 +282,27 @@ class Router
|
||||
}
|
||||
|
||||
if ($this->request->getLoadedRoute() === null) {
|
||||
$this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404));
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
if ($rewriteUrl !== null) {
|
||||
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUri()->getPath());
|
||||
} else {
|
||||
$message = sprintf('Route not found: "%s"', $this->request->getUri()->getPath());
|
||||
}
|
||||
|
||||
$this->handleException(new NotFoundHttpException($message, 404));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Exception $e
|
||||
* @throws HttpException
|
||||
* @throws \Exception
|
||||
*/
|
||||
protected function handleException(\Exception $e)
|
||||
{
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
$max = count($this->exceptionHandlers);
|
||||
|
||||
@@ -297,7 +310,10 @@ class Router
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
|
||||
$handler = $this->exceptionHandlers[$i];
|
||||
$handler = new $handler();
|
||||
|
||||
if (is_object($handler) === false) {
|
||||
$handler = new $handler();
|
||||
}
|
||||
|
||||
if (($handler instanceof IExceptionHandler) === false) {
|
||||
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
|
||||
@@ -309,9 +325,8 @@ class Router
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
@@ -372,7 +387,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (strpos($name, '@') !== false) {
|
||||
if (is_string($name) === true && strpos($name, '@') !== false) {
|
||||
list($controller, $method) = array_map('strtolower', explode('@', $name));
|
||||
|
||||
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
|
||||
@@ -381,7 +396,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Check if callback matches (if it's not a function) */
|
||||
if (strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) {
|
||||
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)) {
|
||||
@@ -422,6 +437,10 @@ class Router
|
||||
throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null');
|
||||
}
|
||||
|
||||
if ($name === '' && $parameters === '') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
/* Only merge $_GET when all parameters are null */
|
||||
if ($name === null && $parameters === null && $getParams === null) {
|
||||
$getParams = $_GET;
|
||||
@@ -431,9 +450,7 @@ class Router
|
||||
|
||||
/* Return current route if no options has been specified */
|
||||
if ($name === null && $parameters === null) {
|
||||
$url = rtrim(parse_url($this->request->getUri(), PHP_URL_PATH), '/');
|
||||
|
||||
return (($url === '') ? '/' : $url . '/') . $this->arrayToParams($getParams);
|
||||
return $this->request->getUri()->getPath() . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
$loadedRoute = $this->request->getLoadedRoute();
|
||||
@@ -451,7 +468,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (strpos($name, '@') !== false) {
|
||||
if (is_string($name) === true && strpos($name, '@') !== false) {
|
||||
list($controller, $method) = explode('@', $name);
|
||||
|
||||
/* Loop through all the routes to see if we can find a match */
|
||||
@@ -517,6 +534,19 @@ class Router
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set routes
|
||||
*
|
||||
* @param array $routes
|
||||
* @return static $this
|
||||
*/
|
||||
public function setRoutes(array $routes)
|
||||
{
|
||||
$this->routes = $routes;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current request
|
||||
*
|
||||
|
||||
@@ -7,8 +7,10 @@
|
||||
* This class is added so calls can be made statically like Router::get() making the code look pretty.
|
||||
* It also adds some extra functionality like default-namespace.
|
||||
*/
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Handlers\CallbackExceptionHandler;
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
use Pecee\Http\Response;
|
||||
use Pecee\SimpleRouter\Exceptions\HttpException;
|
||||
@@ -33,6 +35,10 @@ class SimpleRouter
|
||||
*/
|
||||
protected static $response;
|
||||
|
||||
/**
|
||||
* Router instance
|
||||
* @var Router
|
||||
*/
|
||||
protected static $router;
|
||||
|
||||
/**
|
||||
@@ -43,7 +49,7 @@ class SimpleRouter
|
||||
*/
|
||||
public static function start()
|
||||
{
|
||||
static::router()->routeRequest();
|
||||
echo static::router()->routeRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,7 +220,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl
|
||||
* @return RouteUrl|IRoute
|
||||
*/
|
||||
public static function match(array $requestMethods, $url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -237,7 +243,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl
|
||||
* @return RouteUrl|IRoute
|
||||
*/
|
||||
public static function all($url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -259,7 +265,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteController
|
||||
* @return RouteController|IRoute
|
||||
*/
|
||||
public static function controller($url, $controller, array $settings = null)
|
||||
{
|
||||
@@ -281,7 +287,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteResource
|
||||
* @return RouteResource|IRoute
|
||||
*/
|
||||
public static function resource($url, $controller, array $settings = null)
|
||||
{
|
||||
@@ -297,6 +303,28 @@ class SimpleRouter
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add exception callback handler.
|
||||
*
|
||||
* @param \Closure $callback
|
||||
* @return CallbackExceptionHandler $callbackHandler
|
||||
*/
|
||||
public static function error(\Closure $callback)
|
||||
{
|
||||
$routes = static::router()->getRoutes();
|
||||
|
||||
$callbackHandler = new CallbackExceptionHandler($callback);
|
||||
|
||||
$group = new RouteGroup();
|
||||
$group->addExceptionHandler($callbackHandler);
|
||||
|
||||
array_unshift($routes, $group);
|
||||
|
||||
static::router()->setRoutes($routes);
|
||||
|
||||
return $callbackHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
@@ -351,7 +379,7 @@ class SimpleRouter
|
||||
*/
|
||||
public static function router()
|
||||
{
|
||||
if(static::$router === null) {
|
||||
if (static::$router === null) {
|
||||
static::$router = new Router();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,24 +2,34 @@
|
||||
|
||||
class DummyController
|
||||
{
|
||||
public function start()
|
||||
public function method1()
|
||||
{
|
||||
echo static::class . '@' . 'start() OK';
|
||||
|
||||
}
|
||||
|
||||
public function method2()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function param($params = null)
|
||||
{
|
||||
$params = func_get_args();
|
||||
echo 'Params: ' . join(', ', $params);
|
||||
echo join(', ', func_get_args());
|
||||
}
|
||||
|
||||
public function notFound()
|
||||
{
|
||||
echo 'not found';
|
||||
}
|
||||
public function getTest()
|
||||
{
|
||||
echo 'getTest';
|
||||
}
|
||||
|
||||
public function silent() {
|
||||
public function postTest()
|
||||
{
|
||||
echo 'postTest';
|
||||
}
|
||||
|
||||
}
|
||||
public function putTest()
|
||||
{
|
||||
echo 'putTest';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
class ResponseException extends \Exception
|
||||
{
|
||||
protected $response;
|
||||
|
||||
public function __construct($response)
|
||||
{
|
||||
$this->response = $response;
|
||||
parent::__construct('', 0);
|
||||
}
|
||||
|
||||
public function getResponse()
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
$request->setUri(new \Pecee\Http\Uri('/'));
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
$request->setUri(new \Pecee\Http\Uri('/'));
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
throw new ResponseException('ExceptionHandler loaded');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 1 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 2 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 3 loaded' . chr(10);
|
||||
|
||||
throw new ExceptionHandlerException('All good!', 666);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
class ResourceController implements \Pecee\Controllers\IResourceController
|
||||
{
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'index';
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
echo 'show ' . $id;
|
||||
}
|
||||
|
||||
public function store()
|
||||
{
|
||||
echo 'store';
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
echo 'create';
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
echo 'edit ' . $id;
|
||||
}
|
||||
|
||||
public function update($id)
|
||||
{
|
||||
echo 'update ' . $id;
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
echo 'destroy ' . $id;
|
||||
}
|
||||
}
|
||||
+26
-38
@@ -2,8 +2,7 @@
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -13,82 +12,71 @@ class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
$this->result = false;
|
||||
|
||||
SimpleRouter::group(['prefix' => '/group'], function () {
|
||||
TestRouter::group(['prefix' => '/group'], function () {
|
||||
$this->result = true;
|
||||
});
|
||||
|
||||
try {
|
||||
SimpleRouter::start();
|
||||
} catch (Exception $e) {
|
||||
// ignore RouteNotFound exception
|
||||
}
|
||||
TestRouter::debug('/', 'get');
|
||||
} catch(\Exception $e) {
|
||||
|
||||
}
|
||||
$this->assertTrue($this->result);
|
||||
}
|
||||
|
||||
public function testNestedGroup()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/api/v1/test');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/api/v1/test', 'get');
|
||||
|
||||
}
|
||||
|
||||
public function testManyRoutes()
|
||||
public function testMultipleRoutes()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/match');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::get('/my/match', 'DummyController@start');
|
||||
TestRouter::get('/my/match', 'DummyController@method1');
|
||||
|
||||
SimpleRouter::group(['prefix' => '/service'], function () {
|
||||
TestRouter::group(['prefix' => '/service'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/no-match', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/no-match', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/match', 'get');
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/fancy/url/1');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
// Test array name
|
||||
SimpleRouter::get('/my/fancy/url/1', 'DummyController@start', ['as' => 'fancy1']);
|
||||
TestRouter::get('/my/fancy/url/1', 'DummyController@method1', ['as' => 'fancy1']);
|
||||
|
||||
// Test method name
|
||||
SimpleRouter::get('/my/fancy/url/2', 'DummyController@start')->setName('fancy2');
|
||||
TestRouter::get('/my/fancy/url/2', 'DummyController@method1')->setName('fancy2');
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debugNoReset('/my/fancy/url/1');
|
||||
|
||||
$this->assertEquals('/my/fancy/url/1/', SimpleRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', SimpleRouter::getUrl('fancy2'));
|
||||
$this->assertEquals('/my/fancy/url/1/', TestRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', TestRouter::getUrl('fancy2'));
|
||||
|
||||
TestRouter::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
|
||||
{
|
||||
|
||||
public static function debugNoReset($testUri, $testMethod = 'get')
|
||||
{
|
||||
static::request()->setUri(new \Pecee\Http\Uri($testUri));
|
||||
static::request()->setMethod($testMethod);
|
||||
|
||||
static::start();
|
||||
}
|
||||
|
||||
public static function debug($testUri, $testMethod = 'get')
|
||||
{
|
||||
try {
|
||||
static::debugNoReset($testUri, $testMethod);
|
||||
} catch(\Exception $e) {
|
||||
static::router()->reset();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
static::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
public static function debugOutput($testUri, $testMethod = 'get')
|
||||
{
|
||||
$response = null;
|
||||
|
||||
// Route request
|
||||
ob_start();
|
||||
static::debug($testUri, $testMethod);
|
||||
$response = ob_get_contents();
|
||||
ob_end_clean();
|
||||
|
||||
// Return response
|
||||
return $response;
|
||||
}
|
||||
|
||||
}
|
||||
+12
-19
@@ -3,39 +3,32 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class MiddlewareTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testMiddlewareFound()
|
||||
{
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
$this->setExpectedException(MiddlewareLoadedException::class);
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
|
||||
}
|
||||
|
||||
public function testNestedMiddlewareLoad()
|
||||
public function testNestedMiddlewareDontLoad()
|
||||
{
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
|
||||
TestRouter::get('/middleware', 'DummyController@method1');
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testCallbackExceptionHandler()
|
||||
{
|
||||
$this->setExpectedException(ExceptionHandlerException::class);
|
||||
|
||||
// Match normal route on alias
|
||||
TestRouter::get('/my-new-url', 'DummyController@method2');
|
||||
TestRouter::get('/my-url', 'DummyController@method1');
|
||||
|
||||
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $exception) {
|
||||
throw new ExceptionHandlerException();
|
||||
});
|
||||
|
||||
TestRouter::debugNoReset('/404-url', 'get');
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterControllerTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testGet()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'get');
|
||||
|
||||
$this->assertEquals('getTest', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testPost()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'post');
|
||||
|
||||
$this->assertEquals('postTest', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testPut()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'put');
|
||||
|
||||
$this->assertEquals('putTest', $response);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/ResourceController.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterResourceTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testResourceStore()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource', 'post');
|
||||
|
||||
$this->assertEquals('store', $response);
|
||||
}
|
||||
|
||||
public function testResourceCreate()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/create', 'get');
|
||||
|
||||
$this->assertEquals('create', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceIndex()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource', 'get');
|
||||
|
||||
$this->assertEquals('index', $response);
|
||||
}
|
||||
|
||||
public function testResourceDestroy()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'delete');
|
||||
|
||||
$this->assertEquals('destroy 38', $response);
|
||||
}
|
||||
|
||||
|
||||
public function testResourceEdit()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38/edit', 'get');
|
||||
|
||||
$this->assertEquals('edit 38', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceUpdate()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'put');
|
||||
|
||||
$this->assertEquals('update 38', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceGet()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'get');
|
||||
|
||||
$this->assertEquals('show 38', $response);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ResponseException.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouteRewriteTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
/**
|
||||
* Redirects to another route through 3 exception handlers.
|
||||
*
|
||||
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
|
||||
* the exceptionhandler is asking the router to reload.
|
||||
*
|
||||
* That means that the exceptionhandler is loaded again, but this time
|
||||
* the router ignores the same rewrite-route to avoid loop - loads
|
||||
* the second which have same behavior and is also ignored before
|
||||
* throwing the final Exception in ExceptionHandler 3.
|
||||
*
|
||||
* So this tests:
|
||||
* 1. If ExceptionHandlers loads
|
||||
* 2. If ExceptionHandlers load in the correct order
|
||||
* 3. If ExceptionHandlers can rewrite the page on error
|
||||
* 4. If the router can avoid redirect-loop due to developer has started loop.
|
||||
* 5. And finally if we reaches the last exception-handler and that the correct
|
||||
* exception-type is being thrown.
|
||||
*/
|
||||
public function testExceptionHandlerRewrite()
|
||||
{
|
||||
global $stack;
|
||||
$stack = [];
|
||||
|
||||
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
|
||||
|
||||
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () {
|
||||
|
||||
TestRouter::get('/my-path', 'DummyController@method1');
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
TestRouter::debug('/my-non-existing-path', 'get');
|
||||
} catch (\ResponseException $e) {
|
||||
|
||||
}
|
||||
|
||||
$expectedStack = [
|
||||
ExceptionHandlerFirst::class,
|
||||
ExceptionHandlerSecond::class,
|
||||
ExceptionHandlerThird::class,
|
||||
];
|
||||
|
||||
$this->assertEquals($expectedStack, $stack);
|
||||
|
||||
}
|
||||
|
||||
public function testRewriteExceptionMessage()
|
||||
{
|
||||
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
|
||||
|
||||
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
|
||||
|
||||
if (strtolower($request->getUri()->getPath()) == '/my/test') {
|
||||
$request->setRewriteUrl('/another-non-existing');
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
TestRouter::debug('/my/test', 'get');
|
||||
}
|
||||
|
||||
}
|
||||
+72
-97
@@ -3,12 +3,7 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerFirst.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerSecond.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerThird.php';
|
||||
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException as NotFoundHttpException;
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -16,113 +11,57 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testMultiParam()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1-param2');
|
||||
TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
|
||||
|
||||
SimpleRouter::get('/test-{param1}-{param2}', function($param1, $param2) {
|
||||
|
||||
if($param1 === 'param1' && $param2 === 'param2') {
|
||||
if ($param1 === 'param1' && $param2 === 'param2') {
|
||||
$this->result = true;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/test-param1-param2', 'get');
|
||||
|
||||
$this->assertTrue($this->result);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to another route through 3 exception handlers.
|
||||
*
|
||||
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
|
||||
* the exceptionhandler is asking the router to reload.
|
||||
*
|
||||
* That means that the exceptionhandler is loaded again, but this time
|
||||
* the router ignores the same rewrite-route to avoid loop - loads
|
||||
* the second which have same behavior and is also ignored before
|
||||
* throwing the final Exception in ExceptionHandler 3.
|
||||
*
|
||||
* So this tests:
|
||||
* 1. If ExceptionHandlers loads
|
||||
* 2. If ExceptionHandlers load in the correct order
|
||||
* 3. If ExceptionHandlers can rewrite the page on error
|
||||
* 4. If the router can avoid redirect-loop due to developer has started loop.
|
||||
* 5. And finally if we reaches the last exception-handler and that the correct
|
||||
* exception-type is being thrown.
|
||||
*/
|
||||
public function testNotFound()
|
||||
{
|
||||
$this->setExpectedException('ExceptionHandlerException');
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1-param2');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => ['TestExceptionHandlerFirst', 'TestExceptionHandlerSecond']], function () {
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'TestExceptionHandlerThird'], function () {
|
||||
|
||||
SimpleRouter::get('/non-existing-path', 'DummyController@start');
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
|
||||
TestRouter::get('/non-existing-path', 'DummyController@method1');
|
||||
TestRouter::debug('/test-param1-param2', 'post');
|
||||
}
|
||||
|
||||
public function testGet()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
}
|
||||
|
||||
public function testPost()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::post('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::post('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
}
|
||||
|
||||
public function testPut()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('put');
|
||||
|
||||
SimpleRouter::put('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::put('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'put');
|
||||
}
|
||||
|
||||
public function testDelete()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('delete');
|
||||
|
||||
SimpleRouter::delete('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::delete('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'delete');
|
||||
}
|
||||
|
||||
public function testMethodNotAllowed()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
|
||||
try {
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
} catch (\Exception $e) {
|
||||
$this->assertEquals(403, $e->getCode());
|
||||
}
|
||||
@@ -130,43 +69,79 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testSimpleParam()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1');
|
||||
TestRouter::get('/test-{param1}', 'DummyController@param');
|
||||
$response = TestRouter::debugOutput('/test-param1', 'get');
|
||||
|
||||
SimpleRouter::get('/test-{param1}', 'DummyController@param');
|
||||
SimpleRouter::start();
|
||||
$this->assertEquals('param1', $response);
|
||||
}
|
||||
|
||||
public function testPathParamRegex()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test/path/123123');
|
||||
TestRouter::get('/{lang}/productscategories/{name}', 'DummyController@param', ['where' => ['lang' => '[a-z]+', 'name' => '[A-Za-z0-9\-]+']]);
|
||||
$response = TestRouter::debugOutput('/it/productscategories/system', 'get');
|
||||
|
||||
SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
|
||||
SimpleRouter::start();
|
||||
$this->assertEquals('it, system', $response);
|
||||
}
|
||||
|
||||
public function testDomainRoute()
|
||||
public function testDomainAllowedRoute()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test');
|
||||
SimpleRouter::request()->setHost('hello.world.com');
|
||||
|
||||
$this->result = false;
|
||||
|
||||
SimpleRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
SimpleRouter::get('/test', function ($subdomain = null) {
|
||||
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
TestRouter::get('/test', function ($subdomain = null) {
|
||||
$this->result = ($subdomain === 'hello');
|
||||
});
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::request()->setHost('hello.world.com');
|
||||
TestRouter::debug('/test', 'get');
|
||||
|
||||
$this->assertTrue($this->result);
|
||||
|
||||
}
|
||||
|
||||
public function testDomainNotAllowedRoute()
|
||||
{
|
||||
$this->result = false;
|
||||
|
||||
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
TestRouter::get('/test', function ($subdomain = null) {
|
||||
$this->result = ($subdomain === 'hello');
|
||||
});
|
||||
});
|
||||
|
||||
TestRouter::request()->setHost('other.world.com');
|
||||
|
||||
|
||||
TestRouter::debug('/test', 'get');
|
||||
|
||||
$this->assertFalse($this->result);
|
||||
|
||||
}
|
||||
|
||||
public function testRegEx()
|
||||
{
|
||||
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
|
||||
TestRouter::debug('/my/custom-path', 'get');
|
||||
}
|
||||
|
||||
public function testDefaultParameterRegex()
|
||||
{
|
||||
TestRouter::get('/my/{path}', 'DummyController@param', ['defaultParameterRegex' => '[\w\-]+']);
|
||||
$output = TestRouter::debugOutput('/my/custom-regex', 'get');
|
||||
|
||||
$this->assertEquals('custom-regex', $output);
|
||||
}
|
||||
|
||||
public function testDefaultParameterRegexGroup()
|
||||
{
|
||||
TestRouter::group(['defaultParameterRegex' => '[\w\-]+'], function() {
|
||||
TestRouter::get('/my/{path}', 'DummyController@param');
|
||||
});
|
||||
|
||||
$output = TestRouter::debugOutput('/my/custom-regex', 'get');
|
||||
|
||||
$this->assertEquals('custom-regex', $output);
|
||||
}
|
||||
|
||||
}
|
||||
+105
-46
@@ -3,111 +3,170 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterUrlTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
protected $result = false;
|
||||
|
||||
protected function getUrl($name = null, $parameters = null, array $getParams = [])
|
||||
public function testIssue253()
|
||||
{
|
||||
return SimpleRouter::getUrl($name, $parameters, $getParams);
|
||||
TestRouter::get('/', 'DummyController@method1');
|
||||
TestRouter::get('/page/{id?}', 'DummyController@method1');
|
||||
TestRouter::get('/test-output', function() {
|
||||
return 'return value';
|
||||
});
|
||||
|
||||
TestRouter::debugNoReset('/page/22', 'get');
|
||||
$this->assertEquals('/page/{id?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
$this->assertEquals('/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
$output = TestRouter::debugOutput('/test-output', 'get');
|
||||
$this->assertEquals('return value', $output);
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testUnicodeCharacters()
|
||||
{
|
||||
// Test spanish characters
|
||||
TestRouter::get('/cursos/listado/{listado?}/{category?}', '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());
|
||||
|
||||
// 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();
|
||||
}
|
||||
|
||||
public function testOptionalParameters()
|
||||
{
|
||||
TestRouter::get('/aviso/legal', 'DummyController@method1');
|
||||
TestRouter::get('/aviso/{aviso}', 'DummyController@method1');
|
||||
TestRouter::get('/pagina/{pagina}', 'DummyController@method1');
|
||||
TestRouter::get('/{pagina?}', 'DummyController@method1');
|
||||
|
||||
TestRouter::debugNoReset('/aviso/optional', 'get');
|
||||
$this->assertEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/pagina/optional', 'get');
|
||||
$this->assertEquals('/pagina/{pagina}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/optional', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertNotEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testSimilarUrls()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::resource('/url11', 'DummyController@method1');
|
||||
TestRouter::resource('/url1', 'DummyController@method1', ['as' => 'match']);
|
||||
|
||||
TestRouter::debugNoReset('/url1', 'get');
|
||||
|
||||
$this->assertEquals(TestRouter::getUrl('match'), TestRouter::getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/');
|
||||
|
||||
// Match normal route on alias
|
||||
SimpleRouter::get('/', 'DummyController@silent', ['as' => 'home']);
|
||||
TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
|
||||
|
||||
SimpleRouter::get('/about', 'DummyController@about');
|
||||
TestRouter::get('/about', 'DummyController@about');
|
||||
|
||||
SimpleRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
TestRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
|
||||
// Match route with prefix on alias
|
||||
SimpleRouter::get('/{id?}', 'DummyController@start', ['as' => 'home']);
|
||||
TestRouter::get('/{id?}', 'DummyController@method2', ['as' => 'home']);
|
||||
|
||||
// Match controller with prefix and alias
|
||||
SimpleRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
TestRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
|
||||
// Match controller with prefix and NO alias
|
||||
SimpleRouter::controller('/pages', 'DummyController');
|
||||
TestRouter::controller('/pages', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
TestRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
|
||||
// Match resource controller
|
||||
SimpleRouter::resource('phones', 'DummyController');
|
||||
TestRouter::resource('phones', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
TestRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
|
||||
// Match controller with no prefix and no alias
|
||||
SimpleRouter::controller('/cats', 'CatsController');
|
||||
TestRouter::controller('/cats', 'CatsController');
|
||||
|
||||
// Pretend to load page
|
||||
SimpleRouter::start();
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', $this->getUrl('gadgets.iphone'));
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', TestRouter::getUrl('gadgets.iphone'));
|
||||
|
||||
$this->assertEquals('/api/phones/create/', $this->getUrl('api.phones.create'));
|
||||
$this->assertEquals('/api/phones/create/', TestRouter::getUrl('api.phones.create'));
|
||||
|
||||
// Should match /
|
||||
$this->assertEquals('/', $this->getUrl('home'));
|
||||
$this->assertEquals('/', TestRouter::getUrl('home'));
|
||||
|
||||
// Should match /about/
|
||||
$this->assertEquals('/about/', $this->getUrl('DummyController@about'));
|
||||
$this->assertEquals('/about/', TestRouter::getUrl('DummyController@about'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', $this->getUrl('DummyController@start'));
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('DummyController@method2'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', $this->getUrl('admin.home'));
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('admin.home'));
|
||||
|
||||
// Should match /admin/2/
|
||||
$this->assertEquals('/admin/2/', $this->getUrl('admin.home', ['id' => 2]));
|
||||
$this->assertEquals('/admin/2/', TestRouter::getUrl('admin.home', ['id' => 2]));
|
||||
|
||||
// Should match /admin/users/
|
||||
$this->assertEquals('/admin/users/', $this->getUrl('admin.users'));
|
||||
$this->assertEquals('/admin/users/', TestRouter::getUrl('admin.users'));
|
||||
|
||||
// Should match /admin/users/home/
|
||||
$this->assertEquals('/admin/users/home/', $this->getUrl('admin.users@home'));
|
||||
$this->assertEquals('/admin/users/home/', TestRouter::getUrl('admin.users@home'));
|
||||
|
||||
// Should match /cats/
|
||||
$this->assertEquals('/cats/', $this->getUrl('CatsController'));
|
||||
$this->assertEquals('/cats/', TestRouter::getUrl('CatsController'));
|
||||
|
||||
// Should match /cats/view/
|
||||
$this->assertEquals('/cats/view/', $this->getUrl('CatsController', 'view'));
|
||||
$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', 'view'));
|
||||
|
||||
// Should match /cats/view/
|
||||
//$this->assertEquals('/cats/view/', $this->getUrl('CatsController', ['view']));
|
||||
//$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', ['view']));
|
||||
|
||||
// Should match /cats/view/666
|
||||
$this->assertEquals('/cats/view/666/', $this->getUrl('CatsController@getView', ['666']));
|
||||
$this->assertEquals('/cats/view/666/', TestRouter::getUrl('CatsController@getView', ['666']));
|
||||
|
||||
// Should match /funny/man/
|
||||
$this->assertEquals('/funny/man/', $this->getUrl('/funny/man'));
|
||||
$this->assertEquals('/funny/man/', TestRouter::getUrl('/funny/man'));
|
||||
|
||||
// Should match /?jackdaniels=true&cola=yeah
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', $this->getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
|
||||
}
|
||||
|
||||
public function testRegEx()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/custom-path');
|
||||
|
||||
SimpleRouter::get('/my/{path}', 'DummyController@start')->where(['path' => '[a-zA-Z\-]+']);
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user