mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
77 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 933f2370fe | |||
| b3f8910cab | |||
| 8557741083 | |||
| c60d7d81c1 | |||
| 637b998f02 | |||
| aca7d3d503 | |||
| 846c9e6584 | |||
| 0df469184c | |||
| 649ed28a91 | |||
| 5cb7086e96 | |||
| a2edc1504c | |||
| d31cda8e70 | |||
| 921f050a31 | |||
| dcbf59b305 | |||
| bc16388613 | |||
| d3ed3a61b5 | |||
| 969b64650e | |||
| c2cf2334e7 | |||
| af730e6e15 | |||
| f5a32cf520 | |||
| 1843ea0594 | |||
| fd28f4549f | |||
| 5e5a424ee8 | |||
| 099f04fc10 | |||
| ac2993f804 | |||
| 99da70874e | |||
| 2a66350883 | |||
| c95a5291d3 | |||
| 20fc067765 | |||
| cbb4294f58 | |||
| d6bdcbe70c | |||
| 25f569384f | |||
| b37c73d5dd | |||
| f5597c24ce | |||
| b8061f2aa7 | |||
| 6c7ac2b250 | |||
| d2de22e5e0 | |||
| 252fb16326 | |||
| 63dfbb24af | |||
| 3ccfac9422 | |||
| 8f2d49fb73 | |||
| bdb5b2dead | |||
| 5d643d842a | |||
| d6cf5c9b68 | |||
| 03cac14e8e | |||
| f49fa5dca2 | |||
| 9d6a3c328f | |||
| 1ba05b923c | |||
| c221381c02 | |||
| b173659657 | |||
| 961d73a13f | |||
| 54ae628f4e | |||
| 7a23ac0b2e | |||
| b555eb07a6 | |||
| 8959a237f9 | |||
| 0a70a1aa1a | |||
| 58e4eb85bb | |||
| a497c36ea4 | |||
| 8db60f85a1 | |||
| 626a3b2f6a | |||
| 7863df6325 | |||
| 2524428926 | |||
| 06202612d4 | |||
| ed66bc919b | |||
| 3e175d234d | |||
| 37b8090dac | |||
| c1a6c63dc7 | |||
| b3b362a9e6 | |||
| 0650e5ba93 | |||
| ff8f94ff08 | |||
| aa73f887b1 | |||
| 4edf6aaa6e | |||
| b6f0f6899a | |||
| 93d8c26416 | |||
| aec1f5f10c | |||
| 8064b5f536 | |||
| 5c81da7b77 |
@@ -1,7 +1,5 @@
|
||||
# Simple PHP router
|
||||
Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.
|
||||
|
||||
**Please note: this project has just been added and is still a work in progress. Please use with caution until a stable release version is available :)**
|
||||
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the Laravel router.
|
||||
|
||||
## Installation
|
||||
Add the latest version pf Simple PHP Router to your ```composer.json```
|
||||
@@ -17,6 +15,26 @@ Add the latest version pf Simple PHP Router to your ```composer.json```
|
||||
}
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
### Features
|
||||
|
||||
- Basic routing (get, post, put, delete) with support for custom multiple verbs.
|
||||
- Regular Expression Constraints for parameters.
|
||||
- Named routes.
|
||||
- Generating url to routes.
|
||||
- Route groups.
|
||||
- Middleware (classes that intercepts before the route is rendered).
|
||||
- Namespaces.
|
||||
- Route prefixes.
|
||||
- CSRF protection.
|
||||
|
||||
### Features currently "in-the-works"
|
||||
|
||||
- Global Constraints
|
||||
- Sub-Domain Routing
|
||||
- Optional parameters
|
||||
|
||||
## Initialising the router
|
||||
|
||||
In your ```index.php``` require your ```routes.php``` and call the ```routeRequest()``` method when all your custom routes has been loaded. This will trigger and do the actual routing of the requests.
|
||||
@@ -36,7 +54,7 @@ SimpleRouter::init($defaultControllerNamespace);
|
||||
```
|
||||
|
||||
## Adding routes
|
||||
Remember the ```routes.php``` file you required in your ```index.php```? This file will contain all your custom rules for routing.
|
||||
Remember the ```routes.php``` file you required in your ```index.php```? This file will contain all your custom rules for routing.
|
||||
This router is heavily inspired by the Laravel 5.* router, so anything you find in the Laravel documentation should work here as well.
|
||||
|
||||
### Basic example
|
||||
@@ -46,8 +64,8 @@ use Pecee\SimpleRouter\SimpleRouter;
|
||||
|
||||
/*
|
||||
* This route will match the url /v1/services/answers/1/
|
||||
|
||||
* The middleware is just a class that renders before the
|
||||
|
||||
* The middleware is just a class that renders before the
|
||||
* Controller or callback is loaded. This is useful for stopping
|
||||
* the request, for instance if a user is not authenticated.
|
||||
*/
|
||||
@@ -56,14 +74,21 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
|
||||
|
||||
SimpleRouter::group(['prefix' => 'services'], function() {
|
||||
|
||||
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show');
|
||||
|
||||
// Resetful ressource
|
||||
SimpleRouter::ressource('/rest', 'ControllerRessource');
|
||||
|
||||
SimpleRouter::get('/answers/{id}', 'ControllerAnswers@show')
|
||||
->where(['id' => '[0-9]+');
|
||||
|
||||
/**
|
||||
* This example will route url when matching the regular expression to the method.
|
||||
* For example route: /ajax/music/world -> ControllerAjax@process (parameter: music/world)
|
||||
*/
|
||||
SimpleRouter::all('/ajax', 'ControllerAjax@process')->match('ajax\\/([A-Za-z0-9\\/]+)');
|
||||
|
||||
// Resetful resource
|
||||
SimpleRouter::resource('/rest', 'ControllerRessource');
|
||||
|
||||
// Load the entire controller (where url matches method names - getIndex(), postIndex() etc)
|
||||
SimpleRouter::controller('/controller', 'ControllerDefault');
|
||||
|
||||
|
||||
// Example of providing callback instead of Controller
|
||||
SimpleRouter::get('/something', function() {
|
||||
die('Callback example');
|
||||
@@ -75,7 +100,7 @@ SimpleRouter::group(['prefix' => 'v1', 'middleware' => '\MyWebsite\Middleware\So
|
||||
|
||||
### Doing it the object oriented (hardcore) way
|
||||
|
||||
The ```SimpleRouter``` class referenced in the previous example, is just a simple helper class that knows how to communicate with the ```RouterBase``` class.
|
||||
The ```SimpleRouter``` class referenced in the previous example, is just a simple helper class that knows how to communicate with the ```RouterBase``` class.
|
||||
If you are up for a challenge, want the full control or simply just want to create your own ```Router``` helper class, this example is for you.
|
||||
|
||||
```php
|
||||
@@ -123,8 +148,11 @@ class Router extends SimpleRouter {
|
||||
// Init locale settings
|
||||
Locale::getInstance();
|
||||
|
||||
// Set default namespace
|
||||
// Set default namespace for routes
|
||||
$defaultNamespace = '\\'.Registry::getInstance()->get('AppName') . '\\Controller';
|
||||
|
||||
// Add custom csrf verifier (must extend BaseCsrfVerifier)
|
||||
parent::csrfVerifier('MyProject\Middleware\CustomCsrfVerifier');
|
||||
|
||||
// Handle exceptions
|
||||
try {
|
||||
@@ -156,17 +184,62 @@ function url($controller, $parameters = null, $getParams = null) {
|
||||
}
|
||||
```
|
||||
|
||||
In ```routes.php``` we have added this route:
|
||||
This is a basic example for getting the current csrf token
|
||||
|
||||
```SimpleRouter::get('/item/{id}', 'myController@show');```
|
||||
```php
|
||||
/**
|
||||
* Get current csrf-token
|
||||
* @return null|string
|
||||
*/
|
||||
function csrf_token() {
|
||||
$token = new \Pecee\CsrfToken();
|
||||
return $token->getToken();
|
||||
}
|
||||
```
|
||||
|
||||
In the template we then call:
|
||||
## Getting urls
|
||||
|
||||
```url('myController@show', ['id' => 22], ['category' => 'shoes']);```
|
||||
**In ```routes.php``` we have added this route:**
|
||||
|
||||
Result url is:
|
||||
```php
|
||||
SimpleRouter::get('/item/{id}', 'myController@show', ['as' => 'item']);
|
||||
```
|
||||
|
||||
```/item/22?category=shoes ```
|
||||
**In the template we then call:**
|
||||
|
||||
```php
|
||||
url('item', ['id' => 22], ['category' => 'shoes']);
|
||||
```
|
||||
|
||||
**Result url is:**
|
||||
|
||||
```php
|
||||
/item/22/?category=shoes
|
||||
```
|
||||
|
||||
## Custom CSRF verifier
|
||||
|
||||
Create a new class and extend the ```BaseCsrfVerifier``` middleware class provided with simple-php-router.
|
||||
|
||||
Add the property ```except``` with an array of the urls to the routes you would like to exclude from the CSRF validation. Using ```*``` at the end for the url will match the entire url.
|
||||
|
||||
Querystrings are ignored.
|
||||
|
||||
```php
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
|
||||
class CsrfVerifier extends BaseCsrfVerifier {
|
||||
|
||||
protected $except = ['/companies/*', '/user/save'];
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Register the new class in your ```routes.php```, custom ```Router``` class or wherever you register your routes.
|
||||
|
||||
```php
|
||||
SimpleRouter::csrfVerifier(new \Demo\Middleware\CsrfVerifier());
|
||||
```
|
||||
|
||||
## Documentation
|
||||
While I work on a better documentation, please refer to the Laravel 5 routing documentation here:
|
||||
@@ -174,4 +247,26 @@ While I work on a better documentation, please refer to the Laravel 5 routing do
|
||||
http://laravel.com/docs/5.1/routing
|
||||
|
||||
## Easily extendable
|
||||
The router can be easily extended to customize your needs.
|
||||
The router can be easily extended to customize your needs.
|
||||
|
||||
## The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Simon Sessing� / simple-php-router
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Pecee\\": "src/"
|
||||
"Pecee\\": "src/Pecee/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
namespace Pecee;
|
||||
|
||||
class CsrfToken {
|
||||
|
||||
const CSRF_KEY = 'XSRF-TOKEN';
|
||||
|
||||
protected $token;
|
||||
|
||||
public function __construct() {
|
||||
if($this->getToken() === null) {
|
||||
$this->setToken($this->generateToken());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set csrf token cookie
|
||||
*
|
||||
* @param $token
|
||||
*/
|
||||
public function setToken($token) {
|
||||
setcookie(self::CSRF_KEY, $token, time() + 60 * 120, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get csrf token
|
||||
* @return string|null
|
||||
*/
|
||||
public function getToken(){
|
||||
if(isset($_COOKIE[self::CSRF_KEY])) {
|
||||
return $_COOKIE[self::CSRF_KEY];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?php
|
||||
namespace Pecee\Exception;
|
||||
|
||||
class TokenMismatchException extends \Exception {}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\CsrfToken;
|
||||
use Pecee\Exception\TokenMismatchException;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class BaseCsrfVerifier implements IMiddleware {
|
||||
|
||||
const POST_KEY = 'csrf-token';
|
||||
const HEADER_KEY = 'X-CSRF-TOKEN';
|
||||
|
||||
protected $except;
|
||||
protected $csrfToken;
|
||||
|
||||
|
||||
public function __construct() {
|
||||
$this->csrfToken = new CsrfToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach($this->except as $url) {
|
||||
$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) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function handle(Request $request) {
|
||||
|
||||
if($request->getMethod() != 'get' && !$this->skip($request)) {
|
||||
|
||||
$token = (isset($_POST[self::POST_KEY])) ? $_POST[self::POST_KEY] : null;
|
||||
|
||||
// If the token is not posted, check headers for valid x-csrf-token
|
||||
if($token === null) {
|
||||
$token = $request->getHeader(self::HEADER_KEY);
|
||||
}
|
||||
|
||||
if( !$this->csrfToken->validate( $token ) ) {
|
||||
throw new TokenMismatchException('Invalid csrf-token.');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
interface IMiddleware {
|
||||
public function handle(Request $request);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Request {
|
||||
|
||||
protected static $instance;
|
||||
|
||||
protected $data;
|
||||
protected $uri;
|
||||
protected $host;
|
||||
protected $method;
|
||||
protected $headers;
|
||||
|
||||
/**
|
||||
* Return new instance
|
||||
* @return static
|
||||
*/
|
||||
public static function getInstance() {
|
||||
if(self::$instance === null) {
|
||||
self::$instance = new static();
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function __construct() {
|
||||
$this->data = array();
|
||||
$this->host = $_SERVER['HTTP_HOST'];
|
||||
$this->uri = $_SERVER['REQUEST_URI'];
|
||||
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
|
||||
$this->headers = getallheaders();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getUri() {
|
||||
return $this->uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHost() {
|
||||
return $this->host;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getMethod() {
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get http basic auth user
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUser() {
|
||||
return (isset($_SERVER['PHP_AUTH_USER'])) ? $_SERVER['PHP_AUTH_USER']: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get http basic auth password
|
||||
* @return string|null
|
||||
*/
|
||||
public function getPassword() {
|
||||
return (isset($_SERVER['PHP_AUTH_PW'])) ? $_SERVER['PHP_AUTH_PW']: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get headers
|
||||
* @return array
|
||||
*/
|
||||
public function getHeaders() {
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get id address
|
||||
* @return string
|
||||
*/
|
||||
public function getIp() {
|
||||
return isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get referer
|
||||
* @return string
|
||||
*/
|
||||
public function getReferer() {
|
||||
return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user agent
|
||||
* @return string
|
||||
*/
|
||||
public function getUserAgent() {
|
||||
return isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get header value by name
|
||||
* @param string $name
|
||||
* @return string|null
|
||||
*/
|
||||
public function getHeader($name) {
|
||||
return (isset($this->headers[$name])) ? $this->headers[$name] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get request input or default value
|
||||
* @param string $name
|
||||
* @param string $defaultValue
|
||||
* @return mixed
|
||||
*/
|
||||
public function getInput($name, $defaultValue) {
|
||||
return (isset($_REQUEST[$name]) ? $_REQUEST[$name] : $defaultValue);
|
||||
}
|
||||
|
||||
public function __set($name, $value = null) {
|
||||
$this->data[$name] = $value;
|
||||
}
|
||||
|
||||
public function __get($name) {
|
||||
return isset($this->data[$name]) ? $this->data[$name] : null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Response {
|
||||
|
||||
/**
|
||||
* Set the http status code
|
||||
*
|
||||
* @param int $code
|
||||
* @return self $this
|
||||
*/
|
||||
public function httpCode($code) {
|
||||
http_response_code($code);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect the response
|
||||
*
|
||||
* @param string $url
|
||||
*/
|
||||
public function redirect($url) {
|
||||
$this->header('Location: ' . $url);
|
||||
die();
|
||||
}
|
||||
|
||||
public function refresh() {
|
||||
$this->redirect(url());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add http authorisation
|
||||
* @param string $name
|
||||
* @return self $this
|
||||
*/
|
||||
public function auth($name = '') {
|
||||
$this->headers([
|
||||
'WWW-Authenticate: Basic realm="' . $name . '"',
|
||||
'HTTP/1.0 401 Unauthorized'
|
||||
]);
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function cache($duration = 2592000) {
|
||||
$this->headers([
|
||||
'Cache-Control: public,max-age='.$duration.',must-revalidate',
|
||||
'Expires: '.gmdate('D, d M Y H:i:s',(time()+$duration)).' GMT',
|
||||
'Last-modified: '.gmdate('D, d M Y H:i:s',time()).' GMT'
|
||||
]);
|
||||
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 self $this
|
||||
*/
|
||||
public function header($value) {
|
||||
header($value);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple headers to response
|
||||
* @param array $headers
|
||||
* @return self $this
|
||||
*/
|
||||
public function headers(array $headers) {
|
||||
foreach($headers as $header) {
|
||||
header($header);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
interface IRouteEntry {
|
||||
|
||||
}
|
||||
@@ -1,21 +1,24 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\ArrayUtil;
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\Url;
|
||||
|
||||
class RouterBase {
|
||||
|
||||
protected static $instance;
|
||||
|
||||
protected $request;
|
||||
protected $currentRoute;
|
||||
protected $routes;
|
||||
protected $processedRoutes;
|
||||
protected $controllerUrlMap;
|
||||
protected $backstack;
|
||||
protected $requestUri;
|
||||
protected $requestMethod;
|
||||
protected $loadedRoute;
|
||||
protected $defaultNamespace;
|
||||
protected $baseCsrfVerifier;
|
||||
|
||||
// TODO: make interface for controller routers, so they can be easily detected
|
||||
// TODO: clean up - cut some of the methods down to smaller pieces
|
||||
@@ -24,8 +27,8 @@ class RouterBase {
|
||||
$this->routes = array();
|
||||
$this->backstack = array();
|
||||
$this->controllerUrlMap = array();
|
||||
$this->requestUri = $_SERVER['REQUEST_URI'];
|
||||
$this->requestMethod = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
|
||||
$this->request = Request::getInstance();
|
||||
$this->baseCsrfVerifier = new BaseCsrfVerifier();
|
||||
}
|
||||
|
||||
public function addRoute(RouterEntry $route) {
|
||||
@@ -42,9 +45,8 @@ class RouterBase {
|
||||
/* @var $route RouterEntry */
|
||||
foreach($routes as $route) {
|
||||
|
||||
if($this->defaultNamespace) {
|
||||
if($this->defaultNamespace && !$route->getNamespace()) {
|
||||
$namespace = null;
|
||||
|
||||
if ($route->getNamespace()) {
|
||||
$namespace = $this->defaultNamespace . '\\' . $route->getNamespace();
|
||||
} else {
|
||||
@@ -61,15 +63,17 @@ class RouterBase {
|
||||
}
|
||||
$route->addSettings($mergedSettings);
|
||||
|
||||
if(!($route instanceof RouterGroup) && is_array($newPrefixes) && count($newPrefixes) && $backstack) {
|
||||
$route->setUrl( join('/', $newPrefixes) . $route->getUrl() );
|
||||
}
|
||||
if(!($route instanceof RouterGroup)) {
|
||||
if(is_array($newPrefixes) && count($newPrefixes) && $backstack) {
|
||||
$route->setUrl( join('/', $newPrefixes) . $route->getUrl() );
|
||||
}
|
||||
|
||||
$this->controllerUrlMap[] = $route;
|
||||
$this->controllerUrlMap[] = $route;
|
||||
}
|
||||
|
||||
$this->currentRoute = $route;
|
||||
if($route instanceof RouterGroup && is_callable($route->getCallback())) {
|
||||
$route->renderRoute($this->requestMethod);
|
||||
$route->renderRoute($this->request);
|
||||
}
|
||||
$this->currentRoute = null;
|
||||
|
||||
@@ -84,22 +88,46 @@ class RouterBase {
|
||||
}
|
||||
|
||||
public function routeRequest() {
|
||||
// Loop through each route-request
|
||||
|
||||
// Verify csrf token for request
|
||||
if($this->baseCsrfVerifier !== null) {
|
||||
/* @var $csrfVerifier BaseCsrfVerifier */
|
||||
$csrfVerifier = $this->baseCsrfVerifier;
|
||||
$csrfVerifier = new $csrfVerifier();
|
||||
$csrfVerifier->handle($this->request);
|
||||
}
|
||||
|
||||
// Loop through each route-request
|
||||
$this->processRoutes($this->routes);
|
||||
|
||||
$routeNotAllowed = false;
|
||||
|
||||
/* @var $route RouterEntry */
|
||||
foreach($this->controllerUrlMap as $route) {
|
||||
$routeMatch = $route->matchRoute($this->requestMethod, rtrim($this->requestUri, '/') . '/');
|
||||
$routeMatch = $route->matchRoute($this->request);
|
||||
|
||||
if($routeMatch && !($routeMatch instanceof RouterGroup)) {
|
||||
|
||||
if(count($route->getRequestMethods()) && !in_array($this->request->getMethod(), $route->getRequestMethods())) {
|
||||
$routeNotAllowed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
$routeNotAllowed = false;
|
||||
|
||||
$this->loadedRoute = $routeMatch;
|
||||
$routeMatch->renderRoute($this->requestMethod);
|
||||
$routeMatch->loadMiddleware($this->request);
|
||||
$routeMatch->renderRoute($this->request);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if($routeNotAllowed) {
|
||||
throw new RouterException('Route or method not allowed', 403);
|
||||
}
|
||||
|
||||
if(!$this->loadedRoute) {
|
||||
throw new RouterException(sprintf('Route not found: %s', $this->requestUri), 404);
|
||||
throw new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,20 +155,6 @@ class RouterBase {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getRequestMethod() {
|
||||
return $this->requestMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getRequestUri() {
|
||||
return $this->requestUri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
@@ -162,14 +176,43 @@ class RouterBase {
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
protected function processUrl($route, $method = null, $parameters = null, $getParams = null) {
|
||||
$url = rtrim($route->getUrl(), '/') . '/';
|
||||
/**
|
||||
* Get current request
|
||||
*
|
||||
* @return Request
|
||||
*/
|
||||
public function getRequest() {
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
if($method !== null) {
|
||||
$url .= $method . '/';
|
||||
/**
|
||||
* Get base csrf verifier class
|
||||
* @return BaseCsrfVerifier
|
||||
*/
|
||||
public function getBaseCsrfVerifier() {
|
||||
return $this->baseCsrfVerifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set base csrf verifier class
|
||||
*
|
||||
* @param BaseCsrfVerifier $baseCsrfVerifier
|
||||
* @return self
|
||||
*/
|
||||
public function setBaseCsrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) {
|
||||
$this->baseCsrfVerifier = $baseCsrfVerifier;
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function processUrl($route, $method = null, $parameters = null, $getParams = null) {
|
||||
|
||||
$url = '/' . trim($route->getUrl(), '/');
|
||||
|
||||
if(($route instanceof RouterController || $route instanceof RouterResource) && $method !== null) {
|
||||
$url .= $method;
|
||||
}
|
||||
|
||||
if($route instanceof RouterController || $route instanceof RouterRessource) {
|
||||
if($route instanceof RouterController || $route instanceof RouterResource) {
|
||||
if(count($parameters)) {
|
||||
$url .= join('/', $parameters);
|
||||
}
|
||||
@@ -180,18 +223,22 @@ class RouterBase {
|
||||
$i = 0;
|
||||
foreach($params as $param => $value) {
|
||||
$value = (isset($parameters[$param])) ? $parameters[$param] : $value;
|
||||
$url = str_ireplace('{' . $param. '}', $value, $route->getUrl());
|
||||
$url = str_ireplace('{' . $param. '}', $value, $url);
|
||||
$i++;
|
||||
}
|
||||
} else {
|
||||
// If no parameters are specified in the route, assume that the provided parameters should be used.
|
||||
if(count($parameters)) {
|
||||
$url = rtrim($url, '/') . '/' . join('/', $parameters);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$p = '';
|
||||
if($getParams !== null && count($getParams)) {
|
||||
$p = '?'.Url::arrayToParams($getParams);
|
||||
}
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
$url .= $p;
|
||||
if($getParams !== null && count($getParams)) {
|
||||
$url .= '?'.Url::arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
@@ -206,38 +253,39 @@ class RouterBase {
|
||||
throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null');
|
||||
}
|
||||
|
||||
if($controller === null && $parameters === null && $this->loadedRoute !== null) {
|
||||
return $this->processUrl($this->loadedRoute, null, $getParams);
|
||||
}
|
||||
|
||||
$c = '';
|
||||
$method = null;
|
||||
|
||||
/* @var $route RouterRoute */
|
||||
foreach($this->controllerUrlMap as $route) {
|
||||
|
||||
// Check an alias exist, if the matches - use it
|
||||
if($route instanceof RouterRoute && strtolower($route->getAlias()) === strtolower($controller)) {
|
||||
return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
|
||||
}
|
||||
|
||||
if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) {
|
||||
$c = $route->getCallback();
|
||||
} else if($route instanceof RouterController || $route instanceof RouterRessource) {
|
||||
} else if($route instanceof RouterController || $route instanceof RouterResource) {
|
||||
$c = $route->getController();
|
||||
}
|
||||
|
||||
if($c === $controller || strpos($c, $controller) === 0) {
|
||||
if(stripos($c, '@') !== false) {
|
||||
$tmp = explode('@', $route->getCallback());
|
||||
$method = strtolower($tmp[1]);
|
||||
}
|
||||
return $this->processUrl($route, $method, $parameters, $getParams);
|
||||
return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
|
||||
}
|
||||
}
|
||||
|
||||
$c = '';
|
||||
|
||||
// No match has yet been found, let's try to guess what url that should be returned
|
||||
foreach($this->controllerUrlMap as $route) {
|
||||
if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) {
|
||||
$c = $route->getCallback();
|
||||
|
||||
if(stripos($controller, '@') !== false) {
|
||||
$tmp = explode('@', $controller);
|
||||
$c = $tmp[0];
|
||||
}
|
||||
|
||||
} else if($route instanceof RouterController || $route instanceof RouterRessource) {
|
||||
$c = $route->getClass();
|
||||
} else if($route instanceof RouterController || $route instanceof RouterResource) {
|
||||
$c = $route->getController();
|
||||
}
|
||||
|
||||
@@ -247,20 +295,25 @@ class RouterBase {
|
||||
$method = $tmp[1];
|
||||
}
|
||||
|
||||
if($controller == $c) {
|
||||
if($controller === $c) {
|
||||
return $this->processUrl($route, $method, $parameters, $getParams);
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing found - return current route
|
||||
if($this->loadedRoute) {
|
||||
$getParams = ($getParams === null) ? array() : $getParams;
|
||||
$params = ($this->loadedRoute->getParameters() == null) ? array() : $this->loadedRoute->getParameters();
|
||||
$parameters = ($parameters === null) ? array() : $parameters;
|
||||
return $this->processUrl($this->loadedRoute, null, array_merge($params, $parameters), array_merge($_GET, $getParams));
|
||||
$controller = ($controller === null) ? '/' : $controller;
|
||||
$url = array($controller);
|
||||
|
||||
if(is_array($parameters)) {
|
||||
ArrayUtil::append($url, $parameters);
|
||||
}
|
||||
|
||||
return '/';
|
||||
$url = '/' . trim(join('/', $url), '/') . '/';
|
||||
|
||||
if(is_array($getParams)) {
|
||||
$url .= '?' . Url::arrayToParams($getParams);
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
public static function getInstance() {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouterController extends RouterEntry {
|
||||
|
||||
const DEFAULT_METHOD = 'index';
|
||||
@@ -15,10 +17,32 @@ class RouterController extends RouterEntry {
|
||||
$this->controller = $controller;
|
||||
}
|
||||
|
||||
public function matchRoute($requestMethod, $url) {
|
||||
public function renderRoute(Request $request) {
|
||||
if(is_object($this->getCallback()) && is_callable($this->getCallback())) {
|
||||
|
||||
$url = parse_url($url);
|
||||
$url = $url['path'];
|
||||
// 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 = $request->getMethod() . ucfirst($controller[1]);
|
||||
|
||||
if (!method_exists($class, $method)) {
|
||||
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
call_user_func_array(array($class, $method), $this->getParameters());
|
||||
|
||||
return $class;
|
||||
}
|
||||
}
|
||||
|
||||
public function matchRoute(Request $request) {
|
||||
$url = parse_url($request->getUri());
|
||||
$url = rtrim($url['path'], '/') . '/';
|
||||
|
||||
if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) {
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
abstract class RouterEntry {
|
||||
|
||||
const REQUEST_TYPE_POST = 'post';
|
||||
@@ -19,18 +22,14 @@ abstract class RouterEntry {
|
||||
protected $settings;
|
||||
protected $callback;
|
||||
protected $parameters;
|
||||
protected $parametersRegex;
|
||||
protected $regexMatch;
|
||||
|
||||
public function __construct() {
|
||||
$this->settings = array();
|
||||
$this->settings['requestMethods'] = array();
|
||||
$this->parameters = array();
|
||||
}
|
||||
|
||||
protected function loadClass($name) {
|
||||
if(!class_exists($name)) {
|
||||
throw new RouterException(sprintf('Class %s does not exist', $name));
|
||||
}
|
||||
|
||||
return new $name();
|
||||
$this->parametersRegex = array();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,20 +62,20 @@ abstract class RouterEntry {
|
||||
return $this->callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getParameters(){
|
||||
return $this->parameters;
|
||||
public function getMethod() {
|
||||
if(strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
return $tmp[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $parameters
|
||||
* @return self
|
||||
*/
|
||||
public function setParameters($parameters) {
|
||||
$this->parameters = $parameters;
|
||||
return $this;
|
||||
public function getClass() {
|
||||
if(strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
return $tmp[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,6 +133,44 @@ abstract class RouterEntry {
|
||||
return $this->settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getParameters(){
|
||||
return $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $parameters
|
||||
* @return self
|
||||
*/
|
||||
public function setParameters($parameters) {
|
||||
$this->parameters = $parameters;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add regular expression parameter match
|
||||
*
|
||||
* @param array $options
|
||||
* @return self
|
||||
*/
|
||||
public function where(array $options) {
|
||||
$this->parametersRegex = array_merge($this->parametersRegex, $options);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add regular expression match for url
|
||||
*
|
||||
* @param string $regex
|
||||
* @return self
|
||||
*/
|
||||
public function match($regex) {
|
||||
$this->regexMatch = $regex;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get settings that are allowed to be inherited by child routes.
|
||||
*
|
||||
@@ -142,9 +179,9 @@ abstract class RouterEntry {
|
||||
public function getMergeableSettings() {
|
||||
$settings = $this->settings;
|
||||
|
||||
if(isset($settings['middleware'])) {
|
||||
/*if(isset($settings['middleware'])) {
|
||||
unset($settings['middleware']);
|
||||
}
|
||||
}*/
|
||||
|
||||
if(isset($settings['prefix'])) {
|
||||
unset($settings['prefix']);
|
||||
@@ -157,8 +194,10 @@ abstract class RouterEntry {
|
||||
* @param array $settings
|
||||
* @return self
|
||||
*/
|
||||
public function addSettings(array $settings) {
|
||||
array_merge($this->settings, $settings);
|
||||
public function addSettings(array $settings = null) {
|
||||
if(is_array($settings)) {
|
||||
$this->settings = array_merge($this->settings, $settings);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -169,7 +208,7 @@ abstract class RouterEntry {
|
||||
public function setSettings($settings) {
|
||||
$this->settings = $settings;
|
||||
|
||||
if($settings['prefix']) {
|
||||
if(isset($settings['prefix'])) {
|
||||
$this->setPrefix($settings['prefix']);
|
||||
}
|
||||
|
||||
@@ -196,12 +235,28 @@ abstract class RouterEntry {
|
||||
$this->settings[$name] = $value;
|
||||
}
|
||||
|
||||
public function renderRoute($requestMethod) {
|
||||
// Load middleware
|
||||
if($this->getMiddleware()) {
|
||||
$this->loadClass($this->getMiddleware());
|
||||
protected function loadClass($name) {
|
||||
if(!class_exists($name)) {
|
||||
throw new RouterException(sprintf('Class %s does not exist', $name));
|
||||
}
|
||||
|
||||
return new $name();
|
||||
}
|
||||
|
||||
public function loadMiddleware(Request $request) {
|
||||
if($this->getMiddleware()) {
|
||||
$middleware = $this->loadClass($this->getMiddleware());
|
||||
if (!($middleware instanceof IMiddleware)) {
|
||||
throw new RouterException($this->getMiddleware() . ' must be instance of Middleware');
|
||||
}
|
||||
|
||||
/* @var $class Middleware */
|
||||
$middleware->handle($request);
|
||||
}
|
||||
}
|
||||
|
||||
public function renderRoute(Request $request) {
|
||||
|
||||
if(is_object($this->getCallback()) && is_callable($this->getCallback())) {
|
||||
|
||||
// When the callback is a function
|
||||
@@ -210,8 +265,9 @@ abstract class RouterEntry {
|
||||
// When the callback is a method
|
||||
$controller = explode('@', $this->getCallback());
|
||||
$className = $this->getNamespace() . '\\' . $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $requestMethod . ucfirst($controller[1]);
|
||||
$method = $controller[1];
|
||||
|
||||
if (!method_exists($class, $method)) {
|
||||
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
@@ -225,6 +281,30 @@ abstract class RouterEntry {
|
||||
return null;
|
||||
}
|
||||
|
||||
abstract function matchRoute($requestMethod, $url);
|
||||
/**
|
||||
* Set allowed request methods
|
||||
*
|
||||
* @param array $methods
|
||||
* @return self $this
|
||||
*/
|
||||
public function setRequestMethods(array $methods) {
|
||||
$this->settings['requestMethods'] = $methods;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get allowed requeset methods
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRequestMethods() {
|
||||
if(!isset($this->settings['requestMethods']) || isset($this->settings['requestMethods']) && !is_array($this->settings['requestMethods'])) {
|
||||
$value = isset($this->settings['requestMethods']) ? $this->settings['requestMethods'] : null;
|
||||
return array($value);
|
||||
}
|
||||
return $this->settings['requestMethods'];
|
||||
}
|
||||
|
||||
abstract function matchRoute(Request $request);
|
||||
|
||||
}
|
||||
@@ -2,24 +2,26 @@
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouterGroup extends RouterEntry {
|
||||
|
||||
public function __construct() {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function matchRoute($requestMethod, $url) {
|
||||
public function renderRoute(Request $request) {
|
||||
// Check if request method is allowed
|
||||
|
||||
if(strtolower($url) == strtolower($this->prefix) || stripos($url, $this->prefix) === 0) {
|
||||
if(trim($this->prefix) === '' || strtolower($request->getUri()) == strtolower($this->prefix) || stripos($request->getUri(), $this->prefix) === 0) {
|
||||
|
||||
$hasAccess = (!$this->method);
|
||||
|
||||
if($this->method) {
|
||||
if(is_array($this->method)) {
|
||||
$hasAccess = (in_array($requestMethod, $this->method));
|
||||
$hasAccess = (in_array($request->getMethod(), $this->getRequestMethods()));
|
||||
} else {
|
||||
$hasAccess = strtolower($this->method) == strtolower($requestMethod);
|
||||
$hasAccess = strtolower($this->getRequestMethods()) == strtolower($request->getMethod());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,11 +29,17 @@ class RouterGroup extends RouterEntry {
|
||||
throw new RouterException('Method not allowed');
|
||||
}
|
||||
|
||||
return $this;
|
||||
$this->loadMiddleware($request);
|
||||
|
||||
return parent::renderRoute($request);
|
||||
}
|
||||
|
||||
// No match here, move on...
|
||||
return null;
|
||||
}
|
||||
|
||||
public function matchRoute(Request $request) {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+10
-13
@@ -1,7 +1,9 @@
|
||||
<?php
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
class RouterRessource extends RouterEntry {
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouterResource extends RouterEntry {
|
||||
|
||||
const DEFAULT_METHOD = 'index';
|
||||
|
||||
@@ -17,12 +19,7 @@ class RouterRessource extends RouterEntry {
|
||||
$this->postMethod = strtolower(($_SERVER['REQUEST_METHOD'] != 'GET') ? 'post' : 'get');
|
||||
}
|
||||
|
||||
public function renderRoute($requestMethod) {
|
||||
// Load middleware
|
||||
if($this->getMiddleware()) {
|
||||
$this->loadClass($this->getMiddleware());
|
||||
}
|
||||
|
||||
public function renderRoute(Request $request) {
|
||||
if(is_object($this->getCallback()) && is_callable($this->getCallback())) {
|
||||
// When the callback is a function
|
||||
call_user_func_array($this->getCallback(), $this->getParameters());
|
||||
@@ -51,9 +48,9 @@ class RouterRessource extends RouterEntry {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function matchRoute($requestMethod, $url) {
|
||||
$url = parse_url($url);
|
||||
$url = $url['path'];
|
||||
public function matchRoute(Request $request) {
|
||||
$url = parse_url($request->getUri());
|
||||
$url = rtrim($url['path'], '/') . '/';
|
||||
|
||||
if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) {
|
||||
$url = rtrim($url, '/');
|
||||
@@ -72,12 +69,12 @@ class RouterRessource extends RouterEntry {
|
||||
if (count($path)) {
|
||||
|
||||
// Delete
|
||||
if($requestMethod === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) {
|
||||
if($request->getMethod() === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) {
|
||||
return $this->call('destroy', $args);
|
||||
}
|
||||
|
||||
// Update
|
||||
if(in_array($requestMethod, array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) {
|
||||
if(in_array($request->getMethod(), array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) {
|
||||
return $this->call('update', array_merge(array($action), $args));
|
||||
}
|
||||
|
||||
@@ -87,7 +84,7 @@ class RouterRessource extends RouterEntry {
|
||||
}
|
||||
|
||||
// Create
|
||||
if(strtolower($action) === 'create' && $requestMethod === self::REQUEST_TYPE_GET) {
|
||||
if(strtolower($action) === 'create' && $request->getMethod() === self::REQUEST_TYPE_GET) {
|
||||
return $this->call('create', $args);
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Registry;
|
||||
use Pecee\Router;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouterRoute extends RouterEntry {
|
||||
|
||||
const PARAMETERS_REGEX_MATCH = '{([A-Za-z\-\_]*?)}';
|
||||
|
||||
protected $url;
|
||||
protected $requestTypes;
|
||||
|
||||
public function __construct($url, $callback) {
|
||||
parent::__construct();
|
||||
@@ -16,13 +16,17 @@ class RouterRoute extends RouterEntry {
|
||||
$this->setCallback($callback);
|
||||
|
||||
$this->settings['aliases'] = array();
|
||||
$this->requestTypes = array();
|
||||
}
|
||||
|
||||
protected function parseParameters($url) {
|
||||
protected function parseParameters($url, $multiple = false, $regex = self::PARAMETERS_REGEX_MATCH) {
|
||||
$url = rtrim($url, '/');
|
||||
$parameters = array();
|
||||
|
||||
preg_match_all('/{([A-Za-z\-\_]*?)}/is', $url, $parameters);
|
||||
if($multiple) {
|
||||
preg_match_all('/'.$regex.'/is', $url, $parameters);
|
||||
} else {
|
||||
preg_match('/'.$regex.'/is', $url, $parameters);
|
||||
}
|
||||
|
||||
if(isset($parameters[1]) && count($parameters[1]) > 0) {
|
||||
return $parameters[1];
|
||||
@@ -31,58 +35,74 @@ class RouterRoute extends RouterEntry {
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function parseParameter($path) {
|
||||
$parameters = array();
|
||||
|
||||
preg_match('/{([A-Za-z\-\_]*?)}/is', $path, $parameters);
|
||||
|
||||
if(isset($parameters[1]) && count($parameters[1]) > 0) {
|
||||
return $parameters[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function matchRoute($requestMethod, $url) {
|
||||
public function matchRoute(Request $request) {
|
||||
|
||||
// Check if request method is allowed
|
||||
if(count($this->requestTypes) === 0 || in_array($requestMethod, $this->requestTypes)) {
|
||||
|
||||
$url = parse_url($url);
|
||||
$url = $url['path'];
|
||||
$url = parse_url($request->getUri());
|
||||
$url = $url['path'];
|
||||
|
||||
$url = explode('/', trim($url, '/'));
|
||||
$route = explode('/', trim($this->url, '/'));
|
||||
$route = $this->url;
|
||||
|
||||
// Check if url parameter count matches
|
||||
if(count($url) === count($route)) {
|
||||
$routeMatch = preg_replace('/'.self::PARAMETERS_REGEX_MATCH.'/is', '', $route);
|
||||
|
||||
// Check if url parameter count matches
|
||||
if(stripos($url, $routeMatch) === 0) {
|
||||
|
||||
$matches = true;
|
||||
|
||||
if($this->regexMatch) {
|
||||
$parameters = $this->parseParameters($url, true, $this->regexMatch);
|
||||
|
||||
// If regex doesn't match, make sure to return an array
|
||||
if(!is_array($parameters)) {
|
||||
$parameters = array();
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
$matches = (count(explode('/', rtrim($url, '/'))) == count(explode('/', rtrim($route, '/'))));
|
||||
|
||||
$url = explode('/', $url);
|
||||
$route = explode('/', rtrim($route, '/'));
|
||||
|
||||
$parameters = array();
|
||||
|
||||
$matches = true;
|
||||
|
||||
// Check if url matches
|
||||
foreach($route as $i => $path) {
|
||||
$parameter = $this->parseParameter($path);
|
||||
foreach ($route as $i => $path) {
|
||||
$parameter = $this->parseParameters($path, false);
|
||||
|
||||
// Check if parameter of path matches, otherwise quit..
|
||||
if(is_null($parameter) && strtolower($path) != strtolower($url[$i])) {
|
||||
if (is_null($parameter) && strtolower($path) != strtolower($url[$i])) {
|
||||
$matches = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Save parameter if we have one
|
||||
if($parameter) {
|
||||
$parameters[$parameter] = $url[$i];
|
||||
if ($parameter) {
|
||||
$parameterValue = $url[$i];
|
||||
$regex = (isset($this->parametersRegex[$parameter]) ? $this->parametersRegex[$parameter] : null);
|
||||
|
||||
if ($regex !== null) {
|
||||
// Use the regular expression rule provided to filter the value
|
||||
$matches = array();
|
||||
preg_match('/' . $regex . '/is', $url[$i], $matches);
|
||||
|
||||
if (count($matches)) {
|
||||
$parameterValue = $matches[0];
|
||||
}
|
||||
}
|
||||
|
||||
// Add parameter value, if it doesn't exist - replace it with null value
|
||||
$parameters[$parameter] = ($parameterValue === '') ? null : $parameterValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This route matches
|
||||
if($matches) {
|
||||
$this->parameters = $parameters;
|
||||
return $this;
|
||||
}
|
||||
|
||||
// This route matches
|
||||
if($matches) {
|
||||
$this->parameters = $parameters;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +123,7 @@ class RouterRoute extends RouterEntry {
|
||||
*/
|
||||
public function setUrl($url) {
|
||||
|
||||
$parameters = $this->parseParameters($url);
|
||||
$parameters = $this->parseParameters($url, true);
|
||||
|
||||
if($parameters !== null) {
|
||||
foreach($parameters as $param) {
|
||||
@@ -116,49 +136,31 @@ class RouterRoute extends RouterEntry {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $aliases
|
||||
* @return self
|
||||
* Get alias for the url which can be used when getting the url route.
|
||||
* @return string
|
||||
*/
|
||||
public function setAliases(array $aliases) {
|
||||
$this->aliases = $aliases;
|
||||
return $this;
|
||||
public function getAlias(){
|
||||
return $this->alias;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add alias
|
||||
*
|
||||
* @param $alias
|
||||
* Set the url alias for easier getting the url route.
|
||||
* @param string $alias
|
||||
* @return self
|
||||
*/
|
||||
public function addAlias($alias) {
|
||||
$this->aliases[] = $alias;
|
||||
public function setAlias($alias){
|
||||
$this->alias = $alias;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAliases() {
|
||||
$this->aliases;
|
||||
}
|
||||
public function setSettings($settings) {
|
||||
|
||||
/**
|
||||
* Add request type
|
||||
*
|
||||
* @param $type
|
||||
* @return self
|
||||
* @throws RouterException
|
||||
*/
|
||||
public function addRequestType($type) {
|
||||
if(!in_array($type, self::$allowedRequestTypes)) {
|
||||
throw new RouterException('Invalid request method: ' . $type);
|
||||
// Change as to alias
|
||||
if(isset($settings{'as'})) {
|
||||
$this->setAlias($settings['as']);
|
||||
}
|
||||
|
||||
$this->requestTypes[] = $type;
|
||||
return $this;
|
||||
return parent::setSettings($settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getRequestTypes() {
|
||||
return $this->requestTypes;
|
||||
}
|
||||
}
|
||||
@@ -9,17 +9,33 @@
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
|
||||
class SimpleRouter {
|
||||
|
||||
/**
|
||||
* Start/route request
|
||||
* @param null $defaultNamespace
|
||||
* @throws RouterException
|
||||
*/
|
||||
public static function start($defaultNamespace = null) {
|
||||
$router = RouterBase::GetInstance();
|
||||
$router->setDefaultNamespace($defaultNamespace);
|
||||
$router->routeRequest();
|
||||
}
|
||||
|
||||
public static function get($url, $callback) {
|
||||
/**
|
||||
* Set base csrf verifier
|
||||
* @param BaseCsrfVerifier $baseCsrfVerifier
|
||||
*/
|
||||
public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) {
|
||||
RouterBase::getInstance()->setBaseCsrfVerifier($baseCsrfVerifier);
|
||||
}
|
||||
|
||||
public static function get($url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
$route->addRequestType(RouterRoute::REQUEST_TYPE_GET);
|
||||
$route->addSettings($settings);
|
||||
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_GET));
|
||||
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
@@ -27,9 +43,10 @@ class SimpleRouter {
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function post($url, $callback) {
|
||||
public static function post($url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
$route->addRequestType(RouterRoute::REQUEST_TYPE_POST);
|
||||
$route->addSettings($settings);
|
||||
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_POST));
|
||||
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
@@ -37,9 +54,10 @@ class SimpleRouter {
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function put($url, $callback) {
|
||||
public static function put($url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
$route->addRequestType(RouterRoute::REQUEST_TYPE_PUT);
|
||||
$route->addSettings($settings);
|
||||
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_PUT));
|
||||
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
@@ -47,9 +65,10 @@ class SimpleRouter {
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function delete($url, $callback) {
|
||||
public static function delete($url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
$route->addRequestType(RouterRoute::REQUEST_TYPE_DELETE);
|
||||
$route->addSettings($settings);
|
||||
$route->setRequestMethods(array(RouterRoute::REQUEST_TYPE_DELETE));
|
||||
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
@@ -71,11 +90,10 @@ class SimpleRouter {
|
||||
return $group;
|
||||
}
|
||||
|
||||
public static function match(array $requestTypes, $url, $callback) {
|
||||
public static function match(array $requestMethods, $url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
foreach($requestTypes as $requestType) {
|
||||
$route->addRequestType($requestType);
|
||||
}
|
||||
$route->setRequestMethods($requestMethods);
|
||||
$route->addSettings($settings);
|
||||
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
@@ -83,31 +101,34 @@ class SimpleRouter {
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function all($url, $callback) {
|
||||
public static function all($url, $callback, array $settings = null) {
|
||||
$route = new RouterRoute($url, $callback);
|
||||
$route->addSettings($settings);
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function controller($url, $controller) {
|
||||
public static function controller($url, $controller, array $settings = null) {
|
||||
$route = new RouterController($url, $controller);
|
||||
$route->addSettings($settings);
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
public static function ressource($url, $controller) {
|
||||
$route = new RouterRessource($url, $controller);
|
||||
public static function resource($url, $controller, array $settings = null) {
|
||||
$route = new RouterResource($url, $controller);
|
||||
$route->addSettings($settings);
|
||||
$router = RouterBase::getInstance();
|
||||
$router->addRoute($route);
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
public function getRoute($controller = null, $parameters = null, $getParams = null) {
|
||||
public static function getRoute($controller = null, $parameters = null, $getParams = null) {
|
||||
return RouterBase::getInstance()->getRoute($controller, $parameters, $getParams);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user