Compare commits

...

37 Commits

Author SHA1 Message Date
Simon Sessingø 27ff761d18 Merge pull request #230 from skipperbent/v3-development
V3 development
2017-03-06 02:56:37 +01:00
Simon Sessingø 0a58d36606 Development
- Fixed: `RouteController` not matching certain urls.
- Made `RouteResource` more strict in url-matching.
- Added PHPUnit `RouterControllerTest` class.
- Fixed merged `testSimularUrls` method in `RouterUrlTest`.
2017-03-06 02:53:44 +01:00
Simon Sessingø db024b9588 Added simular routes PHPUnit test 2017-03-06 02:21:13 +01:00
Simon Sessingø 94d0764631 Merge pull request #228 from skipperbent/v3-development
Development
2017-03-05 17:10:27 +01:00
Simon Sessingø ff3f1bdcdd Development
- Fixed issue #227 causing custom resource-routes not to be loaded after latest update.
- Optimized `RouteResource` class.
- Renamed `IRestController` to `IResourceController`.
- Added unit-tests for RouterResource.
- Simplified unit-tests with the `TestRouter` custom router class.
2017-03-05 17:09:46 +01:00
Simon Sessingø 3e75d6ec0b Merge pull request #225 from skipperbent/v3-development
Development
2017-03-01 03:39:33 +01:00
Simon Sessingø 8c5d8c2dc9 Development
- Fixed: namespace being prepended on `RouterController` routes with absolute namespaces.
- Fixed: match domain on `RouteController` and `RouteResource`.
- Fixed: strict url-matching on `RouteController`. Fix should provide better url-matching.
- Fixed: `RouterResource` always matching first url when having simular urls (ex: `/funny-cat` and `/funny-dog`).
- Added `loadRoutes` method to `Router` class so routes now can be loaded without routing the request (useful when running in Cli etc).
- Removed `getInstance` from `Router` class. Please use `SimpleRouter::router()` for singleton usage instead.
- Added `getRemoteAddr` alias-method for `getIp` in `Request` class.
- Added `getValue` to `IInputItem` interface.
- Other minor optimizations.
- Updated documentation with note on absolute/relative namespaces.
2017-02-26 09:18:35 +01:00
Simon Sessingø 9d2bffcd02 Merge pull request #222 from skipperbent/v3-development
Development
2017-02-15 03:29:16 +01:00
Simon Sessingø 2a448fccd2 Development
- Fixed: only set default namespace on relative callbacks.
- Fixed: default-namespace not being set when calling `SimpleRouter::resource`.
- Minor optimisations.
2017-02-15 03:28:34 +01:00
Simon Sessingø e682cf0b7c Merge pull request #219 from skipperbent/v3-development
V3 development
2017-02-13 06:47:26 +01:00
Simon Sessingø c87298ee24 Optimisations 2017-02-13 06:45:07 +01:00
Simon Sessingø 79414255e0 Development
- Using `$request->setRewriteRoute($route);` rewrite-callback now renders any added middlewares on the route.
- Rewrite callbacks now sets default-namespace on route, if defined.
2017-02-13 06:29:22 +01:00
Simon Sessingø e913dd98da Merge pull request #217 from skipperbent/v3-development
Fixed: replace empty parameter-values with null.
2017-02-12 20:48:02 +01:00
Simon Sessingø ccd3cf450e Fixed: replace empty parameter-values with null. 2017-02-12 20:43:49 +01:00
Simon Sessingø 2654ca67db Merge pull request #214 from skipperbent/v3-development
Optimisations
2017-02-09 13:34:32 +01:00
Simon Sessingø 86c3e513c3 Optimisations 2017-02-09 13:33:36 +01:00
Simon Sessingø ce276bd5b7 Version 3
- Easier rewrite management.
- Optimisations.
- Updated documentation.
2017-02-09 13:18:05 +01:00
Simon Sessingø bf069c2d42 Fixed getExtension method in InputFile retuning empty value. 2017-02-01 07:51:35 +01:00
Simon Sessingø 523d49359b Development
- Fixed where method calling itself instead of setWhere.
- Added unit-tests for regex.
2017-01-19 18:40:47 +01:00
Simon Sessingø 7cc2652bcd getRoute optimisations. 2016-11-28 14:13:58 +01:00
Simon Sessingø e26d55a810 getUrl will now use default-parameter value if specificially set to null when using url(). 2016-11-28 09:37:05 +01:00
Simon Sessingø 8f3ce68a5e Optimised route-match behavior 2016-11-28 06:43:26 +01:00
Simon Sessingø d25351f4f9 Fixed parameters not merged with default values 2016-11-28 05:53:02 +01:00
Simon Sessingø e8f19fbeae Simplified PARAMETERS_REGEX_MATCH in Route class. 2016-11-28 05:24:12 +01:00
Simon Sessingø 5c89ae2aaf Moved regex/match functionality to LoadableRoute. 2016-11-28 04:45:46 +01:00
Simon Sessingø b694a7c0c9 More cleanup 2016-11-28 04:39:34 +01:00
Simon Sessingø 7847b71bbc Cleanup 2016-11-28 04:38:38 +01:00
Simon Sessingø d9b97ccf42 Bugfixes 2016-11-28 04:20:34 +01:00
Simon Sessingø 74351e0330 Bugfixes 2016-11-27 01:07:11 +01:00
Simon Sessingø f5b03e106c Bugfixes 2016-11-27 00:55:47 +01:00
Simon Sessingø 2c5221051e Development 2016-11-26 10:40:42 +01:00
Simon Sessingø aad11ac581 Input optimisations 2016-11-26 05:21:09 +01:00
Simon Sessingø c1835152b6 Removed PHP 7 specific functionality. 2016-11-26 04:53:05 +01:00
Simon Sessingø 6213f2fb75 Development
- Optimised Input-classes.
- `get` and `getObject` methods on `Input` now supports filtering on multiple method-types when using the `$method` parameter.
- Input classes now know how to parse that stupid nested $_FILES array.
- It's now possible to change method-names on ResourceControllers.
- Removed `getValue` and `setValue` from `InputFile` classes.
- Ensured that request-method are only parsed from $_POST or $_SERVER.
- Fixed minor parameter-issues with subdomain routing.
- Added PHPDocs.
- Added even more unit-tests.
- Many small optimisations tweaks.
2016-11-26 04:30:00 +01:00
Simon Sessingø 68fc6b76c0 Development
- It's now possible to adjust the load-order for parameters on routes.
- Replaced PHP 7.1 deprecated `mcrypt_create_iv` function with `random_bytes` if it is available (requires > PHP7)
- Added `setIndex`, `setName` and `setValue` methods to `IInputItem` to allow for extendability.
- Cleanup and bug fixes.
2016-11-25 18:26:50 +01:00
Simon Sessingø 1c515119b4 Development
- Ensure that request-method is always lowercase.
- Fixed spaces instead of tabs to comply with PSR-2.
2016-11-25 12:51:45 +01:00
Simon Sessingø 2dd2d95af5 Development
- Fixed BootManager not loading.
- Optimised for-loops.
2016-11-25 02:27:46 +01:00
45 changed files with 4245 additions and 3575 deletions
+260 -201
View File
@@ -15,71 +15,72 @@ If you want a great new feature or experience any issues what-so-ever, please fe
## Table of Contents
- Gettings started
- Requirements
- Notes
- Features
- Installation
- Setting up Apache
- Setting up Nginx
- Setting up simple-php-router
- Helper methods
- [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)
- 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
- [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)
- CSRF-protection
- Adding CSRF-verifier
- Getting CSRF-token
- [CSRF-protection](#csrf-protection)
- [Adding CSRF-verifier](#adding-csrf-verifier)
- [Getting CSRF-token](#getting-csrf-token)
- Middleware
- Example
- ExceptionHandler
- Example
- [Middlewares](#middlewares)
- [Example](#example)
- [ExceptionHandler](#exceptionhandler)
- [Example](#example-1)
- 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
- [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)
- Input & parameters
- Return single parameter value
- Return single parameter object
- Managing files
- Return all parameters
- [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)
- Advanced
- Bootmanager: loading routes dynamically
- Ovewrite route about to be loaded
- Examples
- Rewriting to new route
- Changing callback
- [Advanced](#advanced)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Url rewriting](#url-rewriting)
- [Rewrite using callback](#rewrite-using-callback)
- [Rewrite using url](#rewrite-using-url)
- Adding routes manually
- Extending
- [Adding routes manually](#adding-routes-manually)
- [Extending](#extending)
- Credits
- Sites
- License
- [Credits](#credits)
- [Sites](#sites)
- [License](#license)
___
@@ -92,8 +93,7 @@ composer require pecee/simple-router
## Requirements
- PHP 5.4 or greater
- mcrypt extension
- PHP 5.5 or greater
## Notes
@@ -155,7 +155,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.
### Setting up simple-php-router
### Configuration
Create a new file, name it `routes.php` and place it in your library folder. This will be the file where you define all the routes for your project.
@@ -193,8 +193,6 @@ 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.
*
@@ -212,41 +210,43 @@ use Pecee\SimpleRouter\SimpleRouter;
* @param array|null $getParams
* @return string
*/
function url($name = null, $parameters = null, $getParams = null) {
SimpleRouter::getUrl($name, $parameters, $getParams);
function url($name = null, $parameters = null, $getParams = null)
{
return SimpleRouter::getUrl($name, $parameters, $getParams);
}
/**
* Get current csrf-token
* @return null|string
*/
function csrf_token() {
$token = new \Pecee\CsrfToken();
return $token->getToken();
}
/**
* Get request object
* @return \Pecee\Http\Request
*/
function request() {
return SimpleRouter::request();
}
/**
* Get response object
* @return \Pecee\Http\Response
*/
function response() {
function response()
{
return SimpleRouter::response();
}
/**
* @return \Pecee\Http\Request
*/
function request()
{
return SimpleRouter::request();
}
/**
* Get input class
* @return \Pecee\Http\Input\Input
*/
function input() {
return SimpleRouter::request()->getInput();
function input()
{
return request()->getInput();
}
function redirect($url, $code = null)
{
if ($code !== null) {
response()->httpCode($code);
}
response()->redirect($url);
}
```
@@ -422,7 +422,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'], function () {
SimpleRouter::group(['middleware' => \Demo\Middleware\Auth::class], function () {
SimpleRouter::get('/', function () {
// Uses Auth Middleware
});
@@ -437,6 +437,11 @@ SimpleRouter::group(['middleware' => '\Demo\Middleware\Auth'], 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
@@ -480,7 +485,8 @@ 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::router()->getLoadedRoute();
SimpleRouter::request()->getLoadedRoute();
request()->getLoadedRoute();
```
## Other examples
@@ -494,7 +500,7 @@ use Pecee\SimpleRouter\SimpleRouter;
/* Adding custom csrfVerifier here */
SimpleRouter::csrfVerifier(new \Demo\Middlewares\CsrfVerifier());
SimpleRouter::group(['middleware' => '\Demo\Middlewares\Site', 'exceptionHandler' => 'Handlers\CustomExceptionHandler'], function() {
SimpleRouter::group(['middleware' => \Demo\Middlewares\Site::class, 'exceptionHandler' => \Demo\Handlers\CustomExceptionHandler::class], function() {
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show', ['where' => ['id' => '[0-9]+']]);
@@ -504,7 +510,7 @@ SimpleRouter::group(['middleware' => '\Demo\Middlewares\Site', 'exceptionHandler
* Restful resource (see IRestController interface for available methods)
*/
SimpleRouter::resource('/rest', 'ControllerRessource');
SimpleRouter::resource('/rest', ControllerRessource::class);
/**
@@ -520,7 +526,7 @@ SimpleRouter::group(['middleware' => '\Demo\Middlewares\Site', 'exceptionHandler
* etc.
*/
SimpleRouter::controller('/animals', 'ControllerAnimals');
SimpleRouter::controller('/animals', ControllerAnimals::class);
});
@@ -585,13 +591,19 @@ 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) {
public function handle(Request $request) {
$request->setUri(url('home'));
// 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;
}
}
}
@@ -615,11 +627,10 @@ 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, ILoadableRoute &$route = null, \Exception $error)
public function handleError(Request $request, \Exception $error)
{
/* You can use the exception handler to format errors depending on the request and type. */
@@ -636,14 +647,9 @@ class CustomExceptionHandler implements IExceptionHandler
/* 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.
*/
// Render custom 404-page
$request->setUri(url('page.notfound'));
$request->setRewriteCallback('Demo\Controllers\PageController@notFound');
return $request;
}
@@ -661,7 +667,7 @@ class CustomExceptionHandler implements IExceptionHandler
By default all controller and resource routes will use a simplified version of their url as name.
### Get routes using custom name (single route)
### Get by name (single route)
```php
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
@@ -674,10 +680,10 @@ url('product', null, ['category' => 'shoes']);
# /product-view/?category=shoes
```
### Getting the url using the name (controller route)
### Get by name (controller route)
```php
SimpleRouter::controller('/images', 'ImagesController', ['as' => 'picture']);
SimpleRouter::controller('/images', ImagesController::class, ['as' => 'picture']);
url('picture@getView', null, ['category' => 'shoes']);
url('picture', 'getView', ['category' => 'shoes']);
@@ -689,7 +695,7 @@ url('picture', 'view');
# /images/view/
```
### Getting the url using class
### Get by class
```php
SimpleRouter::get('/product-view/{id}', 'ProductsController@show', ['as' => 'product']);
@@ -706,7 +712,7 @@ url('ImagesController@getImage', null, ['id' => 22]);
### Using custom names for methods on a controller/resource route
```php
SimpleRouter::controller('gadgets', 'GadgetsController', ['names' => ['getIphoneInfo' => 'iphone']]);
SimpleRouter::controller('gadgets', GadgetsController::class, ['names' => ['getIphoneInfo' => 'iphone']]);
url('gadgets.iphone');
@@ -717,7 +723,7 @@ url('gadgets.iphone');
### Getting REST/resource controller urls
```php
SimpleRouter::resource('/phones', 'PhonesController');
SimpleRouter::resource('/phones', PhonesController::class);
url('phones');
url('phones.index');
@@ -732,7 +738,7 @@ url('phones.edit');
# /phones/edit/
```
### Return the current url
### Get the current url
```php
url();
@@ -749,17 +755,17 @@ url(null, null, ['q' => 'cars']);
We've added the `Input` class to easy access and manage parameters from your Controller-classes.
**Return single parameter value (matches both GET, POST, FILE):**
### Get single parameter value:
If items is grouped in the html, it will return an array of items.
**Note:** `get` will automatically trim the value and ensure that it's not empty. If it's empty the `$defaultValue` will be returned.
```php
$value = input()->get($index, $defaultValue);
$value = input()->get($index, $defaultValue, $methods);
```
**Return parameter object (matches both GET, POST, FILE):**
### Get parameter object
Will return an instance of `InputItem` or `InputFile` depending on the type.
@@ -772,10 +778,10 @@ If items is grouped in the html, it will return an array of items.
**Note:** `getObject` will only return `$defaultValue` if the item doesn't exist. If you want `$defaultValue` to be returned if the item is empty, please use `input()->get()` instead.
```php
$object = input()->getObject($index);
$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) --
@@ -799,9 +805,11 @@ $object = input()->get($index, $defaultValue, 'file');
$object = input()->findGet($index, $defaultValue);
$object = input()->findPost($index, $defaultValue);
$object = input()->findFile($index, $defaultValue);
```
# -- examples --
### Managing files
```php
/**
* In this small example we loop through a collection of files
* added on the page like this
@@ -819,9 +827,10 @@ foreach(input()->get('images', []) as $image)
}
}
```
**Return all parameters:**
### Get all parameters
```php
// Get all
@@ -853,15 +862,140 @@ All object implements the `IInputItem` interface and will always contain these m
Below example requires you to have the helper functions added. Please refer to the helper functions section in the documentation.
```php
// Get parameter site_id or default-value 2
$siteId = input()->get('site_id', 2);
/* Get parameter site_id or default-value 2 from either post-value or query-string */
$siteId = input()->get('site_id', 2, ['post', 'get']);
```
---
# Advanced
## Load routes dynamicially using the router bootmanager
## 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');
```
### Examples
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
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.
@@ -877,7 +1011,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) {
@@ -885,11 +1019,11 @@ class CustomRouterRules implement IRouterBootManager {
// If the current uri matches the url, we use our custom route
if($request->getUri() === $url) {
$request->setUri($rule);
$request->setRewriteUrl($rule);
return $request;
}
}
return $request;
}
}
@@ -907,82 +1041,6 @@ The last thing we need to do, is to add our custom boot-manager to the ```routes
SimpleRouter::addBootManager(new CustomRouterRules());
```
## 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.
@@ -992,8 +1050,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;
/* Grap the router instance */
$router = Router::getInstance();
/* Create new Router instance */
$router = new Router();
$route = new RouteUrl('/answer/1', function() {
@@ -1001,7 +1059,7 @@ $route = new RouteUrl('/answer/1', function() {
});
$route->setMiddleware('\Demo\Middlewares\AuthMiddleware');
$route->setMiddleware(\Demo\Middlewares\AuthMiddleware::class);
$route->setNamespace('\Demo\Controllers');
$route->setPrefix('v1');
@@ -1043,6 +1101,7 @@ class Router extends SimpleRouter {
# Credits
## Sites
This is some sites that uses the simple-router project in production.
- [holla.dk](http://www.holla.dk)
+29 -23
View File
@@ -1,26 +1,32 @@
{
"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/"
}
"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"
}
],
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "4.7.7"
},
"autoload": {
"psr-4": {
"Pecee\\": "src/Pecee/"
}
}
}
@@ -0,0 +1,47 @@
<?php
namespace Pecee\Controllers;
interface IResourceController
{
/**
* @return void
*/
public function index();
/**
* @param mixed $id
* @return void
*/
public function show($id);
/**
* @return void
*/
public function store();
/**
* @return void
*/
public function create();
/**
* View
* @param mixed $id
* @return void
*/
public function edit($id);
/**
* @param mixed $id
* @return void
*/
public function update($id);
/**
* @param mixed $id
* @return void
*/
public function destroy($id);
}
-46
View File
@@ -1,46 +0,0 @@
<?php
namespace Pecee\Controllers;
interface IRestController {
/**
* @return void
*/
function index();
/**
* @param mixed $id
* @return void
*/
function show($id);
/**
* @return void
*/
function store();
/**
* @return void
*/
function create();
/**
* View
* @param mixed $id
* @return void
*/
function edit($id);
/**
* @param mixed $id
* @return void
*/
function update($id);
/**
* @param mixed $id
* @return void
*/
function destroy($id);
}
+58 -55
View File
@@ -3,66 +3,69 @@ namespace Pecee;
class CsrfToken
{
const CSRF_KEY = 'XSRF-TOKEN';
const CSRF_KEY = 'XSRF-TOKEN';
protected $token;
protected $token;
/**
* Generate random identifier for CSRF token
*
* @return string
*/
public static function generateToken()
{
if (function_exists('mcrypt_create_iv')) {
return bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
}
return bin2hex(openssl_random_pseudo_bytes(32));
}
/**
* Generate random identifier for CSRF token
*
* @return string
*/
public static function generateToken()
{
if (function_exists('random_bytes')) {
return bin2hex(random_bytes(32));
}
/**
* Validate valid CSRF token
*
* @param string $token
* @return bool
*/
public function validate($token)
{
if ($token !== null && $this->getToken() !== null) {
return hash_equals($token, $this->getToken());
}
return false;
}
return bin2hex(openssl_random_pseudo_bytes(32));
}
/**
* Set csrf token cookie
*
* @param $token
*/
public function setToken($token)
{
setcookie(static::CSRF_KEY, $token, time() + 60 * 120, '/');
}
/**
* Validate valid CSRF token
*
* @param string $token
* @return bool
*/
public function validate($token)
{
if ($token !== null && $this->getToken() !== null) {
return hash_equals($token, $this->getToken());
}
/**
* Get csrf token
* @return string|null
*/
public function getToken()
{
if ($this->hasToken()) {
return $_COOKIE[static::CSRF_KEY];
}
return null;
}
return false;
}
/**
* Returns whether the csrf token has been defined
* @return bool
*/
public function hasToken()
{
return isset($_COOKIE[static::CSRF_KEY]);
}
/**
* Set csrf token cookie
*
* @param $token
*/
public function setToken($token)
{
setcookie(static::CSRF_KEY, $token, time() + 60 * 120, '/');
}
/**
* Get csrf token
* @return string|null
*/
public function getToken()
{
if ($this->hasToken()) {
return $_COOKIE[static::CSRF_KEY];
}
return null;
}
/**
* Returns whether the csrf token has been defined
* @return bool
*/
public function hasToken()
{
return isset($_COOKIE[static::CSRF_KEY]);
}
}
+6 -8
View File
@@ -2,16 +2,14 @@
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, ILoadableRoute &$route = null, \Exception $error);
/**
* @param Request $request
* @param \Exception $error
* @return Request|null
*/
public function handleError(Request $request, \Exception $error);
}
+8 -4
View File
@@ -4,12 +4,16 @@ namespace Pecee\Http\Input;
interface IInputItem
{
public function getIndex();
public function getIndex();
public function getName();
public function setIndex($index);
public function getValue();
public function getName();
public function __toString();
public function setName($name);
public function getValue();
public function __toString();
}
+229 -183
View File
@@ -5,247 +5,293 @@ use Pecee\Http\Request;
class Input
{
/**
* @var array
*/
public $get = [];
/**
* @var array
*/
public $get = [];
/**
* @var array
*/
public $post = [];
/**
* @var array
*/
public $post = [];
/**
* @var array
*/
public $file = [];
/**
* @var array
*/
public $file = [];
/**
* @var Request
*/
protected $request;
/**
* @var Request
*/
protected $request;
protected $invalidContentType = false;
public function __construct(Request $request)
{
$this->request = $request;
protected $invalidContentTypes = [
'text/plain',
'application/x-www-form-urlencoded',
];
$this->parseInputs();
}
public function __construct(Request $request)
{
$this->request = $request;
public function parseInputs()
{
/* Parse get requests */
if (count($_GET) > 0) {
$this->get = $this->handleGetPost($_GET);
}
if ($request->getMethod() !== 'get') {
/* Parse post requests */
$postVars = $_POST;
$requestContentType = $request->getHeader('http-content-type');
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete'], false) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
$max = count($this->invalidContentTypes) - 1;
if (count($postVars) > 0) {
$this->post = $this->handleGetPost($postVars);
}
for ($i = $max; $i >= 0; $i--) {
/* Parse get requests */
if (count($_FILES) > 0) {
$this->file = $this->parseFiles();
}
}
$contentType = $this->invalidContentType[$i];
public function parseFiles()
{
$list = [];
if (stripos($requestContentType, $contentType) === 0) {
$this->invalidContentType = true;
break;
}
}
}
foreach ($_FILES as $key => $value) {
if ($this->invalidContentType === false) {
$this->parseInputs();
}
// Handle array input
if (is_array($value['name']) === false) {
$values['index'] = $key;
$list[$key] = InputFile::createFromArray(array_merge($value, $values));
continue;
}
}
$keys = [];
protected function parseInputs()
{
/* Parse get requests */
if (count($_GET) > 0) {
$this->get = $this->handleGetPost($_GET);
}
$files = $this->rearrangeFiles($value['name'], $keys, $value);
/* Parse post requests */
$postVars = $_POST;
if (isset($list[$key])) {
$list[$key][] = $files;
} else {
$list[$key] = $files;
}
if (in_array($this->request->getMethod(), ['put', 'patch', 'delete']) === true) {
parse_str(file_get_contents('php://input'), $postVars);
}
}
if (count($postVars) > 0) {
$this->post = $this->handleGetPost($postVars);
}
return $list;
}
/* Parse get requests */
protected function rearrangeFiles(array $values, &$index, $original)
{
if (count($_FILES) > 0) {
$output = [];
$max = count($_FILES) - 1;
$keys = array_keys($_FILES);
$getItem = function ($key, $property = 'name') use ($original, $index) {
for ($i = $max; $i >= 0; $i--) {
$path = $original[$property];
$key = $keys[$i];
$value = $_FILES[$key];
$fileValues = array_values($index);
// Handle array input
if (is_array($value['name']) === false) {
$values['index'] = $key;
$this->file[$key] = InputFile::createFromArray(array_merge($value, $values));
continue;
}
foreach ($fileValues as $i) {
$path = $path[$i];
}
$subMax = count($value['name']) - 1;
$keys = array_keys($value['name']);
$output = [];
return $path[$key];
};
for ($i = $subMax; $i >= 0; $i--) {
foreach ($values as $key => $value) {
$output[$keys[$i]] = InputFile::createFromArray([
'index' => $key,
'error' => $value['error'][$keys[$i]],
'tmp_name' => $value['tmp_name'][$keys[$i]],
'type' => $value['type'][$keys[$i]],
'size' => $value['size'][$keys[$i]],
'name' => $value['name'][$keys[$i]],
]);
if (is_array($getItem($key)) === false) {
}
$file = InputFile::createFromArray([
'index' => $key,
'error' => $getItem($key, 'error'),
'tmp_name' => $getItem($key, 'tmp_name'),
'type' => $getItem($key, 'type'),
'size' => $getItem($key, 'size'),
'filename' => $getItem($key, 'name'),
]);
$this->file[$key] = $output;
}
}
}
if (isset($output[$key])) {
$output[$key][] = $file;
} else {
$output[$key] = $file;
}
protected function handleGetPost($array)
{
$tmp = [];
continue;
}
$max = count($array) - 1;
$keys = array_keys($array);
$index[] = $key;
for ($i = $max; $i >= 0; $i--) {
$files = $this->rearrangeFiles($value, $index, $original);
$key = $keys[$i];
$value = $array[$key];
if (isset($output[$key])) {
$output[$key][] = $files;
} else {
$output[$key] = $files;
}
// Handle array input
if (is_array($value) === false) {
$tmp[$key] = new InputItem($key, $value);
continue;
}
}
$subMax = count($value) - 1;
$keys = array_keys($value);
$output = [];
return $output;
}
for ($i = $subMax; $i >= 0; $i--) {
$output[$keys[$i]] = new InputItem($key, $value[$keys[$i]]);
}
protected function handleGetPost(array $array)
{
$list = [];
$tmp[$key] = $output;
}
$max = count($array) - 1;
$keys = array_keys($array);
return $tmp;
}
for ($i = $max; $i >= 0; $i--) {
public function findPost($index, $default = null)
{
return isset($this->post[$index]) ? $this->post[$index] : $default;
}
$key = $keys[$i];
$value = $array[$key];
public function findFile($index, $default = null)
{
return isset($this->file[$index]) ? $this->file[$index] : $default;
}
// Handle array input
if (is_array($value) === false) {
$list[$key] = new InputItem($key, $value);
continue;
}
public function findGet($index, $default = null)
{
return isset($this->get[$index]) ? $this->get[$index] : $default;
}
$output = $this->handleGetPost($value);
public function getObject($index, $default = null, $method = null)
{
$element = null;
$list[$key] = $output;
}
if ($method === null || strtolower($method) === 'get') {
$element = $this->findGet($index);
}
return $list;
}
if ($element === null && $method === null || strtolower($method) === 'post') {
$element = $this->findPost($index);
}
/**
* Find post-value by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @return InputItem|string
*/
public function findPost($index, $defaultValue = null)
{
return isset($this->post[$index]) ? $this->post[$index] : $defaultValue;
}
if ($element === null && $method === null || strtolower($method) === 'file') {
$element = $this->findFile($index);
}
/**
* Find file by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @return InputFile|string
*/
public function findFile($index, $defaultValue = null)
{
return isset($this->file[$index]) ? $this->file[$index] : $defaultValue;
}
return ($element === null) ? $default : $element;
}
/**
* Find parameter/query-string by index or return default value.
*
* @param string $index
* @param string|null $defaultValue
* @return InputItem|string
*/
public function findGet($index, $defaultValue = null)
{
return isset($this->get[$index]) ? $this->get[$index] : $defaultValue;
}
/**
* Get input element value matching index
*
* @param string $index
* @param string|null $default
* @param string|null $method
* @return InputItem|string
*/
public function get($index, $default = null, $method = null)
{
$input = $this->getObject($index, $default, $method);
/**
* Get input object
*
* @param string $index
* @param string|null $defaultValue
* @param array|string|null $methods
* @return IInputItem|string
*/
public function getObject($index, $defaultValue = null, $methods = null)
{
if ($methods !== null && is_string($methods) === true) {
$methods = [$methods];
}
if ($input instanceof InputItem) {
return (trim($input->getValue()) === '') ? $default : $input->getValue();
}
$element = null;
return $input;
}
if ($methods === null || in_array('get', $methods)) {
$element = $this->findGet($index);
}
public function exists($index)
{
return ($this->getObject($index) !== null);
}
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods))) {
$element = $this->findPost($index);
}
/**
* Get all get/post items
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null)
{
if ($this->invalidContentType === true) {
return [];
}
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods))) {
$element = $this->findFile($index);
}
$output = $_POST;
return ($element !== null) ? $element : $defaultValue;
}
if ($this->request->getMethod() === 'post') {
/**
* Get input element value matching index
*
* @param string $index
* @param string|null $defaultValue
* @param array|string|null $methods
* @return InputItem|string
*/
public function get($index, $defaultValue = null, $methods = null)
{
$input = $this->getObject($index, $defaultValue, $methods);
$contents = file_get_contents('php://input');
if ($input instanceof InputItem) {
return (trim($input->getValue()) === '') ? $defaultValue : $input->getValue();
}
if (stripos(trim($contents), '{') === 0) {
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
return $input;
}
$output = array_merge($_GET, $output);
/**
* Check if a input-item exist
*
* @param string $index
* @return bool
*/
public function exists($index)
{
return ($this->getObject($index) !== null);
}
if ($filter !== null) {
$output = array_filter($output, function ($key) use ($filter) {
if (in_array($key, $filter)) {
return true;
}
/**
* Get all get/post items
* @param array|null $filter Only take items in filter
* @return array
*/
public function all(array $filter = null)
{
$output = $_POST;
return false;
}, ARRAY_FILTER_USE_KEY);
}
if ($this->request->getMethod() === 'post') {
return $output;
}
$contents = file_get_contents('php://input');
if (strpos(trim($contents), '{') === 0) {
$output = json_decode($contents, true);
if ($output === false) {
$output = [];
}
}
}
$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;
}
}
+240 -155
View File
@@ -3,188 +3,273 @@ namespace Pecee\Http\Input;
class InputFile implements IInputItem
{
public $index;
public $name;
public $size;
public $type;
public $error;
public $tmpName;
public $index;
public $name;
public $filename;
public $size;
public $type;
public $error;
public $tmpName;
public function __construct($index)
{
$this->index = $index;
public function __construct($index)
{
$this->index = $index;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* Create from array
*
* @param array $values
* @throws \InvalidArgumentException
* @return static
*/
public static function createFromArray(array $values)
{
if (!isset($values['index'])) {
throw new \InvalidArgumentException('Index key is required');
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/* Easy way of ensuring that all indexes-are set and not filling the screen with isset() */
/**
* @return string
*/
public function getSize()
{
return $this->size;
}
$values = array_merge([
'tmp_name' => null,
'type' => null,
'size' => null,
'name' => null,
'error' => null,
], $values);
/**
* @return string
*/
public function getType()
{
return $this->type;
}
return (new static($values['index']))
->setSize($values['size'])
->setError($values['error'])
->setType($values['type'])
->setTmpName($values['tmp_name'])
->setFilename($values['name']);
/**
* @return string
*/
public function getError()
{
return $this->error;
}
}
public function getMime()
{
return $this->getType();
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getTmpName()
{
return $this->tmpName;
}
/**
* Set input index
* @param string $index
* @return static $this
*/
public function setIndex($index)
{
$this->index = $index;
public function getExtension()
{
return pathinfo($this->getName(), PATHINFO_EXTENSION);
}
return $this;
}
public function move($destination)
{
return move_uploaded_file($this->tmpName, $destination);
}
/**
* @return string
*/
public function getSize()
{
return $this->size;
}
public function getContents()
{
return file_get_contents($this->tmpName);
}
/**
* Set file size
* @param int $size
* @return static $this
*/
public function setSize($size)
{
$this->size = $size;
public function setName($name)
{
$this->name = $name;
return $this;
}
return $this;
}
/**
* Get mime-type of file
* @return string
*/
public function getMime()
{
return $this->getType();
}
/**
* Set file temp. name
* @param string $name
* @return static $this
*/
public function setTmpName($name)
{
$this->tmpName = $name;
/**
* @return string
*/
public function getType()
{
return $this->type;
}
return $this;
}
/**
* Set type
* @param string $type
* @return static $this
*/
public function setType($type)
{
$this->type = $type;
/**
* Set file size
* @param int $size
* @return static $this
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
return $this;
}
/**
* Returns extension without "."
*
* @return string
*/
public function getExtension()
{
return pathinfo($this->getFilename(), PATHINFO_EXTENSION);
}
/**
* Set type
* @param string $type
* @return static $this
*/
public function setType($type)
{
$this->type = $type;
/**
* Get human friendly name
*
* @return string
*/
public function getName()
{
return $this->name;
}
return $this;
}
/**
* Set human friendly name.
* Useful for adding validation etc.
*
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
/**
* Set error
* @param int $error
* @return static $this
*/
public function setError($error)
{
$this->error = (int)$error;
return $this;
}
return $this;
}
/**
* Set filename
*
* @param string $name
* @return static $this
*/
public function setFilename($name)
{
$this->filename = $name;
public function getValue()
{
return $this->getTmpName();
}
return $this;
}
public function hasError()
{
return ($this->getError() !== 0);
}
/**
* Get filename
*
* @return string mixed
*/
public function getFilename()
{
return $this->filename;
}
/**
* Create from array
* @param array $values
* @return static
*/
public static function createFromArray(array $values)
{
if (!isset($values['index'])) {
throw new \InvalidArgumentException('Index key is required');
}
/**
* Move the uploaded temporary file to it's new home
*
* @param string $destination
* @return bool
*/
public function move($destination)
{
return move_uploaded_file($this->tmpName, $destination);
}
$input = new static($values['index']);
$input->setError(isset($values['error']) ? $values['error'] : null);
$input->setName(isset($values['name']) ? $values['name'] : null);
$input->setSize(isset($values['size']) ? $values['size'] : null);
$input->setType(isset($values['type']) ? $values['type'] : null);
$input->setTmpName(isset($values['tmp_name']) ? $values['tmp_name'] : null);
/**
* Get file contents
*
* @return string
*/
public function getContents()
{
return file_get_contents($this->tmpName);
}
return $input;
}
/**
* Return true if an upload error occurred.
*
* @return bool
*/
public function hasError()
{
return ($this->getError() !== 0);
}
public function toArray()
{
return [
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->name,
'error' => $this->error,
];
}
/**
* Get upload-error code.
*
* @return string
*/
public function getError()
{
return $this->error;
}
/**
* Set error
*
* @param int $error
* @return static $this
*/
public function setError($error)
{
$this->error = (int)$error;
return $this;
}
/**
* @return string
*/
public function getTmpName()
{
return $this->tmpName;
}
/**
* Set file temp. name
* @param string $name
* @return static $this
*/
public function setTmpName($name)
{
$this->tmpName = $name;
return $this;
}
public function __toString()
{
return $this->getTmpName();
}
public function getValue()
{
return $this->getFilename();
}
public function toArray()
{
return [
'tmp_name' => $this->tmpName,
'type' => $this->type,
'size' => $this->size,
'name' => $this->filename,
'error' => $this->error,
];
}
public function __toString()
{
return $this->getValue();
}
}
+64 -55
View File
@@ -3,68 +3,77 @@ namespace Pecee\Http\Input;
class InputItem implements IInputItem
{
public $index;
public $name;
public $value;
public $index;
public $name;
public $value;
public function __construct($index, $value = null)
{
$this->index = $index;
$this->value = $value;
public function __construct($index, $value = null)
{
$this->index = $index;
$this->value = $value;
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
// Make the name human friendly, by replace _ with space
$this->name = ucfirst(str_replace('_', ' ', $this->index));
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getIndex()
{
return $this->index;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
public function setIndex($index)
{
$this->index = $index;
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
return $this;
}
/**
* Set input name
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set input value
* @param string $value
* @return static $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* Set input name
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
public function __toString()
{
return (string)$this->value;
}
return $this;
}
/**
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Set input value
* @param string $value
* @return static $this
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
public function __toString()
{
return (string)$this->value;
}
}
+68 -68
View File
@@ -4,96 +4,96 @@ 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
{
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
const POST_KEY = 'csrf-token';
const HEADER_KEY = 'X-CSRF-TOKEN';
protected $except;
protected $csrfToken;
protected $token;
protected $except;
protected $csrfToken;
protected $token;
public function __construct()
{
$this->csrfToken = new CsrfToken();
public function __construct()
{
$this->csrfToken = new CsrfToken();
// Generate or get the CSRF-Token from Cookie.
$this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken();
}
// Generate or get the CSRF-Token from Cookie.
$this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken();
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
* @return bool
*/
protected function skip(Request $request)
{
if ($this->except === null || is_array($this->except) === false) {
return false;
}
/**
* Check if the url matches the urls in the except property
* @param Request $request
* @return bool
*/
protected function skip(Request $request)
{
if ($this->except === null || is_array($this->except) === false) {
return false;
}
$max = count($this->except) - 1;
$max = count($this->except) - 1;
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
for ($i = $max; $i >= 0; $i--) {
$url = $this->except[$i];
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUri(), $url) === 0);
} else {
$skip = ($url === rtrim($request->getUri(), '/'));
}
$url = rtrim($url, '/');
if ($url[strlen($url) - 1] === '*') {
$url = rtrim($url, '*');
$skip = (stripos($request->getUri(), $url) === 0);
} else {
$skip = ($url === rtrim($request->getUri(), '/'));
}
if ($skip === true) {
return true;
}
}
if ($skip === true) {
return true;
}
}
return false;
}
return false;
}
public function handle(Request $request, ILoadableRoute &$route = null)
{
public function handle(Request $request)
{
if (in_array($request->getMethod(), ['post', 'put', 'delete']) === true && $this->skip($request) === false) {
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) {
$token = $request->getInput()->get(static::POST_KEY, null, 'post');
$token = $request->getInput()->get(static::POST_KEY, null, 'post');
// If the token is not posted, check headers for valid x-csrf-token
if ($token === null) {
$token = $request->getHeader(static::HEADER_KEY);
}
// If the token is not posted, check headers for valid x-csrf-token
if ($token === null) {
$token = $request->getHeader(static::HEADER_KEY);
}
if ($this->csrfToken->validate($token) === false) {
throw new TokenMismatchException('Invalid csrf-token.');
}
if ($this->csrfToken->validate($token) === false) {
throw new TokenMismatchException('Invalid csrf-token.');
}
}
}
}
}
public function generateToken()
{
$token = $this->csrfToken->generateToken();
$this->csrfToken->setToken($token);
return $token;
}
public function generateToken()
{
$token = CsrfToken::generateToken();
$this->csrfToken->setToken($token);
public function hasToken()
{
if ($this->token != null) {
return true;
}
return $token;
}
return $this->csrfToken->hasToken();
}
public function hasToken()
{
if ($this->token !== null) {
return true;
}
public function getToken()
{
return $this->token;
}
return $this->csrfToken->hasToken();
}
public function getToken()
{
return $this->token;
}
}
+5 -7
View File
@@ -2,15 +2,13 @@
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, ILoadableRoute &$route);
/**
* @param Request $request
* @return Request|null
*/
public function handle(Request $request);
}
+311 -188
View File
@@ -2,229 +2,352 @@
namespace Pecee\Http;
use Pecee\Http\Input\Input;
use Pecee\SimpleRouter\Route\ILoadableRoute;
use Pecee\SimpleRouter\Route\RouteUrl;
use Pecee\SimpleRouter\SimpleRouter;
class Request
{
protected $data = [];
protected $headers;
protected $host;
protected $uri;
protected $method;
protected $input;
protected $data = [];
protected $headers;
protected $host;
protected $uri;
protected $method;
protected $input;
public function __construct()
{
$this->parseHeaders();
$this->host = $this->getHeader('http-host');;
$this->uri = $this->getHeader('request-uri');
$this->input = new Input($this);
$this->method = $this->input->get('_method', strtolower($this->getHeader('request-method')));
}
/**
* @var ILoadableRoute|null
*/
protected $rewriteRoute;
protected $rewriteUrl;
protected function parseHeaders()
{
$this->headers = [];
/**
* @var ILoadableRoute|null
*/
protected $loadedRoute;
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
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'));
}
for($i = $max; $i >= 0; $i--) {
$key = $keys[$i];
$value = $_SERVER[$key];
protected function parseHeaders()
{
$this->headers = [];
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
}
for ($i = $max; $i >= 0; $i--) {
$key = $keys[$i];
$value = $_SERVER[$key];
public function isSecure()
{
if ($this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443) {
return true;
}
$this->headers[strtolower($key)] = $value;
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
}
return false;
}
}
/**
* @return string
*/
public function getUri()
{
return $this->uri;
}
public function isSecure()
{
return $this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* @return string
*/
public function getUri()
{
return $this->uri;
}
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Get http basic auth user
* @return string|null
*/
public function getUser()
{
return $this->getHeader('php-auth-user');
}
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Get http basic auth password
* @return string|null
*/
public function getPassword()
{
return $this->getHeader('php-auth-pw');
}
/**
* Get http basic auth user
* @return string|null
*/
public function getUser()
{
return $this->getHeader('php-auth-user');
}
/**
* Get all headers
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get http basic auth password
* @return string|null
*/
public function getPassword()
{
return $this->getHeader('php-auth-pw');
}
/**
* Get id address
* @return string
*/
public function getIp()
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
}
/**
* Get all headers
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
if ($this->getHeader('http-x-forwarded-for') !== null && strlen($this->getHeader('http-x-forwarded-for'))) {
return $this->getHeader('http-x-forwarded_for');
}
/**
* Get id address
* @return string
*/
public function getIp()
{
if ($this->getHeader('http-cf-connecting-ip') !== null) {
return $this->getHeader('http-cf-connecting-ip');
}
return $this->getHeader('remote-addr');
}
if ($this->getHeader('http-x-forwarded-for') !== null) {
return $this->getHeader('http-x-forwarded_for');
}
/**
* Get referer
* @return string
*/
public function getReferer()
{
return $this->getHeader('http-referer');
}
return $this->getHeader('remote-addr');
}
/**
* Get user agent
* @return string
*/
public function getUserAgent()
{
return $this->getHeader('http-user-agent');
}
/**
* Get remote address/ip
*
* @alias static::getIp
* @return string
*/
public function getRemoteAddr()
{
return $this->getIp();
}
/**
* Get header value by name
*
* @param string $name
* @param object|null $defaultValue
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null)
{
if (isset($this->headers[strtolower($name)])) {
return $this->headers[strtolower($name)];
}
/**
* Get referer
* @return string
*/
public function getReferer()
{
return $this->getHeader('http-referer');
}
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
/**
* Get user agent
* @return string
*/
public function getUserAgent()
{
return $this->getHeader('http-user-agent');
}
for ($i = $max; $i >= 0; $i--) {
/**
* Get header value by name
*
* @param string $name
* @param string|null $defaultValue
*
* @return string|null
*/
public function getHeader($name, $defaultValue = null)
{
if (isset($this->headers[strtolower($name)])) {
return $this->headers[strtolower($name)];
}
$key = $keys[$i];
$name = $_SERVER[$key];
$max = count($_SERVER) - 1;
$keys = array_keys($_SERVER);
if ($key === $name) {
return $name;
}
}
for ($i = $max; $i >= 0; $i--) {
return $defaultValue;
}
$key = $keys[$i];
$name = $_SERVER[$key];
/**
* Get input class
* @return Input
*/
public function getInput()
{
return $this->input;
}
if ($key === $name) {
return $name;
}
}
/**
* Is format accepted
*
* @param string $format
*
* @return bool
*/
public function isFormatAccepted($format)
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
return $defaultValue;
}
/**
* Get accept formats
* @return array
*/
public function getAcceptFormats()
{
return explode(',', $this->getHeader('http-accept'));
}
/**
* Get input class
* @return Input
*/
public function getInput()
{
return $this->input;
}
/**
* @param string $uri
*/
public function setUri($uri)
{
$this->uri = $uri;
}
/**
* Is format accepted
*
* @param string $format
*
* @return bool
*/
public function isFormatAccepted($format)
{
return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1);
}
/**
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* Get accept formats
* @return array
*/
public function getAcceptFormats()
{
return explode(',', $this->getHeader('http-accept'));
}
/**
* @param string $method
*/
public function setMethod($method)
{
$this->method = $method;
}
/**
* @param string $uri
*/
public function setUri($uri)
{
$this->uri = $uri;
}
public function __set($name, $value = null)
{
$this->data[$name] = $value;
}
/**
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
public function __get($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
/**
* @param string $method
*/
public function setMethod($method)
{
$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);
}
public function __set($name, $value = null)
{
$this->data[$name] = $value;
}
public function __get($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
}
+98 -95
View File
@@ -3,116 +3,119 @@ namespace Pecee\Http;
class Response
{
protected $request;
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Set the http status code
*
* @param int $code
* @return static
*/
public function httpCode($code)
{
http_response_code($code);
return $this;
}
/**
* Set the http status code
*
* @param int $code
* @return static
*/
public function httpCode($code)
{
http_response_code($code);
/**
* Redirect the response
*
* @param string $url
* @param int $httpCode
*/
public function redirect($url, $httpCode = null)
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
}
return $this;
}
$this->header('location: ' . $url);
die();
}
/**
* Redirect the response
*
* @param string $url
* @param int $httpCode
*/
public function redirect($url, $httpCode = null)
{
if ($httpCode !== null) {
$this->httpCode($httpCode);
}
public function refresh()
{
$this->redirect($this->request->getUri());
}
$this->header('location: ' . $url);
die();
}
/**
* Add http authorisation
* @param string $name
* @return static
*/
public function auth($name = '')
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
'HTTP/1.0 401 Unauthorized'
]);
return $this;
}
public function refresh()
{
$this->redirect($this->request->getUri());
}
public function cache($eTag, $lastModified = 2592000)
{
/**
* Add http authorisation
* @param string $name
* @return static
*/
public function auth($name = '')
{
$this->headers([
'WWW-Authenticate: Basic realm="' . $name . '"',
'HTTP/1.0 401 Unauthorized',
]);
$this->headers([
'Cache-Control: public',
'Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT',
'Etag: ' . $eTag
]);
return $this;
}
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
public function cache($eTag, $lastModified = 2592000)
{
if ($httpModified !== null && strtotime($httpModified) == $lastModified || $httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) {
$this->headers([
'Cache-Control: public',
'Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT',
'Etag: ' . $eTag,
]);
$this->header('HTTP/1.1 304 Not Modified');
$httpModified = $this->request->getHeader('http-if-modified-since');
$httpIfNoneMatch = $this->request->getHeader('http-if-none-match');
exit();
}
if (($httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) || ($httpModified !== null && strtotime($httpModified) === $lastModified)) {
return $this;
}
$this->header('HTTP/1.1 304 Not Modified');
/**
* Json encode array
* @param array $value
*/
public function json(array $value)
{
$this->header('Content-Type: application/json');
echo json_encode($value);
die();
}
exit();
}
/**
* Add header to response
* @param string $value
* @return static
*/
public function header($value)
{
header($value);
return $this;
}
return $this;
}
/**
* Add multiple headers to response
* @param array $headers
* @return static
*/
public function headers(array $headers)
{
$max = count($headers);
for($i = 0; $i < $max; $i++) {
$this->header($headers[$i]);
}
return $this;
}
/**
* Json encode array
* @param array $value
*/
public function json(array $value)
{
$this->header('Content-Type: application/json');
echo json_encode($value);
die();
}
/**
* Add header to response
* @param string $value
* @return static
*/
public function header($value)
{
header($value);
return $this;
}
/**
* Add multiple headers to response
* @param array $headers
* @return static
*/
public function headers(array $headers)
{
foreach ($headers as $header) {
$this->header($header);
}
return $this;
}
}
@@ -3,4 +3,5 @@ namespace Pecee\SimpleRouter\Exceptions;
class NotFoundHttpException extends HttpException
{
}
@@ -5,11 +5,11 @@ use Pecee\Http\Request;
interface IRouterBootManager
{
/**
* Called when router loads it's routes
*
* @param Request $request
* @return Request
*/
public function boot(Request $request);
/**
* Called when router loads it's routes
*
* @param Request $request
* @return Request
*/
public function boot(Request $request);
}
@@ -3,34 +3,34 @@ namespace Pecee\SimpleRouter\Route;
interface IControllerRoute extends IRoute
{
/**
* Get controller class-name
*
* @return string
*/
public function getController();
/**
* Get controller class-name
*
* @return string
*/
public function getController();
/**
* Set controller class-name
*
* @param string $controller
* @return static
*/
public function setController($controller);
/**
* Set controller class-name
*
* @param string $controller
* @return static
*/
public function setController($controller);
/**
* Return active method
*
* @return string
*/
public function getMethod();
/**
* Return active method
*
* @return string
*/
public function getMethod();
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method);
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method);
}
+46 -46
View File
@@ -5,56 +5,56 @@ use Pecee\Http\Request;
interface IGroupRoute extends IRoute
{
/**
* Method called to check if a domain matches
*
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request);
/**
* Method called to check if a domain matches
*
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request);
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
*/
public function setExceptionHandlers(array $handlers);
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
*/
public function setExceptionHandlers(array $handlers);
/**
* Get exception-handlers for group
*
* @return array
*/
public function getExceptionHandlers();
/**
* Get exception-handlers for group
*
* @return array
*/
public function getExceptionHandlers();
/**
* Get domains for domain.
*
* @return array
*/
public function getDomains();
/**
* Get domains for domain.
*
* @return array
*/
public function getDomains();
/**
* Set allowed domains for group.
*
* @param array $domains
* @return $this
*/
public function setDomains(array $domains);
/**
* Set allowed domains for group.
*
* @param array $domains
* @return $this
*/
public function setDomains(array $domains);
/**
* Set prefix that child-routes will inherit.
*
* @param string $prefix
* @return string
*/
public function setPrefix($prefix);
/**
* Set prefix that child-routes will inherit.
*
* @param string $prefix
* @return string
*/
public function setPrefix($prefix);
/**
* Get prefix.
*
* @return string
*/
public function getPrefix();
/**
* Get prefix.
*
* @return string
*/
public function getPrefix();
}
+53 -39
View File
@@ -5,50 +5,64 @@ use Pecee\Http\Request;
interface ILoadableRoute extends IRoute
{
/**
* Find url that matches method, parameters or name.
* Used when calling the url() helper.
*
* @param string|null $method
* @param array|null $parameters
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null);
/**
* Find url that matches method, parameters or name.
* Used when calling the url() helper.
*
* @param string|null $method
* @param array|null $parameters
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null);
/**
* Loads and renders middlewares-classes
*
* @param Request $request
* @param ILoadableRoute $route
*/
public function loadMiddleware(Request $request, ILoadableRoute &$route);
/**
* Loads and renders middlewares-classes
*
* @param Request $request
*/
public function loadMiddleware(Request $request);
public function getUrl();
public function getUrl();
public function setUrl($url);
public function setUrl($url);
/**
* Returns the provided name for the router.
*
* @return string
*/
public function getName();
/**
* Returns the provided name for the router.
*
* @return string
*/
public function getName();
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name);
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name);
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static $this
*/
public function setName($name);
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static $this
*/
public function setName($name);
/**
* Get regular expression match used for matching route (if defined).
*
* @return string
*/
public function getMatch();
/**
* Add regular expression match for the entire route.
*
* @param string $regex
* @return static
*/
public function setMatch($regex);
}
+151 -164
View File
@@ -5,195 +5,182 @@ use Pecee\Http\Request;
interface IRoute
{
/**
* Method called to check if a domain matches
*
* @param Request $request
* @return bool
*/
public function matchRoute(Request $request);
/**
* Method called to check if a domain matches
*
* @param string $route
* @param Request $request
* @return bool
*/
public function matchRoute($route, Request $request);
/**
* Called when route is matched.
* Returns class to be rendered.
*
* @param Request $request
* @return object
*/
public function renderRoute(Request $request);
/**
* Called when route is matched.
* Returns class to be rendered.
*
* @param Request $request
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
* @return void
*/
public function renderRoute(Request $request);
/**
* Returns callback name/identifier for the current route based on the callback.
* Useful if you need to get a unique identifier for the loaded route, for instance
* when using translations etc.
*
* @return string
*/
public function getIdentifier();
/**
* Returns callback name/identifier for the current route based on the callback.
* Useful if you need to get a unique identifier for the loaded route, for instance
* when using translations etc.
*
* @return string
*/
public function getIdentifier();
/**
* Set allowed request methods
*
* @param array $methods
* @return static $this
*/
public function setRequestMethods(array $methods);
/**
* Set allowed request methods
*
* @param array $methods
* @return static $this
*/
public function setRequestMethods(array $methods);
/**
* Get allowed request methods
*
* @return array
*/
public function getRequestMethods();
/**
* Get allowed request methods
*
* @return array
*/
public function getRequestMethods();
/**
* @return IRoute|null
*/
public function getParent();
/**
* @return IRoute|null
*/
public function getParent();
/**
* Get the group for the route.
*
* @return IGroupRoute|null
*/
public function getGroup();
/**
* Get the group for the route.
*
* @return IGroupRoute|null
*/
public function getGroup();
/**
* Set group
*
* @param IGroupRoute $group
* @return static $this
*/
public function setGroup(IGroupRoute $group);
/**
* Set group
*
* @param IGroupRoute $group
* @return static $this
*/
public function setGroup(IGroupRoute $group);
/**
* Set parent route
*
* @param IRoute $parent
* @return static $this
*/
public function setParent(IRoute $parent);
/**
* Set parent route
*
* @param IRoute $parent
* @return static $this
*/
public function setParent(IRoute $parent);
/**
* Set callback
*
* @param string $callback
* @return static
*/
public function setCallback($callback);
/**
* Set callback
*
* @param string $callback
* @return static
*/
public function setCallback($callback);
/**
* @return string
*/
public function getCallback();
/**
* @return string
*/
public function getCallback();
public function getMethod();
public function getMethod();
public function getClass();
public function getClass();
public function setMethod($method);
public function setMethod($method);
/**
* @param string $namespace
* @return static $this
*/
public function setNamespace($namespace);
/**
* @param string $namespace
* @return static $this
*/
public function setNamespace($namespace);
/**
* @return string
*/
public function getNamespace();
/**
* @return string
*/
public function getNamespace();
/**
* @param string $namespace
* @return static $this
*/
public function setDefaultNamespace($namespace);
/**
* @param string $namespace
* @return static $this
*/
public function setDefaultNamespace($namespace);
public function getDefaultNamespace();
public function getDefaultNamespace();
/**
* Get regular expression match used for matching route (if defined).
*
* @return string
*/
public function getMatch();
/**
* Get parameter names.
*
* @return array
*/
public function getWhere();
/**
* Add regular expression match for the entire route.
*
* @param string $regex
* @return static
*/
public function setMatch($regex);
/**
* Set parameter names.
*
* @param array $options
* @return static
*/
public function setWhere(array $options);
/**
* Get parameter names.
*
* @return array
*/
public function getWhere();
/**
* Get parameters
*
* @return array
*/
public function getParameters();
/**
* Set parameter names.
*
* @param array $options
* @return static
*/
public function setWhere(array $options);
/**
* Get parameters
*
* @param array $parameters
* @return static $this
*/
public function setParameters(array $parameters);
/**
* Get parameters
*
* @return array
*/
public function getParameters();
/**
* Merge with information from another route.
*
* @param array $settings
* @param bool $merge
* @return static $this
*/
public function setSettings(array $settings, $merge = false);
/**
* Get parameters
*
* @param array $parameters
* @return static $this
*/
public function setParameters(array $parameters);
/**
* Export route settings to array so they can be merged with another route.
*
* @return array
*/
public function toArray();
/**
* Merge with information from another route.
*
* @param array $settings
* @param bool $merge
* @return static $this
*/
public function setSettings(array $settings, $merge = false);
/**
* Get middlewares array
*
* @return array
*/
public function getMiddlewares();
/**
* Export route settings to array so they can be merged with another route.
*
* @return array
*/
public function toArray();
/**
* Set middleware class-name
*
* @param string $middleware
* @return static
*/
public function setMiddleware($middleware);
/**
* Get middlewares array
*
* @return array
*/
public function getMiddlewares();
/**
* Set middleware class-name
*
* @param string $middleware
* @return static
*/
public function setMiddleware($middleware);
/**
* Set middlewares array
*
* @param array $middlewares
* @return $this
*/
public function setMiddlewares(array $middlewares);
/**
* Set middlewares array
*
* @param array $middlewares
* @return $this
*/
public function setMiddlewares(array $middlewares);
}
+195 -152
View File
@@ -7,198 +7,241 @@ use Pecee\SimpleRouter\Exceptions\HttpException;
abstract class LoadableRoute extends Route implements ILoadableRoute
{
const PARAMETERS_REGEX_MATCH = '%s([\w\-\_]*?)\%s{0,1}%s';
/**
* @var string
*/
protected $url;
protected $url;
protected $name;
/**
* @var string
*/
protected $name;
/**
* Loads and renders middlewares-classes
*
* @param Request $request
* @param ILoadableRoute $route
* @throws HttpException
*/
public function loadMiddleware(Request $request, ILoadableRoute &$route)
{
if (count($this->getMiddlewares()) > 0) {
protected $regex;
$max = count($this->getMiddlewares());
/**
* Loads and renders middlewares-classes
*
* @param Request $request
* @throws HttpException
*/
public function loadMiddleware(Request $request)
{
$max = count($this->getMiddlewares());
for ($i = 0; $i < $max; $i++) {
if ($max > 0) {
$middleware = $this->getMiddlewares()[$i];
for ($i = 0; $i < $max; $i++) {
$middleware = $this->loadClass($middleware);
if (!($middleware instanceof IMiddleware)) {
throw new HttpException($middleware . ' must be instance of Middleware');
}
$middleware = $this->getMiddlewares()[$i];
$middleware->handle($request, $route);
}
}
}
$middleware = $this->loadClass($middleware);
/**
* Set url
*
* @param string $url
* @return static
*/
public function setUrl($url)
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
if (($middleware instanceof IMiddleware) === false) {
throw new HttpException($middleware . ' must be instance of Middleware');
}
if(strpos($this->url, $this->paramModifiers[0]) !== false) {
$middleware->handle($request);
}
}
}
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
public function matchRegex(Request $request, $url)
{
/* Match on custom defined regular expression */
if (preg_match_all('/' . $regex . '/is', $this->url, $matches)) {
if ($this->regex === null) {
return null;
}
$max = count($matches[1]);
$parameters = [];
for ($i = 0; $i < $max; $i++) {
$this->parameters[$matches[1][$i]] = null;
}
if (preg_match($this->regex, $request->getHost() . $url, $parameters) > 0) {
}
/* Remove global match */
$this->parameters = array_slice($parameters, 1);
}
return true;
}
return $this;
}
return false;
}
public function getUrl()
{
return $this->url;
}
/**
* Set url
*
* @param string $url
* @return static
*/
public function setUrl($url)
{
$this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/';
/**
* Find url that matches method, parameters or name.
* Used when calling the url() helper.
*
* @param string|null $method
* @param array|null $parameters
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null)
{
$url = '';
if (strpos($this->url, $this->paramModifiers[0]) !== false) {
$parameters = (array)$parameters;
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
$url .= '//' . $this->getGroup()->getDomains()[0];
}
if (preg_match_all('/' . $regex . '/', $this->url, $matches)) {
$this->parameters = array_fill_keys($matches[1], null);
}
}
$url .= $this->getUrl();
return $this;
}
$params = array_merge($this->getParameters(), $parameters);
public function getUrl()
{
return $this->url;
}
/* Url that contains parameters that aren't recognized */
$unknownParams = [];
/**
* Find url that matches method, parameters or name.
* Used when calling the url() helper.
*
* @param string|null $method
* @param array|null $parameters
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null)
{
$url = $this->getUrl();
/* Create the param string - {} */
$param1 = $this->paramModifiers[0] . '%s' . $this->paramModifiers[1];
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
$url = '//' . $this->getGroup()->getDomains()[0] . $url;
}
/* Create the param string with the optional symbol - {?} */
$param2 = $this->paramModifiers[0] . '%s' . $this->paramOptionalSymbol . $this->paramModifiers[1];
/* Contains parameters that aren't recognized and will be appended at the end of the url */
$unknownParams = [];
/* Let's parse the values of any {} parameter in the url */
/* Create the param string - {parameter} */
$param1 = $this->paramModifiers[0] . '%s' . $this->paramModifiers[1];
$max = count($params);
$keys = array_keys($params);
/* Create the param string with the optional symbol - {parameter?} */
$param2 = $this->paramModifiers[0] . '%s' . $this->paramOptionalSymbol . $this->paramModifiers[1];
for ($i = 0; $i < $max; $i++) {
$param = $keys[$i];
$value = $params[$param];
/* Replace any {parameter} in the url with the correct value */
$value = (isset($parameters[$param])) ? $parameters[$param] : $value;
$params = $this->getParameters();
$max = count($params) - 1;
$keys = array_keys($params);
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
$url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], $value, $url);
} else {
$unknownParams[$param] = $value;
}
}
for ($i = $max; $i >= 0; $i--) {
$param = $keys[$i];
$value = $value = ($parameters !== null && array_key_exists($param, $parameters)) ? $parameters[$param] : $params[$param];
$url .= join('/', $unknownParams);
/* If parameter is specifically set to null - use the original-defined value */
if ($value === null && isset($this->originalParameters[$param])) {
$value = $this->originalParameters[$param];
}
return rtrim($url, '/') . '/';
}
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
/* Add parameter to the correct position */
$url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], $value, $url);
} else {
$unknownParams[$param] = $value;
}
}
/**
* Returns the provided name for the router.
*
* @return string
*/
public function getName()
{
return $this->name;
}
$url .= join('/', $unknownParams);
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
return (strtolower($this->name) === strtolower($name));
}
return rtrim($url, '/') . '/';
}
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
* Alias for LoadableRoute::setName().
*
* @see LoadableRoute::setName()
* @param string|array $name
* @return static
*/
public function name($name)
{
return $this->setName($name);
}
/**
* Returns the provided name for the router.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
return (strtolower($this->name) === strtolower($name));
}
return $this;
}
/**
* Add regular expression match for the entire route.
*
* @param string $regex
* @return static
*/
public function setMatch($regex)
{
$this->regex = $regex;
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['as'])) {
if ($this->name !== null && $merge !== false) {
$this->setName($values['as'] . '.' . $this->name);
} else {
$this->setName($values['as']);
}
}
return $this;
}
if (isset($values['prefix'])) {
$this->setUrl($values['prefix'] . $this->getUrl());
}
/**
* Get regular expression match used for matching route (if defined).
*
* @return string
*/
public function getMatch()
{
return $this->regex;
}
parent::setSettings($values, $merge);
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
* Alias for LoadableRoute::setName().
*
* @see LoadableRoute::setName()
* @param string|array $name
* @return static
*/
public function name($name)
{
return $this->setName($name);
}
return $this;
}
/**
* Sets the router name, which makes it easier to obtain the url or router at a later point.
*
* @param string $name
* @return static $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['as'])) {
if ($this->name !== null && $merge !== false) {
$this->setName($values['as'] . '.' . $this->name);
} else {
$this->setName($values['as']);
}
}
if (isset($values['prefix'])) {
$this->setUrl($values['prefix'] . $this->getUrl());
}
parent::setSettings($values, $merge);
return $this;
}
}
File diff suppressed because it is too large Load Diff
+139 -162
View File
@@ -2,203 +2,180 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class RouteController extends LoadableRoute implements IControllerRoute
{
protected $defaultMethod = 'index';
protected $controller;
protected $method;
protected $names = [];
protected $defaultMethod = 'index';
protected $controller;
protected $method;
protected $names = [];
public function __construct($url, $controller)
{
$this->setUrl($url);
$this->setName(trim(str_replace('/', '.', $url), '/'));
$this->controller = $controller;
}
public function __construct($url, $controller)
{
$this->setUrl($url);
$this->setName(trim(str_replace('/', '.', $url), '/'));
$this->controller = $controller;
}
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
if ($this->name === null) {
return false;
}
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
if ($this->name === null) {
return false;
}
/* Remove method/type */
if (stripos($name, '.') !== false) {
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
/* Remove method/type */
if (strpos($name, '.') !== false) {
$method = substr($name, strrpos($name, '.') + 1);
$newName = substr($name, 0, strrpos($name, '.'));
if (strtolower($this->name) === strtolower($newName) && in_array($method, $this->names)) {
return true;
}
}
if (in_array($method, $this->names, false) === true && strtolower($this->name) === strtolower($newName)) {
return true;
}
}
return parent::hasName($name);
}
return parent::hasName($name);
}
public function findUrl($method = null, $parameters = null, $name = null)
{
/**
* @param string|null $method
* @param string|array|null $parameters
* @param string|null $name
* @return string
*/
public function findUrl($method = null, $parameters = null, $name = null)
{
if (strpos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
if ($found !== false) {
$method = $found;
}
}
if (stripos($name, '.') !== false) {
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names);
if ($found !== false) {
$method = $found;
}
}
$url = '';
$parameters = (array)$parameters;
$url = '';
if ($method !== null) {
$parameters = (array)$parameters;
/* Remove requestType from method-name, if it exists */
foreach (static::$requestTypes as $requestType) {
/* Remove requestType from method-name, if it exists */
if ($method !== null) {
$max = count(static::$requestTypes);
if (stripos($method, $requestType) === 0) {
$method = substr($method, strlen($requestType));
break;
}
}
for ($i = 0; $i < $max; $i++) {
$method .= '/';
}
$requestType = static::$requestTypes[$i];
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
$url .= '//' . $this->getGroup()->getDomains()[0];
}
if (stripos($method, $requestType) === 0) {
$method = substr($method, strlen($requestType));
break;
}
}
$method .= '/';
}
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters);
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
$url .= '//' . $this->getGroup()->getDomains()[0];
}
return '/' . trim($url, '/') . '/';
}
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters);
public function matchRoute($url, Request $request)
{
$url = parse_url(urldecode($url), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
return '/' . trim($url, '/') . '/';
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
public function renderRoute(Request $request)
{
if ($this->getCallback() !== null && is_callable($this->getCallback())) {
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
return false;
}
// When the callback is a function
call_user_func_array($this->getCallback(), $this->getParameters());
} else {
// When the callback is a method
$controller = explode('@', $this->getCallback());
$className = $this->getNamespace() . '\\' . $controller[0];
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
$path = explode('/', $strippedUrl);
$class = $this->loadClass($className);
$method = $request->getMethod() . ucfirst($controller[1]);
if (count($path) > 0) {
if (!method_exists($class, $method)) {
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
}
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $request->getMethod() . ucfirst($method);
call_user_func_array([$class, $method], $this->getParameters());
$this->parameters = array_slice($path, 1);
return $class;
}
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
return null;
}
return true;
}
public function matchRoute(Request $request)
{
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
return false;
}
if (strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) {
/**
* Get controller class-name.
*
* @return string
*/
public function getController()
{
return $this->controller;
}
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
/**
* Get controller class-name.
*
* @param string $controller
* @return static
*/
public function setController($controller)
{
$this->controller = $controller;
$path = explode('/', $strippedUrl);
return $this;
}
if (count($path) > 0) {
/**
* Return active method
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
$method = (!isset($path[0]) || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
$this->method = $method;
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method)
{
$this->method = $method;
array_shift($path);
$this->parameters = $path;
return $this;
}
// Set callback
$this->setCallback($this->controller . '@' . $this->method);
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['names'])) {
$this->names = $values['names'];
}
return true;
}
}
parent::setSettings($values, $merge);
return null;
}
/**
* Get controller class-name.
*
* @return string
*/
public function getController()
{
return $this->controller;
}
/**
* Get controller class-name.
*
* @param string $controller
* @return static
*/
public function setController($controller)
{
$this->controller = $controller;
return $this;
}
/**
* Return active method
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Set active method
*
* @param string $method
* @return static
*/
public function setMethod($method)
{
$this->method = $method;
return $this;
}
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['names'])) {
$this->names = $values['names'];
}
parent::setSettings($values, $merge);
return $this;
}
return $this;
}
}
+144 -142
View File
@@ -5,177 +5,179 @@ use Pecee\Http\Request;
class RouteGroup extends Route implements IGroupRoute
{
protected $prefix;
protected $name;
protected $domains = [];
protected $exceptionHandlers = [];
protected $prefix;
protected $name;
protected $domains = [];
protected $exceptionHandlers = [];
/**
* Method called to check if a domain matches
*
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request)
{
if (count($this->domains) > 0) {
/**
* Method called to check if a domain matches
*
* @param Request $request
* @return bool
*/
public function matchDomain(Request $request)
{
if (count($this->domains) === 0) {
return true;
}
$max = count($this->domains);
foreach ($this->domains as $domain) {
for ($i = 0; $i < $max; $i++) {
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
$domain = $this->domains[$i];
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
if ($parameters !== null && count($parameters) > 0) {
if ($parameters !== null) {
$this->parameters = $parameters;
$this->parameters = $parameters;
return true;
}
}
return true;
}
}
return false;
}
return false;
}
return true;
}
/**
* Method called to check if route matches
*
* @param string $url
* @param Request $request
* @return bool
*/
public function matchRoute($url, Request $request)
{
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
return false;
}
/**
* Method called to check if route matches
*
* @param Request $request
* @return bool
*/
public function matchRoute(Request $request)
{
// Skip if prefix doesn't match
if ($this->prefix !== null && stripos($request->getUri(), $this->prefix) === false) {
return false;
}
return $this->matchDomain($request);
}
return $this->matchDomain($request);
}
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
*/
public function setExceptionHandlers(array $handlers)
{
$this->exceptionHandlers = $handlers;
/**
* Set exception-handlers for group
*
* @param array $handlers
* @return static $this
*/
public function setExceptionHandlers(array $handlers)
{
$this->exceptionHandlers = $handlers;
return $this;
}
return $this;
}
/**
* Get exception-handlers for group
*
* @return array
*/
public function getExceptionHandlers()
{
return $this->exceptionHandlers;
}
/**
* Get exception-handlers for group
*
* @return array
*/
public function getExceptionHandlers()
{
return $this->exceptionHandlers;
}
/**
* Get allowed domains for domain.
*
* @return array
*/
public function getDomains()
{
return $this->domains;
}
/**
* Get allowed domains for domain.
*
* @return array
*/
public function getDomains()
{
return $this->domains;
}
/**
* Set allowed domains for group.
*
* @param array $domains
* @return $this
*/
public function setDomains(array $domains)
{
$this->domains = $domains;
/**
* Set allowed domains for group.
*
* @param array $domains
* @return $this
*/
public function setDomains(array $domains)
{
$this->domains = $domains;
return $this;
}
return $this;
}
/**
* @param string $prefix
* @return static
*/
public function setPrefix($prefix)
{
$this->prefix = '/' . trim($prefix, '/');
/**
* @param string $prefix
* @return static
*/
public function setPrefix($prefix)
{
$this->prefix = '/' . trim($prefix, '/');
return $this;
}
return $this;
}
/**
* Set prefix that child-routes will inherit.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Set prefix that child-routes will inherit.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['prefix'])) {
$this->setPrefix($values['prefix'] . $this->prefix);
}
if (isset($values['prefix'])) {
$this->setPrefix($values['prefix'] . $this->prefix);
}
if (isset($values['exceptionHandler'])) {
$this->setExceptionHandlers((array)$values['exceptionHandler']);
}
if (isset($values['exceptionHandler'])) {
$this->setExceptionHandlers((array)$values['exceptionHandler']);
}
if (isset($values['domain'])) {
$this->setDomains((array)$values['domain']);
}
if (isset($values['domain'])) {
$this->setDomains((array)$values['domain']);
}
if (isset($values['as'])) {
if ($this->name !== null && $merge !== false) {
$this->name = $values['as'] . '.' . $this->name;
} else {
$this->name = $values['as'];
}
}
if (isset($values['as'])) {
if ($this->name !== null && $merge !== false) {
$this->name = $values['as'] . '.' . $this->name;
} else {
$this->name = $values['as'];
}
}
parent::setSettings($values, $merge);
parent::setSettings($values, $merge);
return $this;
}
return $this;
}
/**
* Export route settings to array so they can be merged with another route.
*
* @return array
*/
public function toArray()
{
$values = [];
/**
* Export route settings to array so they can be merged with another route.
*
* @return array
*/
public function toArray()
{
$values = [];
if ($this->prefix !== null) {
$values['prefix'] = $this->getPrefix();
}
if ($this->prefix !== null) {
$values['prefix'] = $this->getPrefix();
}
if ($this->name !== null) {
$values['as'] = $this->name;
}
if ($this->name !== null) {
$values['as'] = $this->name;
}
if (count($this->parameters) > 0) {
$values['parameters'] = $this->parameters;
}
return array_merge($values, parent::toArray());
}
return array_merge($values, parent::toArray());
}
}
+174 -156
View File
@@ -2,202 +2,220 @@
namespace Pecee\SimpleRouter\Route;
use Pecee\Http\Request;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
class RouteResource extends LoadableRoute implements IControllerRoute
{
protected $urls = [
'index' => '',
'create' => 'create',
'store' => '',
'show' => '',
'edit' => 'edit',
'update' => '',
'destroy' => '',
];
protected $names = [];
protected $controller;
protected $urls = [
'index' => '',
'create' => 'create',
'store' => '',
'show' => '',
'edit' => 'edit',
'update' => '',
'destroy' => '',
];
public function __construct($url, $controller)
{
$this->setUrl($url);
$this->controller = $controller;
$this->setName(trim(str_replace('/', '.', $url), '/'));
}
protected $methodNames = [
'index' => 'index',
'create' => 'create',
'store' => 'store',
'show' => 'show',
'edit' => 'edit',
'update' => 'update',
'destroy' => 'destroy',
];
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
if ($this->name === null) {
return false;
}
protected $names = [];
protected $controller;
if (strtolower($this->name) === strtolower($name)) {
return true;
}
public function __construct($url, $controller)
{
$this->setUrl($url);
$this->controller = $controller;
$this->setName(trim(str_replace('/', '.', $url), '/'));
}
/* Remove method/type */
if (stripos($name, '.') !== false) {
$name = substr($name, 0, strrpos($name, '.'));
}
/**
* Check if route has given name.
*
* @param string $name
* @return bool
*/
public function hasName($name)
{
if ($this->name === null) {
return false;
}
return (strtolower($this->name) === strtolower($name));
}
if (strtolower($this->name) === strtolower($name)) {
return true;
}
public function findUrl($method = null, $parameters = null, $name = null)
{
$method = array_search($name, $this->names);
if ($method !== false) {
return rtrim($this->url . $this->urls[$method], '/') . '/';
}
/* Remove method/type */
if (strpos($name, '.') !== false) {
$name = substr($name, 0, strrpos($name, '.'));
}
return $this->url;
}
return (strtolower($this->name) === strtolower($name));
}
public function renderRoute(Request $request)
{
if ($this->getCallback() !== null && is_callable($this->getCallback())) {
// When the callback is a function
call_user_func_array($this->getCallback(), $this->getParameters());
} else {
// When the callback is a method
$controller = explode('@', $this->getCallback());
$className = $this->getNamespace() . '\\' . $controller[0];
$class = $this->loadClass($className);
$method = strtolower($controller[1]);
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], '/') . '/';
}
if (!method_exists($class, $method)) {
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
}
return $this->url;
}
call_user_func_array([$class, $method], $this->getParameters());
protected function call($method)
{
$this->setCallback($this->controller . '@' . $method);
return $class;
}
return true;
}
return null;
}
public function matchRoute($url, Request $request)
{
$url = parse_url(urldecode($url), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
protected function call($method, $parameters)
{
$this->setCallback($this->controller . '@' . $method);
$this->parameters = $parameters;
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
return true;
}
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
return false;
}
public function matchRoute(Request $request)
{
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
$this->parameters = $this->parseParameters($route, $url);
if ($this->parameters === null) {
return false;
}
$parameters = $this->parseParameters($route, $url);
$action = strtolower(trim($this->parameters['action']));
$id = $this->parameters['id'];
if ($parameters !== null) {
// Remove action parameter
unset($this->parameters['action']);
$parameters = array_merge($this->parameters, (array)$parameters);
$method = $request->getMethod();
$action = isset($parameters['action']) ? $parameters['action'] : null;
unset($parameters['action']);
// Delete
if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
return $this->call($this->methodNames['destroy']);
}
$method = $request->getMethod();
// Update
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
return $this->call($this->methodNames['update']);
}
// Delete
if (isset($parameters['id']) && $method === static::REQUEST_TYPE_DELETE) {
return $this->call('destroy', $parameters);
}
// Edit
if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
return $this->call($this->methodNames['edit']);
}
// Update
if (isset($parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT])) {
return $this->call('update', $parameters);
}
// Create
if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
return $this->call($this->methodNames['create']);
}
// Edit
if (isset($parameters['id']) && strtolower($action) === 'edit' && $method === static::REQUEST_TYPE_GET) {
return $this->call('edit', $parameters);
}
// Save
if ($method === static::REQUEST_TYPE_POST) {
return $this->call($this->methodNames['store']);
}
// Create
if (strtolower($action) === 'create' && $method === static::REQUEST_TYPE_GET) {
return $this->call('create', $parameters);
}
// Show
if ($method === static::REQUEST_TYPE_GET && $id !== null) {
return $this->call($this->methodNames['show']);
}
// Save
if ($method === static::REQUEST_TYPE_POST) {
return $this->call('store', $parameters);
}
// Index
return $this->call($this->methodNames['index']);
}
// Show
if (isset($parameters['id']) && $method === static::REQUEST_TYPE_GET) {
return $this->call('show', $parameters);
}
/**
* @return string
*/
public function getController()
{
return $this->controller;
}
// Index
return $this->call('index', $parameters);
}
/**
* @param string $controller
* @return static
*/
public function setController($controller)
{
$this->controller = $controller;
return null;
}
return $this;
}
/**
* @return string
*/
public function getController()
{
return $this->controller;
}
public function setName($name)
{
$this->name = $name;
/**
* @param string $controller
* @return static
*/
public function setController($controller)
{
$this->controller = $controller;
$this->names = [
'index' => $this->name . '.index',
'create' => $this->name . '.create',
'store' => $this->name . '.store',
'show' => $this->name . '.show',
'edit' => $this->name . '.edit',
'update' => $this->name . '.update',
'destroy' => $this->name . '.destroy',
];
return $this;
}
return $this;
}
public function setName($name)
{
$this->name = $name;
/**
* Define custom method name for resource controller
*
* @param array $names
* @return static $this
*/
public function setMethodNames(array $names)
{
$this->methodNames = $names;
$this->names = [
'index' => $this->name . '.index',
'create' => $this->name . '.create',
'store' => $this->name . '.store',
'show' => $this->name . '.show',
'edit' => $this->name . '.edit',
'update' => $this->name . '.update',
'destroy' => $this->name . '.destroy',
];
return $this;
}
return $this;
}
/**
* Get method names
*
* @return array $this
*/
public function getMethodNames()
{
return $this->methodNames;
}
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['names'])) {
$this->names = $values['names'];
}
/**
* Merge with information from another route.
*
* @param array $values
* @param bool $merge
* @return static
*/
public function setSettings(array $values, $merge = false)
{
if (isset($values['names'])) {
$this->names = $values['names'];
}
parent::setSettings($values, $merge);
if (isset($values['methods'])) {
$this->methodNames = $values['methods'];
}
return $this;
}
parent::setSettings($values, $merge);
return $this;
}
}
+22 -35
View File
@@ -5,45 +5,32 @@ use Pecee\Http\Request;
class RouteUrl extends LoadableRoute
{
public function __construct($url, $callback)
{
$this->setUrl($url);
$this->setCallback($callback);
}
public function __construct($url, $callback)
{
$this->setUrl($url);
$this->setCallback($callback);
}
public function matchRoute(Request $request)
{
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
public function matchRoute($url, Request $request)
{
$url = parse_url(urldecode($url), PHP_URL_PATH);
$url = rtrim($url, '/') . '/';
// Match on custom defined regular expression
if ($this->regex !== null) {
$parameters = [];
if (preg_match($this->regex, $request->getHost() . $url, $parameters)) {
/* Remove global match */
if(count($parameters) > 1) {
array_shift($parameters);
$this->parameters = $parameters;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
if ($regexMatch === false) {
return false;
}
return true;
}
/* Make regular expression based on route */
$parameters = $this->parseParameters($this->url, $url);
if ($parameters === null) {
return false;
}
return null;
}
$this->setParameters($parameters);
// Make regular expression based on route
$route = rtrim($this->url, '/') . '/';
$parameters = $this->parseParameters($route, $url);
if ($parameters !== null) {
$this->parameters = array_merge($this->parameters, $parameters);
return true;
}
return null;
}
return true;
}
}
File diff suppressed because it is too large Load Diff
+334 -307
View File
@@ -21,354 +21,381 @@ use Pecee\SimpleRouter\Route\RouteUrl;
class SimpleRouter
{
/**
* Default namespace added to all routes
* @var string
*/
protected static $defaultNamespace;
/**
* Default namespace added to all routes
* @var string
*/
protected static $defaultNamespace;
/**
* The response object
* @var Response
*/
protected static $response;
/**
* The response object
* @var Response
*/
protected static $response;
/**
* Start/route request
*
* @throws HttpException
* @throws NotFoundHttpException
*/
public static function start()
{
static::router()->routeRequest();
}
protected static $router;
/**
* Set default namespace which will be prepended to all routes.
*
* @param string $defaultNamespace
*/
public static function setDefaultNamespace($defaultNamespace)
{
static::$defaultNamespace = $defaultNamespace;
}
/**
* Start/route request
*
* @throws HttpException
* @throws NotFoundHttpException
*/
public static function start()
{
static::router()->routeRequest();
}
/**
* Base CSRF verifier
*
* @param BaseCsrfVerifier $baseCsrfVerifier
*/
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
{
static::router()->setCsrfVerifier($baseCsrfVerifier);
}
/**
* Set default namespace which will be prepended to all routes.
*
* @param string $defaultNamespace
*/
public static function setDefaultNamespace($defaultNamespace)
{
static::$defaultNamespace = $defaultNamespace;
}
/**
* Boot managers allows you to alter the routes before the routing occurs.
* Perfect if you want to load pretty-urls from a file or database.
*
* @param IRouterBootManager $bootManager
*/
public static function addBootManager(IRouterBootManager $bootManager)
{
static::router()->addBootManager($bootManager);
}
/**
* Base CSRF verifier
*
* @param BaseCsrfVerifier $baseCsrfVerifier
*/
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier)
{
static::router()->setCsrfVerifier($baseCsrfVerifier);
}
/**
* Route the given url to your callback on GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function get($url, $callback, array $settings = null)
{
return static::match(['get'], $url, $callback, $settings);
}
/**
* Boot managers allows you to alter the routes before the routing occurs.
* Perfect if you want to load pretty-urls from a file or database.
*
* @param IRouterBootManager $bootManager
*/
public static function addBootManager(IRouterBootManager $bootManager)
{
static::router()->addBootManager($bootManager);
}
/**
* Route the given url to your callback on POST request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function post($url, $callback, array $settings = null)
{
return static::match(['post'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function get($url, $callback, array $settings = null)
{
return static::match(['get'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PUT request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function put($url, $callback, array $settings = null)
{
return static::match(['put'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on POST request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function post($url, $callback, array $settings = null)
{
return static::match(['post'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PATCH request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function patch($url, $callback, array $settings = null)
{
return static::match(['patch'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PUT request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function put($url, $callback, array $settings = null)
{
return static::match(['put'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on OPTIONS request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function options($url, $callback, array $settings = null)
{
return static::match(['options'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on PATCH request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function patch($url, $callback, array $settings = null)
{
return static::match(['patch'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on DELETE request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function delete($url, $callback, array $settings = null)
{
return static::match(['delete'], $url, $callback, $settings);
}
/**
* Route the given url to your callback on OPTIONS request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function options($url, $callback, array $settings = null)
{
return static::match(['options'], $url, $callback, $settings);
}
/**
* Groups allows for encapsulating routes with special settings.
*
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RouteGroup
*/
public static function group(array $settings = [], \Closure $callback)
{
$group = new RouteGroup();
$group->setCallback($callback);
$group->setSettings($settings);
/**
* Route the given url to your callback on DELETE request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function delete($url, $callback, array $settings = null)
{
return static::match(['delete'], $url, $callback, $settings);
}
if (is_callable($callback) === false) {
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
/**
* Groups allows for encapsulating routes with special settings.
*
* @param array $settings
* @param \Closure $callback
* @throws \InvalidArgumentException
* @return RouteGroup
*/
public static function group(array $settings = [], \Closure $callback)
{
$group = new RouteGroup();
$group->setCallback($callback);
$group->setSettings($settings);
static::router()->addRoute($group);
if (is_callable($callback) === false) {
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
}
return $group;
}
static::router()->addRoute($group);
/**
* Alias for the form method
*
* @param string $url
* @param callable $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function basic($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
return $group;
}
/**
* This type will route the given url to your callback on the provided request methods.
* Route the given url to your callback on POST and GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function form($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
/**
* Alias for the form method
*
* @param string $url
* @param callable $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function basic($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
/**
* This type will route the given url to your callback on the provided request methods.
*
* @param array $requestMethods
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function match(array $requestMethods, $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
$route = static::addDefaultNamespace($route);
/**
* This type will route the given url to your callback on the provided request methods.
* Route the given url to your callback on POST and GET request method.
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @see SimpleRouter::form
* @return RouteUrl
*/
public static function form($url, $callback, array $settings = null)
{
return static::match(['get', 'post'], $url, $callback, $settings);
}
if ($settings !== null) {
$route->setSettings($settings);
}
/**
* This type will route the given url to your callback on the provided request methods.
*
* @param array $requestMethods
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function match(array $requestMethods, $url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route->setRequestMethods($requestMethods);
$route = static::addDefaultNamespace($route);
static::router()->addRoute($route);
if ($settings !== null) {
$route->setSettings($settings);
}
return $route;
}
static::router()->addRoute($route);
/**
* This type will route the given url to your callback and allow any type of request method
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function all($url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route);
return $route;
}
if ($settings !== null) {
$route->setSettings($settings);
}
/**
* This type will route the given url to your callback and allow any type of request method
*
* @param string $url
* @param string|\Closure $callback
* @param array|null $settings
* @return RouteUrl
*/
public static function all($url, $callback, array $settings = null)
{
$route = new RouteUrl($url, $callback);
$route = static::addDefaultNamespace($route);
static::router()->addRoute($route);
if ($settings !== null) {
$route->setSettings($settings);
}
return $route;
}
static::router()->addRoute($route);
/**
* This route will route request from the given url to the controller.
*
* @param string $url
* @param string $controller
* @param array|null $settings
* @return RouteController
*/
public static function controller($url, $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
return $route;
}
if ($settings !== null) {
$route->setSettings($settings);
}
/**
* This route will route request from the given url to the controller.
*
* @param string $url
* @param string $controller
* @param array|null $settings
* @return RouteController
*/
public static function controller($url, $controller, array $settings = null)
{
$route = new RouteController($url, $controller);
$route = static::addDefaultNamespace($route);
static::router()->addRoute($route);
if ($settings !== null) {
$route->setSettings($settings);
}
return $route;
}
static::router()->addRoute($route);
/**
* This type will route all REST-supported requests to different methods in the provided controller.
*
* @param string $url
* @param string $controller
* @param array|null $settings
* @return RouteResource
*/
public static function resource($url, $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
return $route;
}
if ($settings !== null) {
$route->setSettings($settings);
}
/**
* This type will route all REST-supported requests to different methods in the provided controller.
*
* @param string $url
* @param string $controller
* @param array|null $settings
* @return RouteResource
*/
public static function resource($url, $controller, array $settings = null)
{
$route = new RouteResource($url, $controller);
$route = static::addDefaultNamespace($route);
static::router()->addRoute($route);
if ($settings !== null) {
$route->setSettings($settings);
}
return $route;
}
static::router()->addRoute($route);
/**
* Get url for a route by using either name/alias, class or method name.
*
* The name parameter supports the following values:
* - Route name
* - Controller/resource name (with or without method)
* - Controller class name
*
* When searching for controller/resource by name, you can use this syntax "route.name@method".
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
* If no arguments is specified, it will return the url for the current loaded route.
*
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @return string
*/
public static function getUrl($name = null, $parameters = null, $getParams = null)
{
return static::router()->getUrl($name, $parameters, $getParams);
}
return $route;
}
/**
* Get the request
*
* @return \Pecee\Http\Request
*/
public static function request()
{
return static::router()->getRequest();
}
/**
* Get url for a route by using either name/alias, class or method name.
*
* The name parameter supports the following values:
* - Route name
* - Controller/resource name (with or without method)
* - Controller class name
*
* When searching for controller/resource by name, you can use this syntax "route.name@method".
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
* If no arguments is specified, it will return the url for the current loaded route.
*
* @param string|null $name
* @param string|array|null $parameters
* @param array|null $getParams
* @throws \Exception
* @return string
*/
public static function getUrl($name = null, $parameters = null, $getParams = null)
{
return static::router()->getUrl($name, $parameters, $getParams);
}
/**
* Get the response object
*
* @return Response
*/
public static function response()
{
if (static::$response === null) {
static::$response = new Response(static::request());
}
/**
* Get the request
*
* @return \Pecee\Http\Request
*/
public static function request()
{
return static::router()->getRequest();
}
return static::$response;
}
/**
* Get the response object
*
* @return Response
*/
public static function response()
{
if (static::$response === null) {
static::$response = new Response(static::request());
}
/**
* Returns the router instance
*
* @return Router
*/
public static function router()
{
return Router::getInstance();
}
return static::$response;
}
/**
* Prepends the default namespace to all new routes added.
*
* @param IRoute $route
* @return IRoute
*/
protected static function addDefaultNamespace(IRoute $route)
{
if (static::$defaultNamespace !== null) {
$namespace = static::$defaultNamespace;
/**
* Returns the router instance
*
* @return Router
*/
public static function router()
{
if(static::$router === null) {
static::$router = new Router();
}
if ($route->getNamespace() !== null) {
$namespace .= '\\' . $route->getNamespace();
}
return static::$router;
}
$route->setDefaultNamespace($namespace);
}
/**
* Prepends the default namespace to all new routes added.
*
* @param IRoute $route
* @return IRoute
*/
protected static function addDefaultNamespace(IRoute $route)
{
if (static::$defaultNamespace !== null) {
return $route;
}
$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);
}
}
return $route;
}
/**
* Get default namespace
* @return string
*/
public static function getDefaultNamespace()
{
return static::$defaultNamespace;
}
}
+20 -10
View File
@@ -2,24 +2,34 @@
class DummyController
{
public function start()
public function method1()
{
echo static::class . '@' . 'start() OK';
}
public function method2()
{
}
public function param($params = null)
{
$params = func_get_args();
echo 'Params: ' . join(', ', $params);
echo join(', ', func_get_args());
}
public function notFound()
{
echo 'not found';
}
public function getTest()
{
echo 'getTest';
}
public function silent() {
public function postTest()
{
echo 'postTest';
}
}
public function putTest()
{
echo 'putTest';
}
}
+2 -3
View File
@@ -1,12 +1,11 @@
<?php
require_once 'Exceptions/MiddlewareLoadedException.php';
use Pecee\Http\Middleware\IMiddleware;
use Pecee\Http\Request;
class DummyMiddleware implements IMiddleware
class DummyMiddleware implements \Pecee\Http\Middleware\IMiddleware
{
public function handle(Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route)
public function handle(Request $request)
{
throw new MiddlewareLoadedException('Middleware loaded!');
}
@@ -0,0 +1,4 @@
<?php
class ExceptionHandlerException extends \Exception
{
}
@@ -0,0 +1,18 @@
<?php
class ResponseException extends \Exception
{
protected $response;
public function __construct($response)
{
$this->response = $response;
parent::__construct('', 0);
}
public function getResponse()
{
return $this->response;
}
}
+2 -2
View File
@@ -2,9 +2,9 @@
class ExceptionHandler implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
throw $error;
echo $error->getMessage();
}
}
@@ -0,0 +1,14 @@
<?php
class ExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
$request->setUri('/');
return $request;
}
}
@@ -0,0 +1,14 @@
<?php
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
$request->setUri('/');
return $request;
}
}
@@ -0,0 +1,13 @@
<?php
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
{
public function handleError(\Pecee\Http\Request $request, \Exception $error)
{
global $stack;
$stack[] = static::class;
throw new ResponseException('ExceptionHandler loaded');
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
class ResourceController implements \Pecee\Controllers\IResourceController
{
public function index()
{
echo 'index';
}
public function show($id)
{
echo 'show ' . $id;
}
public function store()
{
echo 'store';
}
public function create()
{
echo 'create';
}
public function edit($id)
{
echo 'edit ' . $id;
}
public function update($id)
{
echo 'update ' . $id;
}
public function destroy($id)
{
echo 'destroy ' . $id;
}
}
+49 -61
View File
@@ -2,94 +2,82 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
require_once 'Helpers/TestRouter.php';
class GroupTest extends PHPUnit_Framework_TestCase
{
protected $result;
protected $result;
public function testGroupLoad()
{
$this->result = false;
public function testGroupLoad()
{
$this->result = false;
SimpleRouter::group(['prefix' => '/group'], function () {
$this->result = true;
});
TestRouter::group(['prefix' => '/group'], function () {
$this->result = true;
});
try {
SimpleRouter::start();
} catch (Exception $e) {
// ignore RouteNotFound exception
}
try {
TestRouter::debug('/', 'get');
} catch(\Exception $e) {
$this->assertTrue($this->result);
}
}
$this->assertTrue($this->result);
}
public function testNestedGroup()
{
public function testNestedGroup()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/api/v1/test');
SimpleRouter::request()->setMethod('get');
TestRouter::group(['prefix' => '/api'], function () {
SimpleRouter::group(['prefix' => '/api'], function () {
TestRouter::group(['prefix' => '/v1'], function () {
TestRouter::get('/test', 'DummyController@method1');
});
SimpleRouter::group(['prefix' => '/v1'], function () {
SimpleRouter::get('/test', 'DummyController@start');
});
});
});
TestRouter::debug('/api/v1/test', 'get');
SimpleRouter::start();
}
}
public function testManyRoutes()
{
public function testMultipleRoutes()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/match');
SimpleRouter::request()->setMethod('get');
TestRouter::group(['prefix' => '/api'], function () {
SimpleRouter::group(['prefix' => '/api'], function () {
TestRouter::group(['prefix' => '/v1'], function () {
TestRouter::get('/test', 'DummyController@method1');
});
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()
{
// Test array name
TestRouter::get('/my/fancy/url/1', 'DummyController@method1', ['as' => 'fancy1']);
public function testUrls()
{
// Test method name
TestRouter::get('/my/fancy/url/2', 'DummyController@method1')->setName('fancy2');
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/fancy/url/1');
SimpleRouter::request()->setMethod('get');
TestRouter::debugNoReset('/my/fancy/url/1');
// Test array name
SimpleRouter::get('/my/fancy/url/1', 'DummyController@start', ['as' => 'fancy1']);
$this->assertEquals('/my/fancy/url/1/', TestRouter::getUrl('fancy1'));
$this->assertEquals('/my/fancy/url/2/', TestRouter::getUrl('fancy2'));
// Test method name
SimpleRouter::get('/my/fancy/url/2', 'DummyController@start')->setName('fancy2');
TestRouter::router()->reset();
SimpleRouter::start();
$this->assertEquals('/my/fancy/url/1/', SimpleRouter::getUrl('fancy1'));
$this->assertEquals('/my/fancy/url/2/', SimpleRouter::getUrl('fancy2'));
}
}
}
+41
View File
@@ -0,0 +1,41 @@
<?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;
}
}
+20 -18
View File
@@ -3,30 +3,32 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
require_once 'Helpers/TestRouter.php';
class MiddlewareTest extends PHPUnit_Framework_TestCase
{
public function testMiddlewareFound()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/my/test/url');
public function testMiddlewareFound()
{
$this->setExpectedException(MiddlewareLoadedException::class);
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
});
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
});
$found = false;
TestRouter::debug('/my/test/url', 'get');
try {
SimpleRouter::start();
} catch (\Exception $e) {
$found = ($e instanceof MiddlewareLoadedException);
}
}
$this->assertTrue($found);
}
public function testNestedMiddlewareDontLoad()
{
TestRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
TestRouter::get('/middleware', 'DummyController@method1');
});
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
require_once 'Dummy/DummyController.php';
require_once 'Helpers/TestRouter.php';
class RouterControllerTest extends PHPUnit_Framework_TestCase
{
public function testGet()
{
// Match normal route on alias
TestRouter::controller('/url', 'DummyController');
$response = TestRouter::debugOutput('/url/test', 'get');
$this->assertEquals('getTest', $response);
}
public function testPost()
{
// Match normal route on alias
TestRouter::controller('/url', 'DummyController');
$response = TestRouter::debugOutput('/url/test', 'post');
$this->assertEquals('postTest', $response);
}
public function testPut()
{
// Match normal route on alias
TestRouter::controller('/url', 'DummyController');
$response = TestRouter::debugOutput('/url/test', 'put');
$this->assertEquals('putTest', $response);
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
require_once 'Dummy/ResourceController.php';
require_once 'Helpers/TestRouter.php';
class RouterResourceTest extends PHPUnit_Framework_TestCase
{
public function testResourceStore()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource', 'post');
$this->assertEquals('store', $response);
}
public function testResourceCreate()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/create', 'get');
$this->assertEquals('create', $response);
}
public function testResourceIndex()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource', 'get');
$this->assertEquals('index', $response);
}
public function testResourceDestroy()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'delete');
$this->assertEquals('destroy 38', $response);
}
public function testResourceEdit()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38/edit', 'get');
$this->assertEquals('edit 38', $response);
}
public function testResourceUpdate()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'put');
$this->assertEquals('update 38', $response);
}
public function testResourceGet()
{
TestRouter::resource('/resource', 'ResourceController');
$response = TestRouter::debugOutput('/resource/38', 'get');
$this->assertEquals('show 38', $response);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?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);
}
}
+91 -104
View File
@@ -2,140 +2,127 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException as NotFoundHttpException;
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
require_once 'Helpers/TestRouter.php';
class RouterRouteTest extends PHPUnit_Framework_TestCase
{
protected $result = false;
protected $result = false;
public function testNotFound()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test-param1-param2');
public function testMultiParam()
{
TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
SimpleRouter::get('/non-existing-path', 'DummyController@start');
});
if ($param1 === 'param1' && $param2 === 'param2') {
$this->result = true;
}
$found = false;
});
try {
SimpleRouter::start();
} catch (\Exception $e) {
$found = ($e instanceof NotFoundHttpException && $e->getCode() == 404);
}
TestRouter::debug('/test-param1-param2', 'get');
$this->assertTrue($found);
}
$this->assertTrue($this->result);
public function testGet()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('get');
}
SimpleRouter::get('/my/test/url', 'DummyController@start');
SimpleRouter::start();
}
public function testNotFound()
{
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
TestRouter::get('/non-existing-path', 'DummyController@method1');
TestRouter::debug('/test-param1-param2', 'post');
}
public function testPost()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('post');
public function testGet()
{
TestRouter::get('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'get');
}
SimpleRouter::post('/my/test/url', 'DummyController@start');
SimpleRouter::start();
}
public function testPost()
{
TestRouter::post('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', 'post');
}
public function testPut()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('put');
public function testPut()
{
TestRouter::put('/my/test/url', 'DummyController@method1');
TestRouter::debug('/my/test/url', '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');
}
public function testDelete()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('delete');
public function testMethodNotAllowed()
{
TestRouter::get('/my/test/url', 'DummyController@method1');
SimpleRouter::delete('/my/test/url', 'DummyController@start');
SimpleRouter::start();
}
try {
TestRouter::debug('/my/test/url', 'post');
} catch (\Exception $e) {
$this->assertEquals(403, $e->getCode());
}
}
public function testMethodNotAllowed()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setUri('/my/test/url');
SimpleRouter::request()->setMethod('post');
public function testSimpleParam()
{
TestRouter::get('/test-{param1}', 'DummyController@param');
$response = TestRouter::debugOutput('/test-param1', 'get');
SimpleRouter::get('/my/test/url', 'DummyController@start');
$this->assertEquals('param1', $response);
}
try {
SimpleRouter::start();
} catch (\Exception $e) {
$this->assertEquals(403, $e->getCode());
}
}
public function testPathParamRegex()
{
TestRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
$response = TestRouter::debugOutput('/test/path/123123', 'get');
public function testSimpleParam()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test-param1');
$this->assertEquals('123123', $response);
}
SimpleRouter::get('/test-{param1}', 'DummyController@param');
SimpleRouter::start();
}
public function testDomainAllowedRoute()
{
$this->result = false;
public function testMultiParam()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test-param1-param2');
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
TestRouter::get('/test', function ($subdomain = null) {
$this->result = ($subdomain === 'hello');
});
});
SimpleRouter::get('/test-{param1}-{param2}', 'DummyController@param');
SimpleRouter::start();
}
TestRouter::request()->setHost('hello.world.com');
TestRouter::debug('/test', 'get');
public function testPathParamRegex()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test/path/123123');
$this->assertTrue($this->result);
SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
SimpleRouter::start();
}
}
public function testDomainRoute()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/test');
SimpleRouter::request()->setHost('hello.world.com');
public function testDomainNotAllowedRoute()
{
$this->result = false;
$this->result = false;
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
TestRouter::get('/test', function ($subdomain = null) {
$this->result = ($subdomain === 'hello');
});
});
SimpleRouter::group(['domain' => '{subdomain}.world.com'], function () {
SimpleRouter::get('/test', function ($subdomain = null) {
$this->result = ($subdomain === 'hello');
});
});
TestRouter::request()->setHost('other.world.com');
SimpleRouter::start();
$this->assertTrue($this->result);
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');
}
}
+65 -60
View File
@@ -3,99 +3,104 @@
require_once 'Dummy/DummyMiddleware.php';
require_once 'Dummy/DummyController.php';
require_once 'Dummy/Handler/ExceptionHandler.php';
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
require_once 'Helpers/TestRouter.php';
class RouterUrlTest extends PHPUnit_Framework_TestCase
{
protected $result = false;
protected function getUrl($name = null, $parameters = null, array $getParams = []) {
return SimpleRouter::getUrl($name, $parameters, $getParams);
}
public function testSimularUrls()
{
// Match normal route on alias
TestRouter::resource('/url11', 'DummyController@method1');
TestRouter::resource('/url1', 'DummyController@method1', ['as' => 'match']);
public function testUrls()
{
SimpleRouter::router()->reset();
SimpleRouter::request()->setMethod('get');
SimpleRouter::request()->setUri('/');
TestRouter::debugNoReset('/url1', 'get');
// Match normal route on alias
SimpleRouter::get('/', 'DummyController@silent', ['as' => 'home']);
$this->assertEquals(TestRouter::getUrl('match'), TestRouter::getUrl());
SimpleRouter::get('/about', 'DummyController@about');
TestRouter::router()->reset();
}
SimpleRouter::group(['prefix' => '/admin', 'as' => 'admin'], function() {
public function testUrls()
{
// Match normal route on alias
TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
// Match route with prefix on alias
SimpleRouter::get('/{id?}', 'DummyController@start', ['as' => 'home']);
TestRouter::get('/about', 'DummyController@about');
// Match controller with prefix and alias
SimpleRouter::controller('/users', 'DummyController', ['as' => 'users']);
TestRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
// Match controller with prefix and NO alias
SimpleRouter::controller('/pages', 'DummyController');
// Match route with prefix on alias
TestRouter::get('/{id?}', 'DummyController@method2', ['as' => 'home']);
});
// Match controller with prefix and alias
TestRouter::controller('/users', 'DummyController', ['as' => 'users']);
SimpleRouter::group(['prefix' => 'api', 'as' => 'api'], function() {
// Match controller with prefix and NO alias
TestRouter::controller('/pages', 'DummyController');
// Match resource controller
SimpleRouter::resource('phones', 'DummyController');
});
});
TestRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
SimpleRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
// Match resource controller
TestRouter::resource('phones', 'DummyController');
// Match controller with no prefix and no alias
SimpleRouter::controller('/cats', 'CatsController');
});
// Pretend to load page
SimpleRouter::start();
TestRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
$this->assertEquals('/gadgets/iphoneinfo/', $this->getUrl('gadgets.iphone'));
// Match controller with no prefix and no alias
TestRouter::controller('/cats', 'CatsController');
$this->assertEquals('/api/phones/create/', $this->getUrl('api.phones.create'));
// Pretend to load page
TestRouter::debugNoReset('/', 'get');
// Should match /
$this->assertEquals('/', $this->getUrl('home'));
$this->assertEquals('/gadgets/iphoneinfo/', TestRouter::getUrl('gadgets.iphone'));
// Should match /about/
$this->assertEquals('/about/', $this->getUrl('DummyController@about'));
$this->assertEquals('/api/phones/create/', TestRouter::getUrl('api.phones.create'));
// Should match /admin/
$this->assertEquals('/admin/', $this->getUrl('DummyController@start'));
// Should match /
$this->assertEquals('/', TestRouter::getUrl('home'));
// Should match /admin/
$this->assertEquals('/admin/', $this->getUrl('admin.home'));
// Should match /about/
$this->assertEquals('/about/', TestRouter::getUrl('DummyController@about'));
// Should match /admin/2/
$this->assertEquals('/admin/2/', $this->getUrl('admin.home', ['id' => 2]));
// Should match /admin/
$this->assertEquals('/admin/', TestRouter::getUrl('DummyController@method2'));
// Should match /admin/users/
$this->assertEquals('/admin/users/', $this->getUrl('admin.users'));
// Should match /admin/
$this->assertEquals('/admin/', TestRouter::getUrl('admin.home'));
// Should match /admin/users/home/
$this->assertEquals('/admin/users/home/', $this->getUrl('admin.users@home'));
// Should match /admin/2/
$this->assertEquals('/admin/2/', TestRouter::getUrl('admin.home', ['id' => 2]));
// Should match /cats/
$this->assertEquals('/cats/', $this->getUrl('CatsController'));
// Should match /admin/users/
$this->assertEquals('/admin/users/', TestRouter::getUrl('admin.users'));
// Should match /cats/view/
$this->assertEquals('/cats/view/', $this->getUrl('CatsController', 'view'));
// Should match /admin/users/home/
$this->assertEquals('/admin/users/home/', TestRouter::getUrl('admin.users@home'));
// Should match /cats/view/
//$this->assertEquals('/cats/view/', $this->getUrl('CatsController', ['view']));
// Should match /cats/
$this->assertEquals('/cats/', TestRouter::getUrl('CatsController'));
// Should match /cats/view/666
$this->assertEquals('/cats/view/666/', $this->getUrl('CatsController@getView', ['666']));
// Should match /cats/view/
$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', 'view'));
// Should match /funny/man/
$this->assertEquals('/funny/man/', $this->getUrl('/funny/man'));
// Should match /cats/view/
//$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', ['view']));
// Should match /?jackdaniels=true&cola=yeah
$this->assertEquals('/?jackdaniels=true&cola=yeah', $this->getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
// Should match /cats/view/666
$this->assertEquals('/cats/view/666/', TestRouter::getUrl('CatsController@getView', ['666']));
}
// Should match /funny/man/
$this->assertEquals('/funny/man/', TestRouter::getUrl('/funny/man'));
// Should match /?jackdaniels=true&cola=yeah
$this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
TestRouter::router()->reset();
}
}