mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c1c25e19ff | |||
| dc7faf52c0 | |||
| 539e905b45 | |||
| 5977efc942 |
@@ -15,73 +15,71 @@ If you want a great new feature or experience any issues what-so-ever, please fe
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Getting started](#getting-started)
|
||||
- [Requirements](#requirements)
|
||||
- [Notes](#notes-1)
|
||||
- [Features](#features)
|
||||
- [Installation](#installation)
|
||||
- [Setting up Apache](#setting-up-apache)
|
||||
- [Setting up Nginx](#setting-up-nginx)
|
||||
- [Configuration](#configuration)
|
||||
- [Helper functions](#helper-functions)
|
||||
- Gettings started
|
||||
- Requirements
|
||||
- Notes
|
||||
- Features
|
||||
- Installation
|
||||
- Setting up Apache
|
||||
- Setting up Nginx
|
||||
- Setting up simple-php-router
|
||||
- Helper methods
|
||||
|
||||
- [Routes](#routes)
|
||||
- [Basic routing](#basic-routing)
|
||||
- [Available methods](#available-methods)
|
||||
- [Multiple HTTP-verbs](#multiple-http-verbs)
|
||||
- [Route parameters](#route-parameters)
|
||||
- [Required parameters](#required-parameters)
|
||||
- [Optional parameters](#optional-parameters)
|
||||
- [Regular expression constraints](#regular-expression-constraints)
|
||||
- [Regular expression route-match](#regular-expression-route-match)
|
||||
- [Named routes](#named-routes)
|
||||
- [Generating URLs To Named Routes](#generating-urls-to-named-routes)
|
||||
- [Router groups](#router-groups)
|
||||
- [Middleware](#middleware)
|
||||
- [Namespaces](#namespaces)
|
||||
- [Subdomain-routing](#subdomain-routing)
|
||||
- [Route prefixes](#route-prefixes)
|
||||
- [Form Method Spoofing](#form-method-spoofing)
|
||||
- [Accessing The Current Route](#accessing-the-current-route)
|
||||
- [Other examples](#other-examples)
|
||||
- Routes
|
||||
- Basic routing
|
||||
- Available methods
|
||||
- Multiple HTTP-verbs
|
||||
- Route parameters
|
||||
- Required parameters
|
||||
- Optional parameters
|
||||
- Regular expression constraints
|
||||
- Regular expression route-match
|
||||
- Named routes
|
||||
- Generating URLs To Named Routes
|
||||
- Router groups
|
||||
- Middleware
|
||||
- Namespaces
|
||||
- Subdomain-routing
|
||||
- Route prefixes
|
||||
- Form Method Spoofing
|
||||
- Accessing The Current Route
|
||||
- Other examples
|
||||
|
||||
- [CSRF-protection](#csrf-protection)
|
||||
- [Adding CSRF-verifier](#adding-csrf-verifier)
|
||||
- [Getting CSRF-token](#getting-csrf-token)
|
||||
- CSRF-protection
|
||||
- Adding CSRF-verifier
|
||||
- Getting CSRF-token
|
||||
|
||||
- [Middlewares](#middlewares)
|
||||
- [Example](#example)
|
||||
- [ExceptionHandler](#exceptionhandler)
|
||||
- [Example](#example-1)
|
||||
- Middleware
|
||||
- Example
|
||||
- ExceptionHandler
|
||||
- Example
|
||||
|
||||
- [Urls](#urls)
|
||||
- [Get by name (single route)](#get-by-name-single-route)
|
||||
- [Get by name (controller route)](#get-by-name-controller-route)
|
||||
- [Get by class](#get-by-class)
|
||||
- [Get by custom names for methods on a controller/resource route](#using-custom-names-for-methods-on-a-controllerresource-route)
|
||||
- [Getting REST/resource controller urls](#getting-restresource-controller-urls)
|
||||
- [Get the current url](#get-the-current-url)
|
||||
- Urls
|
||||
- Get by name (single route)
|
||||
- Get by name (controller route)
|
||||
- Get by class
|
||||
- Get by custom names for methods on a controller/resource route
|
||||
- Getting REST/resource controller urls
|
||||
|
||||
- [Input & parameters](#input--parameters)
|
||||
- [Using the Input class to manage parameters](#using-the-input-class-to-manage-parameters)
|
||||
- [Get single parameter value](#get-single-parameter-value)
|
||||
- [Get parameter object](#get-parameter-object)
|
||||
- [Managing files](#managing-files)
|
||||
- [Get all parameters](#get-all-parameters)
|
||||
- Input & parameters
|
||||
- Return single parameter value
|
||||
- Return single parameter object
|
||||
- Managing files
|
||||
- Return all parameters
|
||||
|
||||
- [Advanced](#advanced)
|
||||
- [Url rewriting](#url-rewriting)
|
||||
- [Rewrite using callback](#rewrite-using-callback)
|
||||
- [Rewrite using url](#rewrite-using-url)
|
||||
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
|
||||
- [Adding routes manually](#adding-routes-manually)
|
||||
- [Parameters](#parameters)
|
||||
- [Custom default regex for matching parameters](#custom-default-regex-for-matching-parameters)
|
||||
- [Extending](#extending)
|
||||
- Advanced
|
||||
- Bootmanager: loading routes dynamically
|
||||
- Ovewrite route about to be loaded
|
||||
- Examples
|
||||
- Rewriting to new route
|
||||
- Changing callback
|
||||
|
||||
- [Credits](#credits)
|
||||
- [Sites](#sites)
|
||||
- [License](#license)
|
||||
- Adding routes manually
|
||||
- Extending
|
||||
|
||||
- Credits
|
||||
- Sites
|
||||
- License
|
||||
|
||||
___
|
||||
|
||||
@@ -156,21 +154,7 @@ 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
|
||||
```
|
||||
|
||||
### Configuration
|
||||
### Setting up simple-php-router
|
||||
|
||||
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.
|
||||
|
||||
@@ -208,6 +192,8 @@ To implement the functions below, simply copy the code to a new file and require
|
||||
|
||||
```php
|
||||
<?php
|
||||
use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
@@ -225,43 +211,41 @@ To implement the functions below, simply copy the code to a new file and require
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
function url($name = null, $parameters = null, $getParams = null)
|
||||
{
|
||||
return SimpleRouter::getUrl($name, $parameters, $getParams);
|
||||
function url($name = null, $parameters = null, $getParams = null) {
|
||||
SimpleRouter::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Pecee\Http\Response
|
||||
* Get current csrf-token
|
||||
* @return null|string
|
||||
*/
|
||||
function response()
|
||||
{
|
||||
return SimpleRouter::response();
|
||||
function csrf_token() {
|
||||
$token = new \Pecee\CsrfToken();
|
||||
return $token->getToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get request object
|
||||
* @return \Pecee\Http\Request
|
||||
*/
|
||||
function request()
|
||||
{
|
||||
function request() {
|
||||
return SimpleRouter::request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get response object
|
||||
* @return \Pecee\Http\Response
|
||||
*/
|
||||
function response() {
|
||||
return SimpleRouter::response();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get input class
|
||||
* @return \Pecee\Http\Input\Input
|
||||
*/
|
||||
function input()
|
||||
{
|
||||
return request()->getInput();
|
||||
}
|
||||
|
||||
function redirect($url, $code = null)
|
||||
{
|
||||
if ($code !== null) {
|
||||
response()->httpCode($code);
|
||||
}
|
||||
|
||||
response()->redirect($url);
|
||||
function input() {
|
||||
return SimpleRouter::request()->getInput();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -437,7 +421,7 @@ Route groups allow you to share route attributes, such as middleware or namespac
|
||||
To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware are executed in the order they are listed in the array:
|
||||
|
||||
```php
|
||||
SimpleRouter::group(['middleware' => \Demo\Middleware\Auth::class], function () {
|
||||
SimpleRouter::group(['middleware' => '\Demo\Middleware\Auth'], function () {
|
||||
SimpleRouter::get('/', function () {
|
||||
// Uses Auth Middleware
|
||||
});
|
||||
@@ -452,11 +436,6 @@ SimpleRouter::group(['middleware' => \Demo\Middleware\Auth::class], function ()
|
||||
|
||||
Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the `namespace` parameter in the group array:
|
||||
|
||||
#### Note
|
||||
Group namespaces will only be added to routes with relative callbacks.
|
||||
For example if your route has an absolute callback like `\Demo\Controller\DefaultController@home`, the namespace from the route will not be prepended.
|
||||
To fix this you can make the callback relative by removing the `\` in the beginning of the callback.
|
||||
|
||||
```php
|
||||
SimpleRouter::group(['namespace' => 'Admin'], function () {
|
||||
// Controllers Within The "App\Http\Controllers\Admin" Namespace
|
||||
@@ -500,8 +479,7 @@ HTML forms do not support `PUT`, `PATCH` or `DELETE` actions. So, when defining
|
||||
You can access information about the current route loaded by using the following method:
|
||||
|
||||
```php
|
||||
SimpleRouter::request()->getLoadedRoute();
|
||||
request()->getLoadedRoute();
|
||||
SimpleRouter::router()->getLoadedRoute();
|
||||
```
|
||||
|
||||
## Other examples
|
||||
@@ -515,7 +493,7 @@ use Pecee\SimpleRouter\SimpleRouter;
|
||||
/* Adding custom csrfVerifier here */
|
||||
SimpleRouter::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
|
||||
|
||||
SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHandler' => \Demo\Handlers\CustomExceptionHandler::class], function() {
|
||||
SimpleRouter::group(['middleware' => '\Demo\Middlewares\Site', 'exceptionHandler' => 'Handlers\CustomExceptionHandler'], function() {
|
||||
|
||||
|
||||
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show', ['where' => ['id' => '[0-9]+']]);
|
||||
@@ -525,7 +503,7 @@ SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHa
|
||||
* Restful resource (see IRestController interface for available methods)
|
||||
*/
|
||||
|
||||
SimpleRouter::resource('/rest', ControllerRessource::class);
|
||||
SimpleRouter::resource('/rest', 'ControllerRessource');
|
||||
|
||||
|
||||
/**
|
||||
@@ -541,7 +519,7 @@ SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHa
|
||||
* etc.
|
||||
*/
|
||||
|
||||
SimpleRouter::controller('/animals', ControllerAnimals::class);
|
||||
SimpleRouter::controller('/animals', 'ControllerAnimals');
|
||||
|
||||
});
|
||||
|
||||
@@ -606,19 +584,13 @@ namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
class CustomMiddleware implements Middleware {
|
||||
|
||||
public function handle(Request $request) {
|
||||
public function handle(Request $request, ILoadableRoute &$route) {
|
||||
|
||||
// Authenticate user, will be available using request()->user
|
||||
$request->user = User::authenticate();
|
||||
|
||||
// If authentication failed, redirect request to user-login page.
|
||||
if($request->user === null) {
|
||||
$request->setRewriteUrl(url('user.login'));
|
||||
return $request;
|
||||
}
|
||||
$request->setUri(url('home'));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -642,10 +614,11 @@ namespace Demo\Handlers;
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
class CustomExceptionHandler implements IExceptionHandler
|
||||
{
|
||||
public function handleError(Request $request, \Exception $error)
|
||||
public function handleError(Request $request, ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
|
||||
/* You can use the exception handler to format errors depending on the request and type. */
|
||||
@@ -662,9 +635,14 @@ class CustomExceptionHandler implements IExceptionHandler
|
||||
/* The router will throw the NotFoundHttpException on 404 */
|
||||
if($error instanceof NotFoundHttpException) {
|
||||
|
||||
// Render custom 404-page
|
||||
/*
|
||||
* Render your own custom 404-view, rewrite the request to another route,
|
||||
* or simply return the $request object to ignore the error and continue on rendering the route.
|
||||
*
|
||||
* The code below will make the router render our page.notfound route.
|
||||
*/
|
||||
|
||||
$request->setRewriteCallback('Demo\Controllers\PageController@notFound');
|
||||
$request->setUri(url('page.notfound'));
|
||||
return $request;
|
||||
|
||||
}
|
||||
@@ -682,7 +660,7 @@ class CustomExceptionHandler implements IExceptionHandler
|
||||
|
||||
By default all controller and resource routes will use a simplified version of their url as name.
|
||||
|
||||
### Get by name (single route)
|
||||
### Get routes using custom name (single route)
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
|
||||
@@ -695,10 +673,10 @@ url('product', null, ['category' => 'shoes']);
|
||||
# /product-view/?category=shoes
|
||||
```
|
||||
|
||||
### Get by name (controller route)
|
||||
### Getting the url using the name (controller route)
|
||||
|
||||
```php
|
||||
SimpleRouter::controller('/images', ImagesController::class, ['as' => 'picture']);
|
||||
SimpleRouter::controller('/images', 'ImagesController', ['as' => 'picture']);
|
||||
|
||||
url('picture@getView', null, ['category' => 'shoes']);
|
||||
url('picture', 'getView', ['category' => 'shoes']);
|
||||
@@ -710,7 +688,7 @@ url('picture', 'view');
|
||||
# /images/view/
|
||||
```
|
||||
|
||||
### Get by class
|
||||
### Getting the url using class
|
||||
|
||||
```php
|
||||
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
|
||||
@@ -727,7 +705,7 @@ url('ImagesController@getImage', null, ['id' => 22]);
|
||||
### Using custom names for methods on a controller/resource route
|
||||
|
||||
```php
|
||||
SimpleRouter::controller('gadgets', GadgetsController::class, ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
SimpleRouter::controller('gadgets', 'GadgetsController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
|
||||
url('gadgets.iphone');
|
||||
|
||||
@@ -738,7 +716,7 @@ url('gadgets.iphone');
|
||||
### Getting REST/resource controller urls
|
||||
|
||||
```php
|
||||
SimpleRouter::resource('/phones', PhonesController::class);
|
||||
SimpleRouter::resource('/phones', 'PhonesController');
|
||||
|
||||
url('phones');
|
||||
url('phones.index');
|
||||
@@ -753,7 +731,7 @@ url('phones.edit');
|
||||
# /phones/edit/
|
||||
```
|
||||
|
||||
### Get the current url
|
||||
### Return the current url
|
||||
|
||||
```php
|
||||
url();
|
||||
@@ -770,7 +748,7 @@ url(null, null, ['q' => 'cars']);
|
||||
|
||||
We've added the `Input` class to easy access and manage parameters from your Controller-classes.
|
||||
|
||||
### Get single parameter value:
|
||||
**Return single parameter value (matches both GET, POST, FILE):**
|
||||
|
||||
If items is grouped in the html, it will return an array of items.
|
||||
|
||||
@@ -780,7 +758,7 @@ If items is grouped in the html, it will return an array of items.
|
||||
$value = input()->get($index, $defaultValue, $methods);
|
||||
```
|
||||
|
||||
### Get parameter object
|
||||
**Return parameter object (matches both GET, POST, FILE):**
|
||||
|
||||
Will return an instance of `InputItem` or `InputFile` depending on the type.
|
||||
|
||||
@@ -796,7 +774,7 @@ If items is grouped in the html, it will return an array of items.
|
||||
$object = input()->getObject($index, $defaultValue = null, $methods = null);
|
||||
```
|
||||
|
||||
### Return specific GET parameter (where name is the name of your parameter):
|
||||
**Return specific GET parameter (where name is the name of your parameter):**
|
||||
|
||||
```php
|
||||
# -- match any (default) --
|
||||
@@ -820,11 +798,9 @@ $object = input()->get($index, $defaultValue, 'file');
|
||||
$object = input()->findGet($index, $defaultValue);
|
||||
$object = input()->findPost($index, $defaultValue);
|
||||
$object = input()->findFile($index, $defaultValue);
|
||||
```
|
||||
|
||||
### Managing files
|
||||
# -- examples --
|
||||
|
||||
```php
|
||||
/**
|
||||
* In this small example we loop through a collection of files
|
||||
* added on the page like this
|
||||
@@ -842,10 +818,9 @@ foreach(input()->get('images', []) as $image)
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Get all parameters
|
||||
**Return all parameters:**
|
||||
|
||||
```php
|
||||
// Get all
|
||||
@@ -885,130 +860,7 @@ $siteId = input()->get('site_id', 2, ['post', 'get']);
|
||||
|
||||
# Advanced
|
||||
|
||||
## Url rewriting
|
||||
Sometimes it can be useful to manipulate the route about to be loaded.
|
||||
simple-php-router allows you to easily change the route about to be executed.
|
||||
All information about the current route is stored in the ```\Pecee\SimpleRouter\Router``` instance's `loadedRoute` property.
|
||||
|
||||
For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::router()`.
|
||||
|
||||
|
||||
```php
|
||||
use Pecee\SimpleRouter;
|
||||
$request = SimpleRouter::request();
|
||||
$request->setRewriteCallback('Example\MyCustomClass@hello');
|
||||
|
||||
// -- or you can rewrite by url --
|
||||
|
||||
$request->setRewriteUrl('/my-rewrite-url');
|
||||
```
|
||||
|
||||
**Note:** It's only possible to change the route BEFORE the route has initially been rendered. You can use the `Request` object to manipulate the route which are about to be loaded.
|
||||
|
||||
### Rewrite using callback
|
||||
|
||||
This method is most efficient, as it will render the route immediately.
|
||||
|
||||
This method is useful for rendering 404-pages etc.
|
||||
|
||||
You can also change the callback by modifying the `$route` parameter. This is perfect if you just want to display a view quickly - or change the callback depending
|
||||
on some criteria's for the request.
|
||||
|
||||
The callback below will fire immediately after the `Middleware` or `ExceptionHandler` has been loaded, as they are loaded before the route is rendered.
|
||||
If you wish to change the callback from outside, please have this in mind.
|
||||
|
||||
The example below will render `DefaultController@notFound` regardless of the url.
|
||||
|
||||
**NOTE: Use this method if you want to load another controller. No additional middlewares or rules will be loaded.**
|
||||
|
||||
##### Middleware example
|
||||
|
||||
```php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class CustomMiddleware implements IMiddleware {
|
||||
|
||||
public function handle(Request $request) {
|
||||
|
||||
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
|
||||
return $request;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
##### Exception handler example
|
||||
|
||||
```php
|
||||
namespace Demo\Handlers;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
class CustomExceptionHandler implements IExceptionHandler
|
||||
{
|
||||
public function handleError(Request $request, \Exception $error)
|
||||
{
|
||||
/* The router will throw the NotFoundHttpException on 404 */
|
||||
if($error instanceof NotFoundHttpException) {
|
||||
|
||||
/*
|
||||
* Render your own custom 404-view, rewrite the request to another route,
|
||||
* or simply return the $request object to ignore the error and continue on rendering the route.
|
||||
*
|
||||
* The code below will make the router render our page.notfound route.
|
||||
*/
|
||||
|
||||
$request->setRewriteCallback('Demo\Controllers\DefaultController@notFound');
|
||||
return $request;
|
||||
|
||||
}
|
||||
|
||||
throw $error;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### Rewrite using url
|
||||
|
||||
The example below will cause the router to reload the request and reinitialize all the routes. This method is slower, but will ensure that all middlewares and rules for the route is loaded.
|
||||
|
||||
This method is useful if you want to redirect a url to another-url which is dependent on a middleware. You can also add a custom rule by calling `$request->setRewriteRoute($route)` if
|
||||
you want to customize request-methods or use another route-type like `RouteController` etc.
|
||||
|
||||
We are using the `url()` helper function to get the uri to another route added in the `routes.php` file.
|
||||
|
||||
**NOTE: Use this method if you want to fully load another route using it's settings (request method, middlewares etc).**
|
||||
|
||||
##### Middleware example
|
||||
|
||||
The example below will redirect the request to the `home`-route.
|
||||
|
||||
```php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class CustomMiddleware implements IMiddleware {
|
||||
|
||||
public function handle(Request $request) {
|
||||
|
||||
$request->setRewriteUrl(url('home'));
|
||||
return $request;
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Bootmanager: loading routes dynamically
|
||||
## Load routes dynamicially using the router bootmanager
|
||||
|
||||
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.
|
||||
|
||||
@@ -1024,7 +876,7 @@ class CustomRouterRules implement IRouterBootManager {
|
||||
|
||||
$rewriteRules = [
|
||||
'/my-cat-is-beatiful' => '/article/view/1',
|
||||
'/horses-are-great' => '/article/view/2',
|
||||
'/horses-are-great' => '/article/view/2'
|
||||
];
|
||||
|
||||
foreach($rewriteRules as $url => $rule) {
|
||||
@@ -1032,11 +884,11 @@ class CustomRouterRules implement IRouterBootManager {
|
||||
// If the current uri matches the url, we use our custom route
|
||||
|
||||
if($request->getUri() === $url) {
|
||||
$request->setRewriteUrl($rule);
|
||||
return $request;
|
||||
$request->setUri($rule);
|
||||
}
|
||||
}
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1054,7 +906,83 @@ The last thing we need to do, is to add our custom boot-manager to the ```routes
|
||||
SimpleRouter::addBootManager(new CustomRouterRules());
|
||||
```
|
||||
|
||||
### Adding routes manually
|
||||
## Easily overwrite route about to be loaded
|
||||
Sometimes it can be useful to manipulate the route about to be loaded.
|
||||
simple-php-router allows you to easily change the route about to be executed.
|
||||
All information about the current route is stored in the ```\Pecee\SimpleRouter\Router``` instance's `loadedRoute` property.
|
||||
|
||||
For easy access you can use the shortcut method `\Pecee\SimpleRouter\SimpleRouter::router()`.
|
||||
|
||||
|
||||
```php
|
||||
use Pecee\SimpleRouter;
|
||||
$route = SimpleRouter::router()->getLoadedRoute();
|
||||
|
||||
$route->setCallback('Example\MyCustomClass@hello');
|
||||
|
||||
// -- or you can rewrite by doing --
|
||||
|
||||
$route->setClass('Example\MyCustomClass');
|
||||
$route->setMethod('hello');
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
It's only possible to change the route BEFORE the route has initially been loaded. If you want to redirect to another route, we highly recommend that you
|
||||
modify the `IRoute` object from a `Middleware` or `ExceptionHandler`, like the examples below.
|
||||
|
||||
#### Rewriting to new route
|
||||
|
||||
The example below will cause the router to re-route the request with another url. We are using the `url()` helper function to get the uri to another route added in the `routes.php` file.
|
||||
|
||||
**NOTE: Use this method if you want to fully load another route using it's settings (request method etc).**
|
||||
|
||||
|
||||
```php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
class CustomMiddleware implements Middleware {
|
||||
|
||||
public function handle(Request $request, ILoadableRoute &$route) {
|
||||
|
||||
$request->setUri(url('home'));
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Changing callback
|
||||
You can also change the callback by modifying the `$route` parameter. This is perfect if you just want to display a view quickly - or change the callback depending
|
||||
on some criteria's for the request.
|
||||
|
||||
The callback below will fire immediately after the `Middleware` or `ExceptionHandler` has been loaded, as they are loaded before the route is rendered.
|
||||
If you wish to change the callback from outside, please have this in mind.
|
||||
|
||||
**NOTE: Use this method if you want to load another controller. No additional middlewares or rules will be loaded.**
|
||||
|
||||
```php
|
||||
namespace Demo\Middlewares;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
class CustomMiddleware implements Middleware {
|
||||
|
||||
public function handle(Request $request, ILoadableRoute &$route) {
|
||||
|
||||
$route->callback('DefaultController@home');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
@@ -1063,8 +991,8 @@ If you are up for a challenge, want the full control or simply just want to crea
|
||||
use \Pecee\SimpleRouter\Router;
|
||||
use \Pecee\SimpleRouter\Route\RouteUrl;
|
||||
|
||||
/* Create new Router instance */
|
||||
$router = new Router();
|
||||
/* Grap the router instance */
|
||||
$router = Router::getInstance();
|
||||
|
||||
$route = new RouteUrl('/answer/1', function() {
|
||||
|
||||
@@ -1072,7 +1000,7 @@ $route = new RouteUrl('/answer/1', function() {
|
||||
|
||||
});
|
||||
|
||||
$route->setMiddleware(\Demo\Middlewares\AuthMiddleware::class);
|
||||
$route->setMiddleware('\Demo\Middlewares\AuthMiddleware');
|
||||
$route->setNamespace('\Demo\Controllers');
|
||||
$route->setPrefix('v1');
|
||||
|
||||
@@ -1080,39 +1008,6 @@ $route->setPrefix('v1');
|
||||
$router->addRoute($route);
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
This section contains advanced tips & tricks on extending the usage for parameters.
|
||||
|
||||
### Custom default 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 nessesary 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.
|
||||
|
||||
#### Route
|
||||
|
||||
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');
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
## Extending
|
||||
|
||||
This is a simple example of an integration into a framework.
|
||||
@@ -1147,7 +1042,6 @@ class Router extends SimpleRouter {
|
||||
# Credits
|
||||
|
||||
## Sites
|
||||
|
||||
This is some sites that uses the simple-router project in production.
|
||||
|
||||
- [holla.dk](http://www.holla.dk)
|
||||
|
||||
+23
-29
@@ -1,32 +1,26 @@
|
||||
{
|
||||
"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",
|
||||
"routing",
|
||||
"laravel",
|
||||
"pecee",
|
||||
"route"
|
||||
],
|
||||
"license": "MIT",
|
||||
"support": {
|
||||
"source": "https://github.com/skipperbent/simple-php-router/issues"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "Simon Sessingø",
|
||||
"email": "simon.sessingoe@gmail.com"
|
||||
"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", "routing", "laravel", "pecee" ],
|
||||
"license": "MIT",
|
||||
"support": {
|
||||
"source": "https://github.com/skipperbent/simple-php-router/issues"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "Simon Sessingø",
|
||||
"email": "simon.sessingoe@gmail.com"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=5.4.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "4.7.7"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Pecee\\": "src/Pecee/"
|
||||
}
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=5.4.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "4.7.7"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Pecee\\": "src/Pecee/"
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
namespace Pecee\Controllers;
|
||||
|
||||
interface IResourceController
|
||||
interface IRestController
|
||||
{
|
||||
|
||||
/**
|
||||
@@ -10,7 +10,6 @@ class CsrfToken
|
||||
/**
|
||||
* Generate random identifier for CSRF token
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* @return string
|
||||
*/
|
||||
public static function generateToken()
|
||||
@@ -19,14 +18,7 @@ class CsrfToken
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
$isSourceStrong = false;
|
||||
|
||||
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
|
||||
if ($isSourceStrong === false || $random === false) {
|
||||
throw new \RuntimeException('IV generation failed');
|
||||
}
|
||||
|
||||
return $random;
|
||||
return bin2hex(openssl_random_pseudo_bytes(32));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
namespace Pecee\Handlers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
interface IExceptionHandler
|
||||
{
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
* @param \Exception $error
|
||||
* @return Request|null
|
||||
*/
|
||||
public function handleError(Request $request, \Exception $error);
|
||||
public function handleError(Request $request, ILoadableRoute &$route = null, \Exception $error);
|
||||
|
||||
}
|
||||
@@ -12,8 +12,6 @@ interface IInputItem
|
||||
|
||||
public function setName($name);
|
||||
|
||||
public function getValue();
|
||||
|
||||
public function __toString();
|
||||
|
||||
}
|
||||
@@ -60,7 +60,7 @@ class Input
|
||||
{
|
||||
$list = [];
|
||||
|
||||
foreach ((array)$_FILES as $key => $value) {
|
||||
foreach ($_FILES as $key => $value) {
|
||||
|
||||
// Handle array input
|
||||
if (is_array($value['name']) === false) {
|
||||
@@ -93,9 +93,7 @@ class Input
|
||||
|
||||
$path = $original[$property];
|
||||
|
||||
$fileValues = array_values($index);
|
||||
|
||||
foreach ($fileValues as $i) {
|
||||
foreach (array_values($index) as $i) {
|
||||
$path = $path[$i];
|
||||
}
|
||||
|
||||
@@ -269,29 +267,21 @@ class Input
|
||||
*/
|
||||
public function all(array $filter = null)
|
||||
{
|
||||
$output = $_POST;
|
||||
$output = $_GET;
|
||||
|
||||
if ($this->request->getMethod() === 'post') {
|
||||
|
||||
$contents = file_get_contents('php://input');
|
||||
|
||||
if (strpos(trim($contents), '{') === 0) {
|
||||
$output = json_decode($contents, true);
|
||||
if ($output === false) {
|
||||
$output = [];
|
||||
$post = json_decode($contents, true);
|
||||
if ($post !== false) {
|
||||
$output = array_merge($output, $post);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$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)) : $output;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -43,8 +43,8 @@ class InputFile implements IInputItem
|
||||
], $values);
|
||||
|
||||
return (new static($values['index']))
|
||||
->setSize($values['size'])
|
||||
->setError($values['error'])
|
||||
->setSize($values['size'])
|
||||
->setType($values['type'])
|
||||
->setTmpName($values['tmp_name'])
|
||||
->setFilename($values['name']);
|
||||
@@ -199,7 +199,7 @@ class InputFile implements IInputItem
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if an upload error occurred.
|
||||
* Return true if an upload error occured.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
@@ -256,11 +256,6 @@ class InputFile implements IInputItem
|
||||
return $this->getTmpName();
|
||||
}
|
||||
|
||||
public function getValue()
|
||||
{
|
||||
return $this->getFilename();
|
||||
}
|
||||
|
||||
public function toArray()
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Pecee\Http\Middleware;
|
||||
use Pecee\CsrfToken;
|
||||
use Pecee\Http\Middleware\Exceptions\TokenMismatchException;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
class BaseCsrfVerifier implements IMiddleware
|
||||
{
|
||||
@@ -54,7 +55,7 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
return false;
|
||||
}
|
||||
|
||||
public function handle(Request $request)
|
||||
public function handle(Request $request, ILoadableRoute &$route = null)
|
||||
{
|
||||
|
||||
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) {
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
|
||||
interface IMiddleware
|
||||
{
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
* @return Request|null
|
||||
*/
|
||||
public function handle(Request $request);
|
||||
public function handle(Request $request, ILoadableRoute &$route);
|
||||
|
||||
}
|
||||
+1
-123
@@ -2,9 +2,6 @@
|
||||
namespace Pecee\Http;
|
||||
|
||||
use Pecee\Http\Input\Input;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
use Pecee\SimpleRouter\Route\RouteUrl;
|
||||
use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
class Request
|
||||
{
|
||||
@@ -15,24 +12,13 @@ class Request
|
||||
protected $method;
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $rewriteRoute;
|
||||
protected $rewriteUrl;
|
||||
|
||||
/**
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $loadedRoute;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->parseHeaders();
|
||||
$this->host = $this->getHeader('http-host');
|
||||
$this->uri = $this->getHeader('request-uri');
|
||||
$this->input = new Input($this);
|
||||
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'), 'post'));
|
||||
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method')));
|
||||
}
|
||||
|
||||
protected function parseHeaders()
|
||||
@@ -125,17 +111,6 @@ class Request
|
||||
return $this->getHeader('remote-addr');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get remote address/ip
|
||||
*
|
||||
* @alias static::getIp
|
||||
* @return string
|
||||
*/
|
||||
public function getRemoteAddr()
|
||||
{
|
||||
return $this->getIp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get referer
|
||||
* @return string
|
||||
@@ -238,103 +213,6 @@ class Request
|
||||
$this->method = $method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite route
|
||||
*
|
||||
* @param ILoadableRoute $route
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteRoute(ILoadableRoute $route)
|
||||
{
|
||||
$this->rewriteRoute = $route;
|
||||
|
||||
$callback = $route->getCallback();
|
||||
|
||||
/* Only add default namespace on relative callbacks */
|
||||
if ($callback === null || $callback[0] !== '\\') {
|
||||
|
||||
$namespace = SimpleRouter::getDefaultNamespace();
|
||||
|
||||
if ($namespace !== null) {
|
||||
|
||||
if ($this->rewriteRoute->getNamespace() !== null) {
|
||||
$namespace .= '\\' . $this->rewriteRoute->getNamespace();
|
||||
}
|
||||
|
||||
$this->rewriteRoute->setDefaultNamespace($namespace);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rewrite route
|
||||
*
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getRewriteRoute()
|
||||
{
|
||||
return $this->rewriteRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rewrite url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRewriteUrl()
|
||||
{
|
||||
return $this->rewriteUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite url
|
||||
*
|
||||
* @param string $rewriteUrl
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteUrl($rewriteUrl)
|
||||
{
|
||||
$this->rewriteUrl = $rewriteUrl;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite callback
|
||||
* @param string $callback
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteCallback($callback)
|
||||
{
|
||||
return $this->setRewriteRoute(new RouteUrl($this->uri, $callback));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get loaded route
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getLoadedRoute()
|
||||
{
|
||||
return $this->loadedRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set loaded route
|
||||
*
|
||||
* @param ILoadableRoute $route
|
||||
* @return static
|
||||
*/
|
||||
public function setLoadedRoute(ILoadableRoute $route)
|
||||
{
|
||||
$this->loadedRoute = $route;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function __isset($name)
|
||||
{
|
||||
return array_key_exists($name, $this->data);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Response
|
||||
@@ -82,14 +83,20 @@ class Response
|
||||
}
|
||||
|
||||
/**
|
||||
* Json encode array
|
||||
* @param array $value
|
||||
* Json encode
|
||||
* @param array|\JsonSerializable $value
|
||||
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
|
||||
* @param int $dept JSON debt.
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function json(array $value)
|
||||
public function json($value, $options = null, $dept = 512)
|
||||
{
|
||||
$this->header('Content-Type: application/json');
|
||||
echo json_encode($value);
|
||||
die();
|
||||
if (($value instanceof \JsonSerializable) === false && is_array($value) === false) {
|
||||
throw new \InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
|
||||
}
|
||||
$this->header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($value, $options, $dept);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,5 +3,4 @@ namespace Pecee\SimpleRouter\Exceptions;
|
||||
|
||||
class NotFoundHttpException extends HttpException
|
||||
{
|
||||
|
||||
}
|
||||
@@ -20,8 +20,9 @@ interface ILoadableRoute extends IRoute
|
||||
* Loads and renders middlewares-classes
|
||||
*
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
*/
|
||||
public function loadMiddleware(Request $request);
|
||||
public function loadMiddleware(Request $request, ILoadableRoute $route);
|
||||
|
||||
public function getUrl();
|
||||
|
||||
|
||||
@@ -8,11 +8,10 @@ interface IRoute
|
||||
/**
|
||||
* Method called to check if a domain matches
|
||||
*
|
||||
* @param string $route
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
public function matchRoute($route, Request $request);
|
||||
public function matchRoute(Request $request);
|
||||
|
||||
/**
|
||||
* Called when route is matched.
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
@@ -24,13 +23,14 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
* Loads and renders middlewares-classes
|
||||
*
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
* @throws HttpException
|
||||
*/
|
||||
public function loadMiddleware(Request $request)
|
||||
public function loadMiddleware(Request $request, ILoadableRoute $route)
|
||||
{
|
||||
$max = count($this->getMiddlewares());
|
||||
if (count($this->getMiddlewares()) > 0) {
|
||||
|
||||
if ($max > 0) {
|
||||
$max = count($this->getMiddlewares());
|
||||
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
|
||||
@@ -38,24 +38,35 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
$middleware = $this->loadClass($middleware);
|
||||
|
||||
if (($middleware instanceof IMiddleware) === false) {
|
||||
if (!($middleware instanceof IMiddleware)) {
|
||||
throw new HttpException($middleware . ' must be instance of Middleware');
|
||||
}
|
||||
|
||||
$middleware->handle($request);
|
||||
$middleware->handle($request, $route);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function matchRegex(Request $request, $url)
|
||||
{
|
||||
|
||||
/* Match on custom defined regular expression */
|
||||
|
||||
if ($this->regex === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (preg_match($this->regex, $request->getHost() . $url) > 0);
|
||||
$parameters = [];
|
||||
|
||||
if (preg_match($this->regex, $request->getHost() . $url, $parameters) > 0) {
|
||||
|
||||
/* Remove global match */
|
||||
$this->parameters = array_slice($parameters, 1);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,9 +81,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
if (strpos($this->url, $this->paramModifiers[0]) !== false) {
|
||||
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
if (preg_match_all('/' . $regex . '/', $this->url, $matches)) {
|
||||
if (preg_match_all('/' . $regex . '/is', $this->url, $matches)) {
|
||||
$this->parameters = array_fill_keys($matches[1], null);
|
||||
}
|
||||
}
|
||||
@@ -136,6 +147,8 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
$url .= join('/', $unknownParams);
|
||||
|
||||
|
||||
|
||||
return rtrim($url, '/') . '/';
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -7,8 +6,7 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
abstract class Route implements IRoute
|
||||
{
|
||||
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
|
||||
const PARAMETERS_DEFAULT_REGEX = '[\w]+';
|
||||
const PARAMETERS_REGEX_MATCH = '%s([\w]+)(\%s?)%s';
|
||||
|
||||
const REQUEST_TYPE_GET = 'get';
|
||||
const REQUEST_TYPE_POST = 'post';
|
||||
@@ -33,7 +31,6 @@ abstract class Route implements IRoute
|
||||
* @var bool
|
||||
*/
|
||||
protected $filterEmptyParams = false;
|
||||
protected $defaultParameterRegex = null;
|
||||
protected $paramModifiers = '{}';
|
||||
protected $paramOptionalSymbol = '?';
|
||||
protected $group;
|
||||
@@ -60,21 +57,16 @@ abstract class Route implements IRoute
|
||||
|
||||
public function renderRoute(Request $request)
|
||||
{
|
||||
$callback = $this->getCallback();
|
||||
|
||||
if ($callback !== null && is_callable($callback)) {
|
||||
if ($this->getCallback() !== null && is_callable($this->getCallback())) {
|
||||
|
||||
/* When the callback is a function */
|
||||
call_user_func_array($callback, $this->getParameters());
|
||||
call_user_func_array($this->getCallback(), $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];
|
||||
$controller = explode('@', $this->getCallback());
|
||||
$className = $this->getNamespace() . '\\' . $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $controller[1];
|
||||
@@ -97,37 +89,22 @@ abstract class Route implements IRoute
|
||||
}
|
||||
}
|
||||
|
||||
protected function parseParameters($route, $url, $parameterRegex = null)
|
||||
protected function parseParameters($route, $url, $parameterRegex = '[\w]+')
|
||||
{
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
$parameters = [];
|
||||
if (preg_match_all('/' . $regex . '/is', $route, $parameters)) {
|
||||
|
||||
if (preg_match_all('/' . $regex . '/', $route, $parameters)) {
|
||||
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', rtrim($route, '/'));
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/is', rtrim($route, '/'));
|
||||
|
||||
foreach ($urlParts as $key => $t) {
|
||||
|
||||
$regex = '';
|
||||
|
||||
if ($key < count($parameters[1])) {
|
||||
if ($key < (count($parameters[1]))) {
|
||||
|
||||
$name = $parameters[1][$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 = isset($this->where[$name]) ? $this->where[$name] : $parameterRegex;
|
||||
$regex = sprintf('\-?\/?(?P<%s>%s)', $name, $regex) . $parameters[2][$key];
|
||||
|
||||
}
|
||||
@@ -141,16 +118,13 @@ abstract class Route implements IRoute
|
||||
$urlRegex = preg_quote($route, '/');
|
||||
}
|
||||
|
||||
if (preg_match('/^' . $urlRegex . '(\/?)$/', $url, $matches) > 0) {
|
||||
if (preg_match('/^' . $urlRegex . '(\/?)$/is', $url, $matches) > 0) {
|
||||
|
||||
$values = [];
|
||||
|
||||
if (isset($parameters[1]) === true) {
|
||||
|
||||
/* Only take matched parameters with name */
|
||||
foreach ($parameters[1] as $name) {
|
||||
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
|
||||
}
|
||||
/* Only take matched parameters with name */
|
||||
foreach ($parameters[1] as $name) {
|
||||
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
|
||||
}
|
||||
|
||||
return $values;
|
||||
@@ -359,10 +333,6 @@ abstract class Route implements IRoute
|
||||
$values['middleware'] = $this->middlewares;
|
||||
}
|
||||
|
||||
if ($this->defaultParameterRegex !== null) {
|
||||
$values['defaultParameterRegex'] = $this->defaultParameterRegex;
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
@@ -396,10 +366,6 @@ abstract class Route implements IRoute
|
||||
$this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares));
|
||||
}
|
||||
|
||||
if (isset($values['defaultParameterRegex'])) {
|
||||
$this->setDefaultParameterRegex($values['defaultParameterRegex']);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -511,28 +477,4 @@ 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
foreach (static::$requestTypes as $requestType) {
|
||||
|
||||
if (stripos($method, $requestType) === 0) {
|
||||
$method = (string)substr($method, strlen($requestType));
|
||||
$method = substr($method, strlen($requestType));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -83,32 +83,34 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
return '/' . trim($url, '/') . '/';
|
||||
}
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
public function matchRoute(Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = parse_url(urldecode($request->getUri()), 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))) {
|
||||
return false;
|
||||
if ($this->matchRegex($request, $url) === true) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
|
||||
$path = explode('/', $strippedUrl);
|
||||
if (stripos($url, $this->url) === 0 && strtolower($url) === strtolower($this->url)) {
|
||||
|
||||
if (count($path) > 0) {
|
||||
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
|
||||
|
||||
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
|
||||
$this->method = $request->getMethod() . ucfirst($method);
|
||||
$path = explode('/', $strippedUrl);
|
||||
|
||||
$this->parameters = array_slice($path, 1);
|
||||
if (count($path) > 0) {
|
||||
|
||||
// Set callback
|
||||
$this->setCallback($this->controller . '@' . $this->method);
|
||||
$method = (!isset($path[0]) || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
|
||||
$this->method = $method;
|
||||
|
||||
return true;
|
||||
$this->parameters = array_slice($path, 1);
|
||||
|
||||
// Set callback
|
||||
$this->setCallback($this->controller . '@' . $this->method);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
@@ -40,14 +40,13 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
/**
|
||||
* Method called to check if route matches
|
||||
*
|
||||
* @param string $url
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
public function matchRoute($url, Request $request)
|
||||
public function matchRoute(Request $request)
|
||||
{
|
||||
/* Skip if prefix doesn't match */
|
||||
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
|
||||
if ($this->prefix !== null && stripos($request->getUri(), $this->prefix) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -54,7 +53,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
/* Remove method/type */
|
||||
if (strpos($name, '.') !== false) {
|
||||
$name = (string)substr($name, 0, strrpos($name, '.'));
|
||||
$name = substr($name, 0, strrpos($name, '.'));
|
||||
}
|
||||
|
||||
return (strtolower($this->name) === strtolower($name));
|
||||
@@ -62,9 +61,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
public function findUrl($method = null, $parameters = null, $name = null)
|
||||
{
|
||||
$url = array_search($name, $this->names, false);
|
||||
if ($url !== false) {
|
||||
return rtrim($this->url . $this->urls[$url], '/') . '/';
|
||||
$method = array_search($name, $this->names, false);
|
||||
if ($method !== false) {
|
||||
return rtrim($this->url . $this->urls[$method], '/') . '/';
|
||||
}
|
||||
|
||||
return $this->url;
|
||||
@@ -77,53 +76,48 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
return true;
|
||||
}
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
public function matchRoute(Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = parse_url(urldecode($request->getUri()), 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))) {
|
||||
return false;
|
||||
$domainMatch = $this->matchRegex($request, $url);
|
||||
if ($domainMatch !== null) {
|
||||
return $domainMatch;
|
||||
}
|
||||
|
||||
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
|
||||
|
||||
/* 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) {
|
||||
$parameters = $this->parseParameters($route, $url);
|
||||
if ($parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$action = strtolower(trim($this->parameters['action']));
|
||||
$id = $this->parameters['id'];
|
||||
$this->parameters = (array)$parameters;
|
||||
|
||||
// Remove action parameter
|
||||
$action = isset($this->parameters['action']) ? $this->parameters['action'] : null;
|
||||
unset($this->parameters['action']);
|
||||
|
||||
$method = $request->getMethod();
|
||||
|
||||
// Delete
|
||||
if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
|
||||
if ($method === static::REQUEST_TYPE_DELETE && isset($this->parameters['id'])) {
|
||||
return $this->call($this->methodNames['destroy']);
|
||||
}
|
||||
|
||||
// Update
|
||||
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
|
||||
if (isset($this->parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false)) {
|
||||
return $this->call($this->methodNames['update']);
|
||||
}
|
||||
|
||||
// Edit
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id']) && strtolower($action) === 'edit') {
|
||||
return $this->call($this->methodNames['edit']);
|
||||
}
|
||||
|
||||
// Create
|
||||
if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
|
||||
if ($method === static::REQUEST_TYPE_GET && strtolower($action) === 'create') {
|
||||
return $this->call($this->methodNames['create']);
|
||||
}
|
||||
|
||||
@@ -133,7 +127,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
}
|
||||
|
||||
// Show
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null) {
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id'])) {
|
||||
return $this->call($this->methodNames['show']);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -12,30 +11,27 @@ class RouteUrl extends LoadableRoute
|
||||
$this->setCallback($callback);
|
||||
}
|
||||
|
||||
public function matchRoute($url, Request $request)
|
||||
public function matchRoute(Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($url), PHP_URL_PATH);
|
||||
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false) {
|
||||
return false;
|
||||
$domainMatch = $this->matchRegex($request, $url);
|
||||
if ($domainMatch !== null) {
|
||||
return $domainMatch;
|
||||
}
|
||||
|
||||
/* Parse parameters from current route */
|
||||
/* Make regular expression based on route */
|
||||
$parameters = $this->parseParameters($this->url, $url);
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($regexMatch === null && $parameters === null) {
|
||||
if ($parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Set the parameters */
|
||||
$this->setParameters((array)$parameters);
|
||||
$this->setParameters($parameters);
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -69,7 +69,38 @@ class Router
|
||||
*/
|
||||
protected $exceptionHandlers;
|
||||
|
||||
public function __construct()
|
||||
/**
|
||||
* The current loaded route
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $loadedRoute;
|
||||
|
||||
/**
|
||||
* List over route changes (to avoid endless-looping)
|
||||
* @var array
|
||||
*/
|
||||
protected $routeRewrites = [];
|
||||
|
||||
/**
|
||||
* If the route has been rewritten/changed this property will contain the original url.
|
||||
* @var string
|
||||
*/
|
||||
protected $originalUrl;
|
||||
|
||||
/**
|
||||
* Get current router instance
|
||||
* @return static
|
||||
*/
|
||||
public static function getInstance()
|
||||
{
|
||||
if (static::$instance === null) {
|
||||
static::$instance = new static();
|
||||
}
|
||||
|
||||
return static::$instance;
|
||||
}
|
||||
|
||||
protected function __construct()
|
||||
{
|
||||
$this->reset();
|
||||
}
|
||||
@@ -112,7 +143,6 @@ class Router
|
||||
* @param array $routes
|
||||
* @param IGroupRoute|null $group
|
||||
* @param IRoute|null $parent
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null)
|
||||
{
|
||||
@@ -121,8 +151,6 @@ class Router
|
||||
|
||||
$exceptionHandlers = [];
|
||||
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
|
||||
/* @var $route IRoute */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
@@ -139,7 +167,7 @@ class Router
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
if ($route->matchRoute($this->request) === true) {
|
||||
|
||||
/* Add exception handlers */
|
||||
if (count($route->getExceptionHandlers()) > 0) {
|
||||
@@ -174,7 +202,7 @@ class Router
|
||||
|
||||
if (count($this->routeStack) > 0) {
|
||||
|
||||
/* Pop and grab the routes added when executing group callback earlier */
|
||||
/* Pop and grap the routes added when executing group callback earlier */
|
||||
$stack = $this->routeStack;
|
||||
$this->routeStack = [];
|
||||
|
||||
@@ -186,56 +214,53 @@ class Router
|
||||
$this->exceptionHandlers = array_unique(array_merge($exceptionHandlers, $this->exceptionHandlers));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load routes
|
||||
* @throws NotFoundHttpException
|
||||
* @return void
|
||||
*/
|
||||
public function loadRoutes()
|
||||
{
|
||||
/* Initialize boot-managers */
|
||||
if (count($this->bootManagers) > 0) {
|
||||
|
||||
$max = count($this->bootManagers) - 1;
|
||||
|
||||
/* @var $manager IRouterBootManager */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$manager = $this->bootManagers[$i];
|
||||
$manager->boot($this->request);
|
||||
}
|
||||
}
|
||||
|
||||
/* Loop through each route-request */
|
||||
$this->processRoutes($this->routes);
|
||||
}
|
||||
|
||||
public function routeRequest($rewrite = false)
|
||||
{
|
||||
$this->loadedRoute = null;
|
||||
$routeNotAllowed = false;
|
||||
|
||||
try {
|
||||
/* Initialize boot-managers */
|
||||
if (count($this->bootManagers) > 0) {
|
||||
|
||||
$max = count($this->bootManagers) - 1;
|
||||
|
||||
/* @var $manager IRouterBootManager */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$manager = $this->bootManagers[$i];
|
||||
|
||||
$this->request = $manager->boot($this->request);
|
||||
|
||||
if (!($this->request instanceof Request)) {
|
||||
throw new HttpException('Bootmanager "' . get_class($manager) . '" must return instance of ' . Request::class, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($rewrite === false) {
|
||||
$this->loadRoutes();
|
||||
|
||||
/* Loop through each route-request */
|
||||
$this->processRoutes($this->routes);
|
||||
|
||||
if ($this->csrfVerifier !== null) {
|
||||
|
||||
/* Verify csrf token for request */
|
||||
$this->csrfVerifier->handle($this->request);
|
||||
}
|
||||
}
|
||||
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
$this->originalUrl = $this->request->getUri();
|
||||
}
|
||||
|
||||
$max = count($this->processedRoutes) - 1;
|
||||
|
||||
/* @var $route ILoadableRoute */
|
||||
/* @var $route IRoute */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$route = $this->processedRoutes[$i];
|
||||
|
||||
/* If the route matches */
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
if ($route->matchRoute($this->request) === true) {
|
||||
|
||||
/* Check if request method matches */
|
||||
if (count($route->getRequestMethods()) > 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
|
||||
@@ -243,23 +268,12 @@ class Router
|
||||
continue;
|
||||
}
|
||||
|
||||
$route->loadMiddleware($this->request);
|
||||
$this->loadedRoute = $route;
|
||||
$this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute);
|
||||
|
||||
$rewriteRoute = $this->request->getRewriteRoute();
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/* If the request has changed */
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
|
||||
unset($this->processedRoutes[$i]);
|
||||
$this->processedRoutes = array_values($this->processedRoutes);
|
||||
/* If the request has changed, we reinitialize the router */
|
||||
if ($this->request->getUri() !== $this->originalUrl && in_array($this->request->getUri(), $this->routeRewrites) === false) {
|
||||
$this->routeRewrites[] = $this->request->getUri();
|
||||
$this->routeRequest(true);
|
||||
|
||||
return;
|
||||
@@ -267,8 +281,8 @@ class Router
|
||||
|
||||
/* Render route */
|
||||
$routeNotAllowed = false;
|
||||
$this->request->setLoadedRoute($route);
|
||||
$route->renderRoute($this->request);
|
||||
$this->request->setUri($this->originalUrl);
|
||||
$this->loadedRoute->renderRoute($this->request);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -282,48 +296,35 @@ class Router
|
||||
$this->handleException(new HttpException('Route or method not allowed', 403));
|
||||
}
|
||||
|
||||
if ($this->request->getLoadedRoute() === null) {
|
||||
if ($this->loadedRoute === null) {
|
||||
$this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404));
|
||||
}
|
||||
}
|
||||
|
||||
protected function handleException(\Exception $e)
|
||||
{
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri();
|
||||
|
||||
$max = count($this->exceptionHandlers);
|
||||
|
||||
/* @var $handler IExceptionHandler */
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
|
||||
$handler = $this->exceptionHandlers[$i];
|
||||
|
||||
$handler = new $handler();
|
||||
|
||||
if (($handler instanceof IExceptionHandler) === false) {
|
||||
if (!($handler instanceof IExceptionHandler)) {
|
||||
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
|
||||
}
|
||||
|
||||
if ($handler->handleError($this->request, $e) !== null) {
|
||||
$request = $handler->handleError($this->request, $this->loadedRoute, $e);
|
||||
|
||||
$rewriteRoute = $this->request->getRewriteRoute();
|
||||
/* If the request has changed */
|
||||
if ($request !== null && $this->request->getUri() !== $this->originalUrl && in_array($request->getUri(), $this->routeRewrites) === false) {
|
||||
$this->request = $request;
|
||||
$this->routeRewrites[] = $request->getUri();
|
||||
$this->routeRequest(true);
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
$rewriteRoute->renderRoute($this->request);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
/* If the request has changed */
|
||||
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
|
||||
unset($this->exceptionHandlers[$i]);
|
||||
$this->exceptionHandlers = array_values($this->exceptionHandlers);
|
||||
$this->routeRequest(true);
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,7 +337,7 @@ class Router
|
||||
|
||||
if ($includeEmpty === false) {
|
||||
$getParams = array_filter($getParams, function ($item) {
|
||||
return (trim($item) !== '');
|
||||
return (!empty($item));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -436,11 +437,9 @@ class Router
|
||||
return (($url === '') ? '/' : $url . '/') . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
$loadedRoute = $this->request->getLoadedRoute();
|
||||
|
||||
/* If nothing is defined and a route is loaded we use that */
|
||||
if ($name === null && $loadedRoute !== null) {
|
||||
return $loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
|
||||
if ($name === null && $this->loadedRoute !== null) {
|
||||
return $this->loadedRoute->findUrl($this->loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
/* We try to find a match on the given name */
|
||||
@@ -549,4 +548,13 @@ class Router
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get loaded route
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getLoadedRoute()
|
||||
{
|
||||
return $this->loadedRoute;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -33,12 +33,6 @@ class SimpleRouter
|
||||
*/
|
||||
protected static $response;
|
||||
|
||||
/**
|
||||
* Router instance
|
||||
* @var Router
|
||||
*/
|
||||
protected static $router;
|
||||
|
||||
/**
|
||||
* Start/route request
|
||||
*
|
||||
@@ -218,7 +212,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl|IRoute
|
||||
* @return RouteUrl
|
||||
*/
|
||||
public static function match(array $requestMethods, $url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -241,7 +235,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl|IRoute
|
||||
* @return RouteUrl
|
||||
*/
|
||||
public static function all($url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -263,7 +257,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteController|IRoute
|
||||
* @return RouteController
|
||||
*/
|
||||
public static function controller($url, $controller, array $settings = null)
|
||||
{
|
||||
@@ -285,12 +279,11 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteResource|IRoute
|
||||
* @return RouteResource
|
||||
*/
|
||||
public static function resource($url, $controller, array $settings = null)
|
||||
{
|
||||
$route = new RouteResource($url, $controller);
|
||||
$route = static::addDefaultNamespace($route);
|
||||
|
||||
if ($settings !== null) {
|
||||
$route->setSettings($settings);
|
||||
@@ -355,11 +348,7 @@ class SimpleRouter
|
||||
*/
|
||||
public static function router()
|
||||
{
|
||||
if(static::$router === null) {
|
||||
static::$router = new Router();
|
||||
}
|
||||
|
||||
return static::$router;
|
||||
return Router::getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -371,35 +360,16 @@ class SimpleRouter
|
||||
protected static function addDefaultNamespace(IRoute $route)
|
||||
{
|
||||
if (static::$defaultNamespace !== null) {
|
||||
$namespace = static::$defaultNamespace;
|
||||
|
||||
$callback = $route->getCallback();
|
||||
|
||||
/* Only add default namespace on relative callbacks */
|
||||
if ($callback === null || $callback[0] !== '\\') {
|
||||
|
||||
$namespace = static::$defaultNamespace;
|
||||
|
||||
$currentNamespace = $route->getNamespace();
|
||||
|
||||
if ($currentNamespace !== null) {
|
||||
$namespace .= '\\' . $currentNamespace;
|
||||
}
|
||||
|
||||
$route->setDefaultNamespace($namespace);
|
||||
|
||||
if ($route->getNamespace() !== null) {
|
||||
$namespace .= '\\' . $route->getNamespace();
|
||||
}
|
||||
|
||||
$route->setDefaultNamespace($namespace);
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default namespace
|
||||
* @return string
|
||||
*/
|
||||
public static function getDefaultNamespace()
|
||||
{
|
||||
return static::$defaultNamespace;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,34 +2,24 @@
|
||||
|
||||
class DummyController
|
||||
{
|
||||
public function method1()
|
||||
public function start()
|
||||
{
|
||||
|
||||
echo static::class . '@' . 'start() OK';
|
||||
}
|
||||
|
||||
public function method2()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public function param($params = null)
|
||||
{
|
||||
echo join(', ', func_get_args());
|
||||
$params = func_get_args();
|
||||
echo 'Params: ' . join(', ', $params);
|
||||
}
|
||||
|
||||
public function getTest()
|
||||
{
|
||||
echo 'getTest';
|
||||
}
|
||||
public function notFound()
|
||||
{
|
||||
echo 'not found';
|
||||
}
|
||||
|
||||
public function postTest()
|
||||
{
|
||||
echo 'postTest';
|
||||
}
|
||||
public function silent() {
|
||||
|
||||
public function putTest()
|
||||
{
|
||||
echo 'putTest';
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
<?php
|
||||
require_once 'Exceptions/MiddlewareLoadedException.php';
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
|
||||
class DummyMiddleware implements IMiddleware
|
||||
{
|
||||
public function handle(Request $request)
|
||||
public function handle(Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route)
|
||||
{
|
||||
throw new MiddlewareLoadedException('Middleware loaded!');
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
class ResponseException extends \Exception
|
||||
{
|
||||
protected $response;
|
||||
|
||||
public function __construct($response)
|
||||
{
|
||||
$this->response = $response;
|
||||
parent::__construct('', 0);
|
||||
}
|
||||
|
||||
public function getResponse()
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo $error->getMessage();
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?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');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 1 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 2 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 3 loaded' . chr(10);
|
||||
|
||||
throw new ExceptionHandlerException('All good!', 666);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
<?php
|
||||
class ResourceController implements \Pecee\Controllers\IResourceController
|
||||
{
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'index';
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
echo 'show ' . $id;
|
||||
}
|
||||
|
||||
public function store()
|
||||
{
|
||||
echo 'store';
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
echo 'create';
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
echo 'edit ' . $id;
|
||||
}
|
||||
|
||||
public function update($id)
|
||||
{
|
||||
echo 'update ' . $id;
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
echo 'destroy ' . $id;
|
||||
}
|
||||
}
|
||||
+38
-26
@@ -2,7 +2,8 @@
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
|
||||
class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -12,71 +13,82 @@ class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
$this->result = false;
|
||||
|
||||
TestRouter::group(['prefix' => '/group'], function () {
|
||||
SimpleRouter::group(['prefix' => '/group'], function () {
|
||||
$this->result = true;
|
||||
});
|
||||
|
||||
try {
|
||||
TestRouter::debug('/', 'get');
|
||||
} catch(\Exception $e) {
|
||||
|
||||
SimpleRouter::start();
|
||||
} catch (Exception $e) {
|
||||
// ignore RouteNotFound exception
|
||||
}
|
||||
|
||||
$this->assertTrue($this->result);
|
||||
}
|
||||
|
||||
public function testNestedGroup()
|
||||
{
|
||||
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/api/v1/test');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
TestRouter::debug('/api/v1/test', 'get');
|
||||
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testMultipleRoutes()
|
||||
public function testManyRoutes()
|
||||
{
|
||||
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/match');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
TestRouter::get('/my/match', 'DummyController@method1');
|
||||
SimpleRouter::get('/my/match', 'DummyController@start');
|
||||
|
||||
TestRouter::group(['prefix' => '/service'], function () {
|
||||
SimpleRouter::group(['prefix' => '/service'], function () {
|
||||
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/no-match', 'DummyController@method1');
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/no-match', 'DummyController@start');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
TestRouter::debug('/my/match', 'get');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/fancy/url/1');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
// Test array name
|
||||
TestRouter::get('/my/fancy/url/1', 'DummyController@method1', ['as' => 'fancy1']);
|
||||
SimpleRouter::get('/my/fancy/url/1', 'DummyController@start', ['as' => 'fancy1']);
|
||||
|
||||
// Test method name
|
||||
TestRouter::get('/my/fancy/url/2', 'DummyController@method1')->setName('fancy2');
|
||||
SimpleRouter::get('/my/fancy/url/2', 'DummyController@start')->setName('fancy2');
|
||||
|
||||
TestRouter::debugNoReset('/my/fancy/url/1');
|
||||
SimpleRouter::start();
|
||||
|
||||
$this->assertEquals('/my/fancy/url/1/', TestRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', TestRouter::getUrl('fancy2'));
|
||||
|
||||
TestRouter::router()->reset();
|
||||
$this->assertEquals('/my/fancy/url/1/', SimpleRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', SimpleRouter::getUrl('fancy2'));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
|
||||
{
|
||||
|
||||
public static function debugNoReset($testUri, $testMethod = 'get')
|
||||
{
|
||||
static::request()->setUri($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;
|
||||
}
|
||||
|
||||
}
|
||||
+19
-12
@@ -3,32 +3,39 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
|
||||
class MiddlewareTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testMiddlewareFound()
|
||||
{
|
||||
$this->setExpectedException(MiddlewareLoadedException::class);
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
|
||||
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::debug('/my/test/url', 'get');
|
||||
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testNestedMiddlewareDontLoad()
|
||||
public function testNestedMiddlewareLoad()
|
||||
{
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
|
||||
TestRouter::get('/middleware', 'DummyController@method1');
|
||||
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::get('/my/test/url', 'DummyController@method1');
|
||||
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
<?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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
<?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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
<?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);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+97
-72
@@ -3,7 +3,12 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
|
||||
require_once 'Helpers/TestRouter.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;
|
||||
|
||||
class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -11,57 +16,113 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testMultiParam()
|
||||
{
|
||||
TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1-param2');
|
||||
|
||||
if ($param1 === 'param1' && $param2 === 'param2') {
|
||||
SimpleRouter::get('/test-{param1}-{param2}', function($param1, $param2) {
|
||||
|
||||
if($param1 === 'param1' && $param2 === 'param2') {
|
||||
$this->result = true;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
TestRouter::debug('/test-param1-param2', 'get');
|
||||
SimpleRouter::start();
|
||||
|
||||
$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('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
|
||||
TestRouter::get('/non-existing-path', 'DummyController@method1');
|
||||
TestRouter::debug('/test-param1-param2', 'post');
|
||||
$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();
|
||||
}
|
||||
|
||||
public function testGet()
|
||||
{
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testPost()
|
||||
{
|
||||
TestRouter::post('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::post('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testPut()
|
||||
{
|
||||
TestRouter::put('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'put');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('put');
|
||||
|
||||
SimpleRouter::put('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testDelete()
|
||||
{
|
||||
TestRouter::delete('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'delete');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('delete');
|
||||
|
||||
SimpleRouter::delete('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testMethodNotAllowed()
|
||||
{
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
|
||||
try {
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
SimpleRouter::start();
|
||||
} catch (\Exception $e) {
|
||||
$this->assertEquals(403, $e->getCode());
|
||||
}
|
||||
@@ -69,79 +130,43 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testSimpleParam()
|
||||
{
|
||||
TestRouter::get('/test-{param1}', 'DummyController@param');
|
||||
$response = TestRouter::debugOutput('/test-param1', 'get');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1');
|
||||
|
||||
$this->assertEquals('param1', $response);
|
||||
SimpleRouter::get('/test-{param1}', 'DummyController@param');
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testPathParamRegex()
|
||||
{
|
||||
TestRouter::get('/{lang}/productscategories/{name}', 'DummyController@param', ['where' => ['lang' => '[a-z]+', 'name' => '[A-Za-z0-9\-]+']]);
|
||||
$response = TestRouter::debugOutput('/it/productscategories/system', 'get');
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test/path/123123');
|
||||
|
||||
$this->assertEquals('it, system', $response);
|
||||
SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
|
||||
SimpleRouter::start();
|
||||
}
|
||||
|
||||
public function testDomainAllowedRoute()
|
||||
public function testDomainRoute()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test');
|
||||
SimpleRouter::request()->setHost('hello.world.com');
|
||||
|
||||
$this->result = false;
|
||||
|
||||
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
TestRouter::get('/test', function ($subdomain = null) {
|
||||
SimpleRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
SimpleRouter::get('/test', function ($subdomain = null) {
|
||||
$this->result = ($subdomain === 'hello');
|
||||
});
|
||||
});
|
||||
|
||||
TestRouter::request()->setHost('hello.world.com');
|
||||
TestRouter::debug('/test', 'get');
|
||||
SimpleRouter::start();
|
||||
|
||||
$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);
|
||||
}
|
||||
|
||||
}
|
||||
+46
-38
@@ -3,103 +3,111 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
|
||||
class RouterUrlTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
protected $result = false;
|
||||
|
||||
public function testSimularUrls()
|
||||
protected function getUrl($name = null, $parameters = null, array $getParams = [])
|
||||
{
|
||||
// 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();
|
||||
return SimpleRouter::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/');
|
||||
|
||||
// Match normal route on alias
|
||||
TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
|
||||
SimpleRouter::get('/', 'DummyController@silent', ['as' => 'home']);
|
||||
|
||||
TestRouter::get('/about', 'DummyController@about');
|
||||
SimpleRouter::get('/about', 'DummyController@about');
|
||||
|
||||
TestRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
SimpleRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
|
||||
// Match route with prefix on alias
|
||||
TestRouter::get('/{id?}', 'DummyController@method2', ['as' => 'home']);
|
||||
SimpleRouter::get('/{id?}', 'DummyController@start', ['as' => 'home']);
|
||||
|
||||
// Match controller with prefix and alias
|
||||
TestRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
SimpleRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
|
||||
// Match controller with prefix and NO alias
|
||||
TestRouter::controller('/pages', 'DummyController');
|
||||
SimpleRouter::controller('/pages', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
TestRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
SimpleRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
|
||||
// Match resource controller
|
||||
TestRouter::resource('phones', 'DummyController');
|
||||
SimpleRouter::resource('phones', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
TestRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
SimpleRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
|
||||
// Match controller with no prefix and no alias
|
||||
TestRouter::controller('/cats', 'CatsController');
|
||||
SimpleRouter::controller('/cats', 'CatsController');
|
||||
|
||||
// Pretend to load page
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
SimpleRouter::start();
|
||||
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', TestRouter::getUrl('gadgets.iphone'));
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', $this->getUrl('gadgets.iphone'));
|
||||
|
||||
$this->assertEquals('/api/phones/create/', TestRouter::getUrl('api.phones.create'));
|
||||
$this->assertEquals('/api/phones/create/', $this->getUrl('api.phones.create'));
|
||||
|
||||
// Should match /
|
||||
$this->assertEquals('/', TestRouter::getUrl('home'));
|
||||
$this->assertEquals('/', $this->getUrl('home'));
|
||||
|
||||
// Should match /about/
|
||||
$this->assertEquals('/about/', TestRouter::getUrl('DummyController@about'));
|
||||
$this->assertEquals('/about/', $this->getUrl('DummyController@about'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('DummyController@method2'));
|
||||
$this->assertEquals('/admin/', $this->getUrl('DummyController@start'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('admin.home'));
|
||||
$this->assertEquals('/admin/', $this->getUrl('admin.home'));
|
||||
|
||||
// Should match /admin/2/
|
||||
$this->assertEquals('/admin/2/', TestRouter::getUrl('admin.home', ['id' => 2]));
|
||||
$this->assertEquals('/admin/2/', $this->getUrl('admin.home', ['id' => 2]));
|
||||
|
||||
// Should match /admin/users/
|
||||
$this->assertEquals('/admin/users/', TestRouter::getUrl('admin.users'));
|
||||
$this->assertEquals('/admin/users/', $this->getUrl('admin.users'));
|
||||
|
||||
// Should match /admin/users/home/
|
||||
$this->assertEquals('/admin/users/home/', TestRouter::getUrl('admin.users@home'));
|
||||
$this->assertEquals('/admin/users/home/', $this->getUrl('admin.users@home'));
|
||||
|
||||
// Should match /cats/
|
||||
$this->assertEquals('/cats/', TestRouter::getUrl('CatsController'));
|
||||
$this->assertEquals('/cats/', $this->getUrl('CatsController'));
|
||||
|
||||
// Should match /cats/view/
|
||||
$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', 'view'));
|
||||
$this->assertEquals('/cats/view/', $this->getUrl('CatsController', 'view'));
|
||||
|
||||
// Should match /cats/view/
|
||||
//$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', ['view']));
|
||||
//$this->assertEquals('/cats/view/', $this->getUrl('CatsController', ['view']));
|
||||
|
||||
// Should match /cats/view/666
|
||||
$this->assertEquals('/cats/view/666/', TestRouter::getUrl('CatsController@getView', ['666']));
|
||||
$this->assertEquals('/cats/view/666/', $this->getUrl('CatsController@getView', ['666']));
|
||||
|
||||
// Should match /funny/man/
|
||||
$this->assertEquals('/funny/man/', TestRouter::getUrl('/funny/man'));
|
||||
$this->assertEquals('/funny/man/', $this->getUrl('/funny/man'));
|
||||
|
||||
// Should match /?jackdaniels=true&cola=yeah
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', $this->getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user