mirror of
https://github.com/skipperbent/simple-php-router.git
synced 2026-06-17 16:57:53 +00:00
Compare commits
287 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 877e0aa937 | |||
| 7f8d90eef8 | |||
| 3e7767d978 | |||
| 4bb784bcec | |||
| c4ee1b9186 | |||
| 5ef9349b18 | |||
| efd5159604 | |||
| 264f0a7b0f | |||
| bdfc36ed5c | |||
| 5197ae2990 | |||
| d921ae8105 | |||
| 9c701aabee | |||
| af2be14ccb | |||
| 2b0821a557 | |||
| fae2e84c98 | |||
| afc81d7005 | |||
| c90c74b88f | |||
| 05f2493304 | |||
| 0856caa9de | |||
| 35dc26d741 | |||
| 496d3e7182 | |||
| f2819f866e | |||
| b9aa348b38 | |||
| c29c52ae16 | |||
| 6547c07113 | |||
| 1fd13ed2aa | |||
| fde77969c0 | |||
| c3072e8886 | |||
| 9d5c4a2ed1 | |||
| 97753f5370 | |||
| b8634bcf79 | |||
| 6ad22a3816 | |||
| ed41cd55af | |||
| ebeca952cf | |||
| 0672e85fd7 | |||
| 927f8d7b3c | |||
| 74177a2082 | |||
| 2221bced4f | |||
| 6559278511 | |||
| 8b9698229d | |||
| a565f66c4c | |||
| 832ef992a3 | |||
| cc5e417db9 | |||
| 2cc90e28d0 | |||
| eb63a5d6ba | |||
| a07b30a80d | |||
| c45cd6347a | |||
| 4a353efc97 | |||
| f7ce440c56 | |||
| 41705f030a | |||
| 18fa0f9610 | |||
| 66ecf0ee33 | |||
| 4ba15033d9 | |||
| 60393a3722 | |||
| cfa18e520a | |||
| 5e448f0835 | |||
| 98ad310404 | |||
| a5aac57ce9 | |||
| 7f924c7d0a | |||
| 3a90578351 | |||
| 52e0f5ef94 | |||
| 3df3ef36ef | |||
| 0090c167bb | |||
| ae68598024 | |||
| c723ca7e61 | |||
| 7362b748af | |||
| 4fe85d6568 | |||
| c82d91375c | |||
| e3b6899375 | |||
| e774122b1e | |||
| e8aceb291c | |||
| 957a382248 | |||
| a179450018 | |||
| 48e2e3f9bc | |||
| f95e12c49c | |||
| 9f509ac818 | |||
| ac3e9ed2ac | |||
| 3b4d23e9ae | |||
| b3e99a2283 | |||
| c1aa5782a1 | |||
| 387d9710d8 | |||
| fd098266f7 | |||
| c7473938c5 | |||
| 65c811356d | |||
| ea255baec3 | |||
| acf37c4023 | |||
| 6fb92d7cae | |||
| e84c8c2f02 | |||
| 7c970c442c | |||
| 4cd1e8e069 | |||
| 8720e732e1 | |||
| 7e8cb91f68 | |||
| bc67038e11 | |||
| e31d8af2f7 | |||
| 9f285fd0ce | |||
| b7f5d31544 | |||
| 5086347802 | |||
| 26f89213a2 | |||
| bb7991afdc | |||
| 796d01bc25 | |||
| 74187ee326 | |||
| f090d6c038 | |||
| 6e859e11ab | |||
| 6aa38cfa4c | |||
| 62f0075cf3 | |||
| 6890b60737 | |||
| a40f81d5fc | |||
| a5527a0e8c | |||
| 3c73de866e | |||
| 883d8a6b0e | |||
| 3a7b27796a | |||
| 1e07140865 | |||
| 4cca5186f3 | |||
| 5437420175 | |||
| 410fa3c9f5 | |||
| be20fe4dd1 | |||
| bc03490100 | |||
| 0947f6746e | |||
| 31c8710ce7 | |||
| 1ac7761d35 | |||
| 9eb7c5c13c | |||
| 5151461a02 | |||
| b07348a3df | |||
| d411b31cc2 | |||
| ca381d445f | |||
| 2c61cef7ad | |||
| 98ee60859f | |||
| 9dd80dd1d9 | |||
| 3f9ab73f7f | |||
| fef997422e | |||
| 8901e7c125 | |||
| 50e8926272 | |||
| e44d6bc30b | |||
| 27ff761d18 | |||
| 0a58d36606 | |||
| db024b9588 | |||
| 3f61c90749 | |||
| 94d0764631 | |||
| ff3f1bdcdd | |||
| e4e632dca9 | |||
| 3e75d6ec0b | |||
| 8c5d8c2dc9 | |||
| a5c4a1f721 | |||
| 9d2bffcd02 | |||
| 2a448fccd2 | |||
| 0bc7fa7bd5 | |||
| e682cf0b7c | |||
| c87298ee24 | |||
| 79414255e0 | |||
| eb036ded3b | |||
| e913dd98da | |||
| ccd3cf450e | |||
| debe080181 | |||
| 2654ca67db | |||
| dd99e1d488 | |||
| 86c3e513c3 | |||
| 1c07311c5d | |||
| ce276bd5b7 | |||
| 801c84eb05 | |||
| ed98519152 | |||
| 55d031e152 | |||
| 8509062e00 | |||
| 4b4ab906fb | |||
| 9617cacc31 | |||
| 54a824ce44 | |||
| 99088719ed | |||
| 2062ff4189 | |||
| 3e41ee28b6 | |||
| 13a5f40cd0 | |||
| 751b4444ae | |||
| 351f7a01e8 | |||
| 8cd42a2c4b | |||
| 1496878ae9 | |||
| e8e1471bab | |||
| b3f2e5f812 | |||
| 4de1498723 | |||
| a60fa9f919 | |||
| ea243f2c89 | |||
| ce6f34f4d4 | |||
| 56653568e4 | |||
| 2868ffe023 | |||
| 5d330643e7 | |||
| 8ab52364da | |||
| 57aa8eac1e | |||
| 110bc2afcf | |||
| 4efc72d013 | |||
| a92a4cdf0d | |||
| 49fc991f9a | |||
| 0a4c78cf64 | |||
| 20353c6e4d | |||
| 6706d86784 | |||
| 4c62f86a26 | |||
| 20c1e0ef69 | |||
| 6445746324 | |||
| 1a2921acb4 | |||
| fe560a9ba5 | |||
| 258d9d05c7 | |||
| c522801c28 | |||
| 7e7319de06 | |||
| 9d275d6d3b | |||
| 531b35532b | |||
| e6dd9f3f55 | |||
| c258f937e8 | |||
| e803b1ca5c | |||
| 88d58cd7b7 | |||
| 45faf9830e | |||
| d04c74ccad | |||
| c915c0386a | |||
| 02809a4daf | |||
| 30479b15ca | |||
| da6b5af19f | |||
| 4dde51e833 | |||
| 914ec9d1b7 | |||
| 961a4d0e94 | |||
| 5f72755a98 | |||
| 2216090a5f | |||
| 41d15d3acd | |||
| d467f60e55 | |||
| ded9c8ebe0 | |||
| c30ae6b098 | |||
| 394f7beb8b | |||
| c93308c8e1 | |||
| baab004482 | |||
| c3241012af | |||
| 00c0cad211 | |||
| 9e2ba2674b | |||
| c6e85676da | |||
| 4d18f33a81 | |||
| 5a74c9d27d | |||
| 9d98b2da4c | |||
| b5eef6f3ee | |||
| 6930864e7e | |||
| ad0eceb814 | |||
| f3f129ae0b | |||
| 4bec2bc5fb | |||
| 85b9fac21e | |||
| 4f47463497 | |||
| 0c93633d13 | |||
| e5c86c1822 | |||
| 973344e46e | |||
| 32c305bd2c | |||
| 4a03005c68 | |||
| 52034411cf | |||
| 4c8ed5bb3d | |||
| 9fed6ffb3f | |||
| 15da599e82 | |||
| 9274acb591 | |||
| 5c7759ab72 | |||
| c7b8593185 | |||
| fb478f475c | |||
| 1142d9d4ce | |||
| 5d5c96e802 | |||
| bfdaf8ac52 | |||
| 71dc6e172f | |||
| 6ee172927f | |||
| bb5e629199 | |||
| 0cc0a59fd5 | |||
| 498fd6b07d | |||
| 96ab22a4f8 | |||
| 7f528c133b | |||
| 5a50190293 | |||
| 355ef01d63 | |||
| d3162b5a2b | |||
| 810b80487d | |||
| 18a9df56ca | |||
| 6e14ded03f | |||
| 899081f8d8 | |||
| e7b9206bc9 | |||
| cd6e800984 | |||
| 11bd5a7d11 | |||
| be32796b01 | |||
| 8b3d71a328 | |||
| 1fae638aaf | |||
| 37c8bc9f32 | |||
| 75029b330a | |||
| fd5d893040 | |||
| c1512740af | |||
| 212ae133de | |||
| ae58231fa1 | |||
| 358b25d4f1 | |||
| 3d45851d9b | |||
| ee5c2207f8 | |||
| b1ca3fc9ef | |||
| 253c0c70d4 | |||
| 53ba2d7ac5 | |||
| 315fe05769 | |||
| a57113309a |
+1
-2
@@ -1,4 +1,3 @@
|
||||
.idea
|
||||
composer.lock
|
||||
vendor/
|
||||
demo-project/vendor
|
||||
vendor/
|
||||
+32
-23
@@ -1,26 +1,35 @@
|
||||
{
|
||||
"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",
|
||||
"router",
|
||||
"routing",
|
||||
"route",
|
||||
"simple-php-router",
|
||||
"laravel",
|
||||
"pecee",
|
||||
"php"
|
||||
],
|
||||
"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/"
|
||||
}
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as Router;
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
* The name parameter supports the following values:
|
||||
* - Route name
|
||||
* - Controller/resource name (with or without method)
|
||||
* - Controller class name
|
||||
*
|
||||
* When searching for controller/resource by name, you can use this syntax "route.name@method".
|
||||
* You can also use the same syntax when searching for a specific controller-class "MyController@home".
|
||||
* If no arguments is specified, it will return the url for the current loaded route.
|
||||
*
|
||||
* @param string|null $name
|
||||
* @param string|array|null $parameters
|
||||
* @param array|null $getParams
|
||||
* @return string
|
||||
*/
|
||||
function url($name = null, $parameters = null, $getParams = null)
|
||||
{
|
||||
return Router::getUrl($name, $parameters, $getParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Pecee\Http\Response
|
||||
*/
|
||||
function response()
|
||||
{
|
||||
return Router::response();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Pecee\Http\Request
|
||||
*/
|
||||
function request()
|
||||
{
|
||||
return Router::request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get input class
|
||||
* @param string|null $index Parameter index name
|
||||
* @param string|null $defaultValue Default return value
|
||||
* @param string|array|null $methods Default method
|
||||
* @return \Pecee\Http\Input\Input|string
|
||||
*/
|
||||
function input($index = null, $defaultValue = null, $methods = null)
|
||||
{
|
||||
if ($index !== null) {
|
||||
return request()->getInput()->get($index, $defaultValue, $methods);
|
||||
}
|
||||
|
||||
return request()->getInput();
|
||||
}
|
||||
|
||||
function redirect($url, $code = null)
|
||||
{
|
||||
if ($code !== null) {
|
||||
response()->httpCode($code);
|
||||
}
|
||||
|
||||
response()->redirect($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current csrf-token
|
||||
* @return string|null
|
||||
*/
|
||||
function csrf_token()
|
||||
{
|
||||
$baseVerifier = Router::router()->getCsrfVerifier();
|
||||
if ($baseVerifier !== null) {
|
||||
return $baseVerifier->getTokenProvider()->getToken();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
namespace Pecee\Controllers;
|
||||
|
||||
interface IRestController
|
||||
interface IResourceController
|
||||
{
|
||||
|
||||
/**
|
||||
@@ -1,71 +0,0 @@
|
||||
<?php
|
||||
namespace Pecee;
|
||||
|
||||
class CsrfToken
|
||||
{
|
||||
const CSRF_KEY = 'XSRF-TOKEN';
|
||||
|
||||
protected $token;
|
||||
|
||||
/**
|
||||
* Generate random identifier for CSRF token
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function generateToken()
|
||||
{
|
||||
if (function_exists('random_bytes')) {
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
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(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]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Handlers;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
/**
|
||||
* Class CallbackExceptionHandler
|
||||
*
|
||||
* Class is used to create callbacks which are fired when an exception is reached.
|
||||
* This allows for easy handling 404-exception etc. without creating an custom ExceptionHandler.
|
||||
*
|
||||
* @package Pecee\Handlers
|
||||
*/
|
||||
class CallbackExceptionHandler implements IExceptionHandler
|
||||
{
|
||||
|
||||
protected $callback;
|
||||
|
||||
public function __construct(\Closure $callback)
|
||||
{
|
||||
$this->callback = $callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Request $request
|
||||
* @param \Exception $error
|
||||
* @return Request|null
|
||||
*/
|
||||
public function handleError(Request $request, \Exception $error)
|
||||
{
|
||||
/* Fire exceptions */
|
||||
return call_user_func($this->callback,
|
||||
$request,
|
||||
$error
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
public function handleError(Request $request, \Exception $error);
|
||||
|
||||
}
|
||||
@@ -12,6 +12,8 @@ interface IInputItem
|
||||
|
||||
public function setName($name);
|
||||
|
||||
public function getValue();
|
||||
|
||||
public function __toString();
|
||||
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Input;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -35,7 +36,7 @@ class Input
|
||||
public function parseInputs()
|
||||
{
|
||||
/* Parse get requests */
|
||||
if (count($_GET) > 0) {
|
||||
if (count($_GET) !== 0) {
|
||||
$this->get = $this->handleGetPost($_GET);
|
||||
}
|
||||
|
||||
@@ -46,12 +47,12 @@ class Input
|
||||
parse_str(file_get_contents('php://input'), $postVars);
|
||||
}
|
||||
|
||||
if (count($postVars) > 0) {
|
||||
if (count($postVars) !== 0) {
|
||||
$this->post = $this->handleGetPost($postVars);
|
||||
}
|
||||
|
||||
/* Parse get requests */
|
||||
if (count($_FILES) > 0) {
|
||||
if (count($_FILES) !== 0) {
|
||||
$this->file = $this->parseFiles();
|
||||
}
|
||||
}
|
||||
@@ -60,20 +61,20 @@ class Input
|
||||
{
|
||||
$list = [];
|
||||
|
||||
foreach ($_FILES as $key => $value) {
|
||||
foreach ((array)$_FILES as $key => $value) {
|
||||
|
||||
// Handle array input
|
||||
if (is_array($value['name']) === false) {
|
||||
$values['index'] = $key;
|
||||
$list[$key] = InputFile::createFromArray(array_merge($value, $values));
|
||||
$list[$key] = InputFile::createFromArray($values + $value);
|
||||
continue;
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
$keys = [$key];
|
||||
|
||||
$files = $this->rearrangeFiles($value['name'], $keys, $value);
|
||||
|
||||
if (isset($list[$key])) {
|
||||
if (isset($list[$key]) === true) {
|
||||
$list[$key][] = $files;
|
||||
} else {
|
||||
$list[$key] = $files;
|
||||
@@ -87,38 +88,30 @@ class Input
|
||||
protected function rearrangeFiles(array $values, &$index, $original)
|
||||
{
|
||||
|
||||
$originalIndex = $index[0];
|
||||
array_shift($index);
|
||||
|
||||
$output = [];
|
||||
|
||||
$getItem = function ($key, $property = 'name') use ($original, $index) {
|
||||
|
||||
$path = $original[$property];
|
||||
|
||||
foreach (array_values($index) as $i) {
|
||||
$path = $path[$i];
|
||||
}
|
||||
|
||||
return $path[$key];
|
||||
};
|
||||
|
||||
foreach ($values as $key => $value) {
|
||||
|
||||
if (is_array($getItem($key)) === false) {
|
||||
if (is_array($original['name'][$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'),
|
||||
'index' => (empty($key) === true && empty($originalIndex) === false) ? $originalIndex : $key,
|
||||
'name' => $original['name'][$key],
|
||||
'error' => $original['error'][$key],
|
||||
'tmp_name' => $original['tmp_name'][$key],
|
||||
'type' => $original['type'][$key],
|
||||
'size' => $original['size'][$key],
|
||||
]);
|
||||
|
||||
if (isset($output[$key])) {
|
||||
if (isset($output[$key]) === true) {
|
||||
$output[$key][] = $file;
|
||||
} else {
|
||||
$output[$key] = $file;
|
||||
continue;
|
||||
}
|
||||
|
||||
$output[$key] = $file;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -126,7 +119,7 @@ class Input
|
||||
|
||||
$files = $this->rearrangeFiles($value, $index, $original);
|
||||
|
||||
if (isset($output[$key])) {
|
||||
if (isset($output[$key]) === true) {
|
||||
$output[$key][] = $files;
|
||||
} else {
|
||||
$output[$key] = $files;
|
||||
@@ -141,13 +134,7 @@ class Input
|
||||
{
|
||||
$list = [];
|
||||
|
||||
$max = count($array) - 1;
|
||||
$keys = array_keys($array);
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$key = $keys[$i];
|
||||
$value = $array[$key];
|
||||
foreach ($array as $key => $value) {
|
||||
|
||||
// Handle array input
|
||||
if (is_array($value) === false) {
|
||||
@@ -215,15 +202,15 @@ class Input
|
||||
|
||||
$element = null;
|
||||
|
||||
if ($methods === null || in_array('get', $methods)) {
|
||||
if ($methods === null || in_array('get', $methods, false) === true) {
|
||||
$element = $this->findGet($index);
|
||||
}
|
||||
|
||||
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods))) {
|
||||
if (($element === null && $methods === null) || ($methods !== null && in_array('post', $methods, false) === true)) {
|
||||
$element = $this->findPost($index);
|
||||
}
|
||||
|
||||
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods))) {
|
||||
if (($element === null && $methods === null) || ($methods !== null && in_array('file', $methods, false) === true)) {
|
||||
$element = $this->findFile($index);
|
||||
}
|
||||
|
||||
@@ -281,15 +268,7 @@ class Input
|
||||
}
|
||||
}
|
||||
|
||||
$output = array_merge($_GET, $output);
|
||||
|
||||
if ($filter !== null) {
|
||||
$output = array_filter($output, function ($key) use ($filter) {
|
||||
return (in_array($key, $filter) === true);
|
||||
}, ARRAY_FILTER_USE_KEY);
|
||||
}
|
||||
|
||||
return $output;
|
||||
return ($filter !== null) ? array_intersect_key($output, array_flip($filter)) : array_merge($_GET, $output);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Input;
|
||||
|
||||
class InputFile implements IInputItem
|
||||
@@ -16,7 +17,7 @@ class InputFile implements IInputItem
|
||||
$this->index = $index;
|
||||
|
||||
// Make the name human friendly, by replace _ with space
|
||||
$this->name = ucfirst(str_replace('_', ' ', $this->index));
|
||||
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -28,23 +29,23 @@ class InputFile implements IInputItem
|
||||
*/
|
||||
public static function createFromArray(array $values)
|
||||
{
|
||||
if (!isset($values['index'])) {
|
||||
if (isset($values['index']) === false) {
|
||||
throw new \InvalidArgumentException('Index key is required');
|
||||
}
|
||||
|
||||
/* Easy way of ensuring that all indexes-are set and not filling the screen with isset() */
|
||||
|
||||
$values = array_merge([
|
||||
$values += [
|
||||
'tmp_name' => null,
|
||||
'type' => null,
|
||||
'size' => null,
|
||||
'name' => null,
|
||||
'error' => null,
|
||||
], $values);
|
||||
];
|
||||
|
||||
return (new static($values['index']))
|
||||
->setError($values['error'])
|
||||
->setSize($values['size'])
|
||||
->setError($values['error'])
|
||||
->setType($values['type'])
|
||||
->setTmpName($values['tmp_name'])
|
||||
->setFilename($values['name']);
|
||||
@@ -199,7 +200,7 @@ class InputFile implements IInputItem
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if an upload error occured.
|
||||
* Return true if an upload error occurred.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
@@ -256,14 +257,20 @@ class InputFile implements IInputItem
|
||||
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,
|
||||
'name' => $this->name,
|
||||
'error' => $this->error,
|
||||
'filename' => $this->filename,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ class InputItem implements IInputItem
|
||||
$this->value = $value;
|
||||
|
||||
// Make the name human friendly, by replace _ with space
|
||||
$this->name = ucfirst(str_replace('_', ' ', $this->index));
|
||||
$this->name = ucfirst(str_replace('_', ' ', strtolower($this->index)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Middleware;
|
||||
|
||||
use Pecee\CsrfToken;
|
||||
use Pecee\Http\Middleware\Exceptions\TokenMismatchException;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
use Pecee\Http\Security\CookieTokenProvider;
|
||||
use Pecee\Http\Security\ITokenProvider;
|
||||
|
||||
class BaseCsrfVerifier implements IMiddleware
|
||||
{
|
||||
@@ -12,15 +13,11 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
const HEADER_KEY = 'X-CSRF-TOKEN';
|
||||
|
||||
protected $except;
|
||||
protected $csrfToken;
|
||||
protected $token;
|
||||
protected $tokenProvider;
|
||||
|
||||
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();
|
||||
$this->tokenProvider = new CookieTokenProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,7 +27,7 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
*/
|
||||
protected function skip(Request $request)
|
||||
{
|
||||
if ($this->except === null || is_array($this->except) === false) {
|
||||
if ($this->except === null || count($this->except) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -42,9 +39,9 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
$url = rtrim($url, '/');
|
||||
if ($url[strlen($url) - 1] === '*') {
|
||||
$url = rtrim($url, '*');
|
||||
$skip = (stripos($request->getUri(), $url) === 0);
|
||||
$skip = (stripos($request->getUri()->getPath(), $url) === 0);
|
||||
} else {
|
||||
$skip = ($url === rtrim($request->getUri(), '/'));
|
||||
$skip = ($url === $request->getUri()->getPath());
|
||||
}
|
||||
|
||||
if ($skip === true) {
|
||||
@@ -55,7 +52,13 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
return false;
|
||||
}
|
||||
|
||||
public function handle(Request $request, ILoadableRoute &$route = null)
|
||||
/**
|
||||
* Handle request
|
||||
*
|
||||
* @param Request $request
|
||||
* @throws TokenMismatchException
|
||||
*/
|
||||
public function handle(Request $request)
|
||||
{
|
||||
|
||||
if ($this->skip($request) === false && in_array($request->getMethod(), ['post', 'put', 'delete'], false) === true) {
|
||||
@@ -67,34 +70,29 @@ class BaseCsrfVerifier implements IMiddleware
|
||||
$token = $request->getHeader(static::HEADER_KEY);
|
||||
}
|
||||
|
||||
if ($this->csrfToken->validate($token) === false) {
|
||||
throw new TokenMismatchException('Invalid csrf-token.');
|
||||
if ($this->tokenProvider->validate($token) === false) {
|
||||
throw new TokenMismatchException('Invalid CSRF-token.');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Refresh existing token
|
||||
$this->tokenProvider->refresh();
|
||||
|
||||
}
|
||||
|
||||
public function generateToken()
|
||||
public function getTokenProvider()
|
||||
{
|
||||
$token = CsrfToken::generateToken();
|
||||
$this->csrfToken->setToken($token);
|
||||
|
||||
return $token;
|
||||
return $this->tokenProvider;
|
||||
}
|
||||
|
||||
public function hasToken()
|
||||
/**
|
||||
* Set token provider
|
||||
* @param ITokenProvider $provider
|
||||
*/
|
||||
public function setTokenProvider(ITokenProvider $provider)
|
||||
{
|
||||
if ($this->token !== null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->csrfToken->hasToken();
|
||||
}
|
||||
|
||||
public function getToken()
|
||||
{
|
||||
return $this->token;
|
||||
$this->tokenProvider = $provider;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
public function handle(Request $request);
|
||||
|
||||
}
|
||||
+115
-31
@@ -1,22 +1,40 @@
|
||||
<?php
|
||||
|
||||
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 = [];
|
||||
private $data = [];
|
||||
protected $headers;
|
||||
protected $host;
|
||||
protected $uri;
|
||||
protected $method;
|
||||
protected $input;
|
||||
|
||||
/**
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $rewriteRoute;
|
||||
protected $rewriteUrl;
|
||||
|
||||
/**
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $loadedRoute;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->parseHeaders();
|
||||
$this->host = $this->getHeader('http-host');
|
||||
$this->uri = $this->getHeader('request-uri');
|
||||
$this->setHost($this->getHeader('http-host'));
|
||||
|
||||
// Check if special IIS header exist, otherwise use default.
|
||||
$this->setUri(new Uri($this->getHeader('unencoded-url', $this->getHeader('request-uri'))));
|
||||
|
||||
$this->input = new Input($this);
|
||||
$this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'), 'post'));
|
||||
}
|
||||
@@ -25,13 +43,7 @@ class Request
|
||||
{
|
||||
$this->headers = [];
|
||||
|
||||
$max = count($_SERVER) - 1;
|
||||
$keys = array_keys($_SERVER);
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$key = $keys[$i];
|
||||
$value = $_SERVER[$key];
|
||||
|
||||
foreach ($_SERVER as $key => $value) {
|
||||
$this->headers[strtolower($key)] = $value;
|
||||
$this->headers[strtolower(str_replace('_', '-', $key))] = $value;
|
||||
}
|
||||
@@ -44,7 +56,7 @@ class Request
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @return Uri
|
||||
*/
|
||||
public function getUri()
|
||||
{
|
||||
@@ -111,6 +123,17 @@ class Request
|
||||
return $this->getHeader('remote-addr');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get remote address/ip
|
||||
*
|
||||
* @alias static::getIp
|
||||
* @return string
|
||||
*/
|
||||
public function getRemoteAddr()
|
||||
{
|
||||
return $this->getIp();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get referer
|
||||
* @return string
|
||||
@@ -139,24 +162,7 @@ class Request
|
||||
*/
|
||||
public function getHeader($name, $defaultValue = null)
|
||||
{
|
||||
if (isset($this->headers[strtolower($name)])) {
|
||||
return $this->headers[strtolower($name)];
|
||||
}
|
||||
|
||||
$max = count($_SERVER) - 1;
|
||||
$keys = array_keys($_SERVER);
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$key = $keys[$i];
|
||||
$name = $_SERVER[$key];
|
||||
|
||||
if ($key === $name) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
return $defaultValue;
|
||||
return isset($this->headers[strtolower($name)]) ? $this->headers[strtolower($name)] : $defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -190,9 +196,9 @@ class Request
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $uri
|
||||
* @param Uri $uri
|
||||
*/
|
||||
public function setUri($uri)
|
||||
public function setUri(Uri $uri)
|
||||
{
|
||||
$this->uri = $uri;
|
||||
}
|
||||
@@ -213,6 +219,84 @@ class Request
|
||||
$this->method = $method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite route
|
||||
*
|
||||
* @param ILoadableRoute $route
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteRoute(ILoadableRoute $route)
|
||||
{
|
||||
$this->rewriteRoute = SimpleRouter::addDefaultNamespace($route);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rewrite route
|
||||
*
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getRewriteRoute()
|
||||
{
|
||||
return $this->rewriteRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rewrite url
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getRewriteUrl()
|
||||
{
|
||||
return $this->rewriteUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite url
|
||||
*
|
||||
* @param string $rewriteUrl
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteUrl($rewriteUrl)
|
||||
{
|
||||
$this->rewriteUrl = $rewriteUrl;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set rewrite callback
|
||||
* @param string $callback
|
||||
* @return static
|
||||
*/
|
||||
public function setRewriteCallback($callback)
|
||||
{
|
||||
return $this->setRewriteRoute(new RouteUrl($this->uri, $callback));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get loaded route
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getLoadedRoute()
|
||||
{
|
||||
return $this->loadedRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set loaded route
|
||||
*
|
||||
* @param ILoadableRoute $route
|
||||
* @return static
|
||||
*/
|
||||
public function setLoadedRoute(ILoadableRoute $route)
|
||||
{
|
||||
$this->loadedRoute = $route;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function __isset($name)
|
||||
{
|
||||
return array_key_exists($name, $this->data);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Response
|
||||
@@ -41,7 +42,7 @@ class Response
|
||||
|
||||
public function refresh()
|
||||
{
|
||||
$this->redirect($this->request->getUri());
|
||||
$this->redirect($this->request->getUri()->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,14 +83,21 @@ class Response
|
||||
}
|
||||
|
||||
/**
|
||||
* Json encode array
|
||||
* @param array $value
|
||||
* Json encode
|
||||
* @param array|\JsonSerializable $value
|
||||
* @param int $options JSON options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
|
||||
* @param int $dept JSON debt.
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function json(array $value)
|
||||
public function json($value, $options = null, $dept = 512)
|
||||
{
|
||||
$this->header('Content-Type: application/json');
|
||||
echo json_encode($value);
|
||||
die();
|
||||
if (($value instanceof \JsonSerializable) === false && is_array($value) === false) {
|
||||
throw new \InvalidArgumentException('Invalid type for parameter "value". Must be of type array or object implementing the \JsonSerializable interface.');
|
||||
}
|
||||
|
||||
$this->header('Content-type: application/json');
|
||||
echo json_encode($value, $options, $dept);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Security;
|
||||
|
||||
class CookieTokenProvider implements ITokenProvider
|
||||
{
|
||||
const CSRF_KEY = 'CSRF-TOKEN';
|
||||
|
||||
protected $token;
|
||||
protected $cookieTimeoutMinutes = 120;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->token = $this->getToken();
|
||||
|
||||
if ($this->token === null) {
|
||||
$this->token = $this->generateToken();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random identifier for CSRF token
|
||||
*
|
||||
* @throws \RuntimeException|\Exception
|
||||
* @return string
|
||||
*/
|
||||
public function generateToken()
|
||||
{
|
||||
if (function_exists('random_bytes') === true) {
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
$isSourceStrong = false;
|
||||
|
||||
$random = openssl_random_pseudo_bytes(32, $isSourceStrong);
|
||||
if ($isSourceStrong === false || $random === false) {
|
||||
throw new \RuntimeException('IV generation failed');
|
||||
}
|
||||
|
||||
return $random;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Overwrite this method to save the token to another storage like session etc.
|
||||
*
|
||||
* @param string $token
|
||||
*/
|
||||
public function setToken($token)
|
||||
{
|
||||
$this->token = $token;
|
||||
setcookie(static::CSRF_KEY, $token, time() + 60 * $this->cookieTimeoutMinutes, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get csrf token
|
||||
* @param string|null $defaultValue
|
||||
* @return string|null
|
||||
*/
|
||||
public function getToken($defaultValue = null)
|
||||
{
|
||||
$this->token = ($this->hasToken() === true) ? $_COOKIE[static::CSRF_KEY] : null;
|
||||
|
||||
return ($this->token !== null) ? $this->token : $defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh existing token
|
||||
*/
|
||||
public function refresh()
|
||||
{
|
||||
if ($this->token !== null) {
|
||||
$this->setToken($this->token);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the csrf token has been defined
|
||||
* @return bool
|
||||
*/
|
||||
public function hasToken()
|
||||
{
|
||||
return isset($_COOKIE[static::CSRF_KEY]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get timeout for cookie in minutes
|
||||
* @return int
|
||||
*/
|
||||
public function getCookieTimeoutMinutes()
|
||||
{
|
||||
return $this->cookieTimeoutMinutes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set cookie timeout in minutes
|
||||
* @param $minutes
|
||||
*/
|
||||
public function setCookieTimeoutMinutes($minutes)
|
||||
{
|
||||
$this->cookieTimeoutMinutes = $minutes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http\Security;
|
||||
|
||||
interface ITokenProvider
|
||||
{
|
||||
|
||||
/**
|
||||
* Refresh existing token
|
||||
*/
|
||||
public function refresh();
|
||||
|
||||
/**
|
||||
* Validate valid CSRF token
|
||||
*
|
||||
* @param string $token
|
||||
* @return bool
|
||||
*/
|
||||
public function validate($token);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\Http;
|
||||
|
||||
class Uri
|
||||
{
|
||||
private $originalUrl;
|
||||
private $data = [
|
||||
'scheme' => null,
|
||||
'host' => null,
|
||||
'port' => null,
|
||||
'user' => null,
|
||||
'pass' => null,
|
||||
'path' => null,
|
||||
'query' => null,
|
||||
'fragment' => null,
|
||||
];
|
||||
|
||||
public function __construct($url)
|
||||
{
|
||||
$this->originalUrl = $url;
|
||||
$this->data = $this->parseUrl($url) + $this->data;
|
||||
|
||||
if (isset($this->data['path']) === true && $this->data['path'] !== '/') {
|
||||
$this->data['path'] = rtrim($this->data['path'], '/') . '/';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if url is using a secure protocol like https
|
||||
* @return bool
|
||||
*/
|
||||
public function isSecure()
|
||||
{
|
||||
return (strtolower($this->getScheme()) === 'https');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if url is relative
|
||||
* @return bool
|
||||
*/
|
||||
public function isRelative()
|
||||
{
|
||||
return ($this->getHost() === null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url scheme
|
||||
* @return string|null
|
||||
*/
|
||||
public function getScheme()
|
||||
{
|
||||
return $this->data['scheme'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url host
|
||||
* @return string|null
|
||||
*/
|
||||
public function getHost()
|
||||
{
|
||||
return $this->data['host'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url port
|
||||
* @return int|null
|
||||
*/
|
||||
public function getPort()
|
||||
{
|
||||
return ($this->data['port'] !== null) ? (int)$this->data['port'] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse username from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getUserName()
|
||||
{
|
||||
return $this->data['user'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse password from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getPassword()
|
||||
{
|
||||
return $this->data['pass'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get path from url
|
||||
* @return string
|
||||
*/
|
||||
public function getPath()
|
||||
{
|
||||
return $this->data['path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get querystring from url
|
||||
* @return string|null
|
||||
*/
|
||||
public function getQueryString()
|
||||
{
|
||||
return $this->data['query'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get fragment from url (everything after #)
|
||||
* @return string|null
|
||||
*/
|
||||
public function getFragment()
|
||||
{
|
||||
return $this->data['fragment'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getOriginalUrl()
|
||||
{
|
||||
return $this->originalUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-8 aware parse_url() replacement.
|
||||
* @param string $url
|
||||
* @param int $component
|
||||
* @throws \InvalidArgumentException
|
||||
* @return array
|
||||
*/
|
||||
public function parseUrl($url, $component = -1)
|
||||
{
|
||||
$encodedUrl = preg_replace_callback(
|
||||
'/[^:\/@?&=#]+/u',
|
||||
function ($matches) {
|
||||
return urlencode($matches[0]);
|
||||
},
|
||||
$url
|
||||
);
|
||||
|
||||
$parts = parse_url($encodedUrl, $component);
|
||||
|
||||
if ($parts === false) {
|
||||
throw new \InvalidArgumentException('Malformed URL: ' . $url);
|
||||
}
|
||||
|
||||
return array_map('urldecode', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns data array with information about the url
|
||||
* @return array
|
||||
*/
|
||||
public function getData()
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return $this->getOriginalUrl();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,4 +3,5 @@ namespace Pecee\SimpleRouter\Exceptions;
|
||||
|
||||
class NotFoundHttpException extends HttpException
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
interface IGroupRoute extends IRoute
|
||||
@@ -13,6 +15,14 @@ interface IGroupRoute extends IRoute
|
||||
*/
|
||||
public function matchDomain(Request $request);
|
||||
|
||||
/**
|
||||
* Add exception handler
|
||||
*
|
||||
* @param IExceptionHandler|string $handler
|
||||
* @return static $this;
|
||||
*/
|
||||
public function addExceptionHandler($handler);
|
||||
|
||||
/**
|
||||
* Set exception-handlers for group
|
||||
*
|
||||
|
||||
@@ -20,9 +20,8 @@ interface ILoadableRoute extends IRoute
|
||||
* Loads and renders middlewares-classes
|
||||
*
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
*/
|
||||
public function loadMiddleware(Request $request, ILoadableRoute $route);
|
||||
public function loadMiddleware(Request $request);
|
||||
|
||||
public function getUrl();
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
interface IPartialGroupRoute
|
||||
{
|
||||
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -8,10 +9,11 @@ interface IRoute
|
||||
/**
|
||||
* Method called to check if a domain matches
|
||||
*
|
||||
* @param string $route
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
public function matchRoute(Request $request);
|
||||
public function matchRoute($route, Request $request);
|
||||
|
||||
/**
|
||||
* Called when route is matched.
|
||||
@@ -19,7 +21,7 @@ interface IRoute
|
||||
*
|
||||
* @param Request $request
|
||||
* @throws \Pecee\SimpleRouter\Exceptions\NotFoundHttpException
|
||||
* @return void
|
||||
* @return string
|
||||
*/
|
||||
public function renderRoute(Request $request);
|
||||
|
||||
@@ -172,7 +174,7 @@ interface IRoute
|
||||
* @param string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function setMiddleware($middleware);
|
||||
public function addMiddleware($middleware);
|
||||
|
||||
/**
|
||||
* Set middlewares array
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
@@ -23,50 +24,41 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
* Loads and renders middlewares-classes
|
||||
*
|
||||
* @param Request $request
|
||||
* @param ILoadableRoute $route
|
||||
* @throws HttpException
|
||||
*/
|
||||
public function loadMiddleware(Request $request, ILoadableRoute $route)
|
||||
public function loadMiddleware(Request $request)
|
||||
{
|
||||
if (count($this->getMiddlewares()) > 0) {
|
||||
$max = count($this->getMiddlewares());
|
||||
|
||||
$max = count($this->getMiddlewares());
|
||||
if ($max === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
|
||||
$middleware = $this->getMiddlewares()[$i];
|
||||
$middleware = $this->getMiddlewares()[$i];
|
||||
|
||||
if (is_object($middleware) === false) {
|
||||
$middleware = $this->loadClass($middleware);
|
||||
|
||||
if (!($middleware instanceof IMiddleware)) {
|
||||
throw new HttpException($middleware . ' must be instance of Middleware');
|
||||
}
|
||||
|
||||
$middleware->handle($request, $route);
|
||||
}
|
||||
|
||||
if (($middleware instanceof IMiddleware) === false) {
|
||||
throw new HttpException($middleware . ' must be inherit the IMiddleware interface');
|
||||
}
|
||||
|
||||
$middleware->handle($request);
|
||||
}
|
||||
}
|
||||
|
||||
public function matchRegex(Request $request, $url)
|
||||
{
|
||||
|
||||
/* Match on custom defined regular expression */
|
||||
|
||||
if ($this->regex === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parameters = [];
|
||||
|
||||
if (preg_match($this->regex, $request->getHost() . $url, $parameters) > 0) {
|
||||
|
||||
/* Remove global match */
|
||||
$this->parameters = array_slice($parameters, 1);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return (preg_match($this->regex, $request->getHost() . $url) > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -81,9 +73,9 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
if (strpos($this->url, $this->paramModifiers[0]) !== false) {
|
||||
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
if (preg_match_all('/' . $regex . '/is', $this->url, $matches)) {
|
||||
if (preg_match_all('/' . $regex . '/u', $this->url, $matches) > 0) {
|
||||
$this->parameters = array_fill_keys($matches[1], null);
|
||||
}
|
||||
}
|
||||
@@ -101,7 +93,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
* Used when calling the url() helper.
|
||||
*
|
||||
* @param string|null $method
|
||||
* @param array|null $parameters
|
||||
* @param string|array|null $parameters
|
||||
* @param string|null $name
|
||||
* @return string
|
||||
*/
|
||||
@@ -109,8 +101,10 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
{
|
||||
$url = $this->getUrl();
|
||||
|
||||
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
|
||||
$url = '//' . $this->getGroup()->getDomains()[0] . $url;
|
||||
$group = $this->getGroup();
|
||||
|
||||
if ($group !== null && count($group->getDomains()) !== 0) {
|
||||
$url = '//' . $group->getDomains()[0] . $url;
|
||||
}
|
||||
|
||||
/* Contains parameters that aren't recognized and will be appended at the end of the url */
|
||||
@@ -130,11 +124,17 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$param = $keys[$i];
|
||||
$value = $value = ($parameters !== null && array_key_exists($param, $parameters)) ? $parameters[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
|
||||
$value = '';
|
||||
} else {
|
||||
$p = (array)$parameters;
|
||||
$value = array_key_exists($param, $p) ? $p[$param] : $params[$param];
|
||||
|
||||
/* If parameter is specifically set to null - use the original-defined value */
|
||||
if ($value === null && isset($this->originalParameters[$param])) {
|
||||
$value = $this->originalParameters[$param];
|
||||
}
|
||||
}
|
||||
|
||||
if (stripos($url, $param1) !== false || stripos($url, $param) !== false) {
|
||||
@@ -145,9 +145,8 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
}
|
||||
}
|
||||
|
||||
$url .= join('/', $unknownParams);
|
||||
|
||||
|
||||
$url = '/' . ltrim($url, '/');
|
||||
$url .= implode('/', $unknownParams);
|
||||
|
||||
return rtrim($url, '/') . '/';
|
||||
}
|
||||
@@ -231,15 +230,18 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
|
||||
*/
|
||||
public function setSettings(array $values, $merge = false)
|
||||
{
|
||||
if (isset($values['as'])) {
|
||||
if (isset($values['as']) === true) {
|
||||
|
||||
$name = $values['as'];
|
||||
|
||||
if ($this->name !== null && $merge !== false) {
|
||||
$this->setName($values['as'] . '.' . $this->name);
|
||||
} else {
|
||||
$this->setName($values['as']);
|
||||
$name .= '.' . $this->name;
|
||||
}
|
||||
|
||||
$this->setName($name);
|
||||
}
|
||||
|
||||
if (isset($values['prefix'])) {
|
||||
if (isset($values['prefix']) === true) {
|
||||
$this->setUrl($values['prefix'] . $this->getUrl());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Middleware\IMiddleware;
|
||||
use Pecee\Http\Request;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
|
||||
abstract class Route implements IRoute
|
||||
{
|
||||
const PARAMETERS_REGEX_MATCH = '%s([\w]+)(\%s?)%s';
|
||||
const PARAMETERS_REGEX_FORMAT = '%s([\w]+)(\%s?)%s';
|
||||
const PARAMETERS_DEFAULT_REGEX = '[\w]+';
|
||||
|
||||
const REQUEST_TYPE_GET = 'get';
|
||||
const REQUEST_TYPE_POST = 'post';
|
||||
@@ -31,8 +34,15 @@ abstract class Route implements IRoute
|
||||
* @var bool
|
||||
*/
|
||||
protected $filterEmptyParams = false;
|
||||
|
||||
/**
|
||||
* Default regular expression used for parsing parameters.
|
||||
* @var string|null
|
||||
*/
|
||||
protected $defaultParameterRegex;
|
||||
protected $paramModifiers = '{}';
|
||||
protected $paramOptionalSymbol = '?';
|
||||
protected $urlRegex = '/^%s\/?$/u';
|
||||
protected $group;
|
||||
protected $parent;
|
||||
protected $callback;
|
||||
@@ -46,85 +56,128 @@ abstract class Route implements IRoute
|
||||
protected $originalParameters = [];
|
||||
protected $middlewares = [];
|
||||
|
||||
/**
|
||||
* Load class by name
|
||||
* @param string $name
|
||||
* @return mixed
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
protected function loadClass($name)
|
||||
{
|
||||
if (class_exists($name) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Class %s does not exist', $name), 404);
|
||||
throw new NotFoundHttpException(sprintf('Class "%s" does not exist', $name), 404);
|
||||
}
|
||||
|
||||
return new $name();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render route
|
||||
*
|
||||
* @param Request $request
|
||||
* @return string|mixed
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
public function renderRoute(Request $request)
|
||||
{
|
||||
if ($this->getCallback() !== null && is_callable($this->getCallback())) {
|
||||
$callback = $this->getCallback();
|
||||
|
||||
if ($callback === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Render callback function */
|
||||
if (is_callable($callback) === true) {
|
||||
|
||||
/* When the callback is a function */
|
||||
call_user_func_array($this->getCallback(), $this->getParameters());
|
||||
return call_user_func_array($callback, $this->getParameters());
|
||||
|
||||
} else {
|
||||
|
||||
/* When the callback is a method */
|
||||
$controller = explode('@', $this->getCallback());
|
||||
$className = $this->getNamespace() . '\\' . $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $controller[1];
|
||||
|
||||
if (method_exists($class, $method) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
|
||||
}
|
||||
|
||||
$parameters = $this->getParameters();
|
||||
|
||||
/* Filter parameters with null-value */
|
||||
|
||||
if ($this->filterEmptyParams === true) {
|
||||
$parameters = array_filter($parameters, function ($var) {
|
||||
return ($var !== null);
|
||||
});
|
||||
}
|
||||
|
||||
call_user_func_array([$class, $method], $parameters);
|
||||
}
|
||||
|
||||
/* When the callback is a class + method */
|
||||
$controller = explode('@', $callback);
|
||||
|
||||
$namespace = $this->getNamespace();
|
||||
|
||||
$className = ($namespace !== null && $controller[0][0] !== '\\') ? $namespace . '\\' . $controller[0] : $controller[0];
|
||||
|
||||
$class = $this->loadClass($className);
|
||||
$method = $controller[1];
|
||||
|
||||
if (method_exists($class, $method) === false) {
|
||||
throw new NotFoundHttpException(sprintf('Method "%s" does not exist in class "%s"', $method, $className), 404);
|
||||
}
|
||||
|
||||
$parameters = $this->getParameters();
|
||||
|
||||
/* Filter parameters with null-value */
|
||||
|
||||
if ($this->filterEmptyParams === true) {
|
||||
$parameters = array_filter($parameters, function ($var) {
|
||||
return ($var !== null);
|
||||
});
|
||||
}
|
||||
|
||||
return call_user_func_array([$class, $method], $parameters);
|
||||
}
|
||||
|
||||
protected function parseParameters($route, $url, $parameterRegex = '[\w]+')
|
||||
protected function parseParameters($route, $url, $parameterRegex = null)
|
||||
{
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
|
||||
|
||||
if (preg_match_all('/' . $regex . '/is', $route, $parameters)) {
|
||||
$parameters = [];
|
||||
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/is', rtrim($route, '/'));
|
||||
// Ensures that hostnames/domains will work with parameters
|
||||
$url = '/' . ltrim($url, '/');
|
||||
|
||||
if (preg_match_all('/' . $regex . '/u', $route, $parameters) > 0) {
|
||||
|
||||
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route);
|
||||
|
||||
foreach ($urlParts as $key => $t) {
|
||||
|
||||
$regex = '';
|
||||
|
||||
if ($key < (count($parameters[1]))) {
|
||||
if ($key < count($parameters[1])) {
|
||||
|
||||
$name = $parameters[1][$key];
|
||||
$regex = isset($this->where[$name]) ? $this->where[$name] : $parameterRegex;
|
||||
$regex = sprintf('\-?\/?(?P<%s>%s)', $name, $regex) . $parameters[2][$key];
|
||||
|
||||
/* If custom regex is defined, use that */
|
||||
if (isset($this->where[$name]) === true) {
|
||||
$regex = $this->where[$name];
|
||||
} else {
|
||||
|
||||
/* If method specific regex is defined use that, otherwise use the default parameter regex */
|
||||
if ($parameterRegex !== null) {
|
||||
$regex = $parameterRegex;
|
||||
} else {
|
||||
$regex = ($this->defaultParameterRegex === null) ? static::PARAMETERS_DEFAULT_REGEX : $this->defaultParameterRegex;
|
||||
}
|
||||
}
|
||||
|
||||
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
|
||||
|
||||
}
|
||||
|
||||
$urlParts[$key] = preg_quote($t, '/') . $regex;
|
||||
}
|
||||
|
||||
$urlRegex = join('', $urlParts);
|
||||
$urlRegex = implode('', $urlParts);
|
||||
|
||||
} else {
|
||||
$urlRegex = preg_quote($route, '/');
|
||||
}
|
||||
|
||||
if (preg_match('/^' . $urlRegex . '(\/?)$/is', $url, $matches) > 0) {
|
||||
if (preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) > 0) {
|
||||
|
||||
$values = [];
|
||||
|
||||
/* Only take matched parameters with name */
|
||||
foreach ($parameters[1] as $name) {
|
||||
$values[$name] = isset($matches[$name]) ? $matches[$name] : null;
|
||||
if (isset($parameters[1]) === true) {
|
||||
|
||||
/* Only take matched parameters with name */
|
||||
foreach ((array)$parameters[1] as $name) {
|
||||
$values[$name] = (isset($matches[$name]) && $matches[$name] !== '') ? $matches[$name] : null;
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
@@ -142,7 +195,7 @@ abstract class Route implements IRoute
|
||||
*/
|
||||
public function getIdentifier()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
return $this->callback;
|
||||
}
|
||||
|
||||
@@ -239,7 +292,7 @@ abstract class Route implements IRoute
|
||||
|
||||
public function getMethod()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[1];
|
||||
@@ -250,7 +303,7 @@ abstract class Route implements IRoute
|
||||
|
||||
public function getClass()
|
||||
{
|
||||
if (strpos($this->callback, '@') !== false) {
|
||||
if (is_string($this->callback) === true && strpos($this->callback, '@') !== false) {
|
||||
$tmp = explode('@', $this->callback);
|
||||
|
||||
return $tmp[0];
|
||||
@@ -321,18 +374,22 @@ abstract class Route implements IRoute
|
||||
$values['namespace'] = $this->namespace;
|
||||
}
|
||||
|
||||
if (count($this->requestMethods) > 0) {
|
||||
if (count($this->requestMethods) !== 0) {
|
||||
$values['method'] = $this->requestMethods;
|
||||
}
|
||||
|
||||
if (count($this->where) > 0) {
|
||||
if (count($this->where) !== 0) {
|
||||
$values['where'] = $this->where;
|
||||
}
|
||||
|
||||
if (count($this->middlewares) > 0) {
|
||||
if (count($this->middlewares) !== 0) {
|
||||
$values['middleware'] = $this->middlewares;
|
||||
}
|
||||
|
||||
if ($this->defaultParameterRegex !== null) {
|
||||
$values['defaultParameterRegex'] = $this->defaultParameterRegex;
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
@@ -345,27 +402,31 @@ abstract class Route implements IRoute
|
||||
*/
|
||||
public function setSettings(array $values, $merge = false)
|
||||
{
|
||||
if ($this->namespace === null && isset($values['namespace'])) {
|
||||
if ($this->namespace === null && isset($values['namespace']) === true) {
|
||||
$this->setNamespace($values['namespace']);
|
||||
}
|
||||
|
||||
if (isset($values['method'])) {
|
||||
if (isset($values['method']) === true) {
|
||||
$this->setRequestMethods(array_merge($this->requestMethods, (array)$values['method']));
|
||||
}
|
||||
|
||||
if (isset($values['where'])) {
|
||||
if (isset($values['where']) === true) {
|
||||
$this->setWhere(array_merge($this->where, (array)$values['where']));
|
||||
}
|
||||
|
||||
if (isset($values['parameters'])) {
|
||||
if (isset($values['parameters']) === true) {
|
||||
$this->setParameters(array_merge($this->parameters, (array)$values['parameters']));
|
||||
}
|
||||
|
||||
// Push middleware if multiple
|
||||
if (isset($values['middleware'])) {
|
||||
if (isset($values['middleware']) === true) {
|
||||
$this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares));
|
||||
}
|
||||
|
||||
if (isset($values['defaultParameterRegex']) === true) {
|
||||
$this->setDefaultParameterRegex($values['defaultParameterRegex']);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
@@ -415,7 +476,7 @@ abstract class Route implements IRoute
|
||||
/* Sort the parameters after the user-defined param order, if any */
|
||||
$parameters = [];
|
||||
|
||||
if (count($this->originalParameters) > 0) {
|
||||
if (count($this->originalParameters) !== 0) {
|
||||
$parameters = $this->originalParameters;
|
||||
}
|
||||
|
||||
@@ -434,7 +495,7 @@ abstract class Route implements IRoute
|
||||
* If this is the first time setting parameters we store them so we
|
||||
* later can organize the array, in case somebody tried to sort the array.
|
||||
*/
|
||||
if (count($parameters) > 0 && count($this->originalParameters) === 0) {
|
||||
if (count($parameters) !== 0 && count($this->originalParameters) === 0) {
|
||||
$this->originalParameters = $parameters;
|
||||
}
|
||||
|
||||
@@ -444,9 +505,10 @@ abstract class Route implements IRoute
|
||||
}
|
||||
|
||||
/**
|
||||
* Set middleware class-name
|
||||
* Add middleware class-name
|
||||
*
|
||||
* @param string $middleware
|
||||
* @deprecated This method is deprecated and will be removed in the near future.
|
||||
* @param IMiddleware|string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function setMiddleware($middleware)
|
||||
@@ -456,6 +518,19 @@ abstract class Route implements IRoute
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add middleware class-name
|
||||
*
|
||||
* @param IMiddleware|string $middleware
|
||||
* @return static
|
||||
*/
|
||||
public function addMiddleware($middleware)
|
||||
{
|
||||
$this->middlewares[] = $middleware;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set middlewares array
|
||||
*
|
||||
@@ -477,4 +552,28 @@ abstract class Route implements IRoute
|
||||
return $this->middlewares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set default regular expression used when matching parameters.
|
||||
* This is used when no custom parameter regex is found.
|
||||
*
|
||||
* @param string $regex
|
||||
* @return static $this
|
||||
*/
|
||||
public function setDefaultParameterRegex($regex)
|
||||
{
|
||||
$this->defaultParameterRegex = $regex;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default regular expression used when matching parameters.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getDefaultParameterRegex()
|
||||
{
|
||||
return $this->defaultParameterRegex;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -53,7 +54,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
if (strpos($name, '.') !== false) {
|
||||
$found = array_search(substr($name, strrpos($name, '.') + 1), $this->names, false);
|
||||
if ($found !== false) {
|
||||
$method = $found;
|
||||
$method = (string)$found;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +67,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
foreach (static::$requestTypes as $requestType) {
|
||||
|
||||
if (stripos($method, $requestType) === 0) {
|
||||
$method = substr($method, strlen($requestType));
|
||||
$method = (string)substr($method, strlen($requestType));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -74,43 +75,40 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
$method .= '/';
|
||||
}
|
||||
|
||||
if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) {
|
||||
$url .= '//' . $this->getGroup()->getDomains()[0];
|
||||
$group = $this->getGroup();
|
||||
|
||||
if ($group !== null && count($group->getDomains()) !== 0) {
|
||||
$url .= '//' . $group->getDomains()[0];
|
||||
}
|
||||
|
||||
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters);
|
||||
$url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . implode('/', $parameters);
|
||||
|
||||
return '/' . trim($url, '/') . '/';
|
||||
}
|
||||
|
||||
public function matchRoute(Request $request)
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
if ($this->matchRegex($request, $url) === true) {
|
||||
return true;
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (stripos($url, $this->url) === 0 && strtolower($url) === strtolower($this->url)) {
|
||||
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
|
||||
$path = explode('/', $strippedUrl);
|
||||
|
||||
$strippedUrl = trim(str_ireplace($this->url, '/', $url), '/');
|
||||
if (count($path) !== 0) {
|
||||
|
||||
$path = explode('/', $strippedUrl);
|
||||
$method = (isset($path[0]) === false || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
|
||||
$this->method = $request->getMethod() . ucfirst($method);
|
||||
|
||||
if (count($path) > 0) {
|
||||
$this->parameters = array_slice($path, 1);
|
||||
|
||||
$method = (!isset($path[0]) || trim($path[0]) === '') ? $this->defaultMethod : $path[0];
|
||||
$this->method = $method;
|
||||
// Set callback
|
||||
$this->setCallback($this->controller . '@' . $this->method);
|
||||
|
||||
$this->parameters = array_slice($path, 1);
|
||||
|
||||
// Set callback
|
||||
$this->setCallback($this->controller . '@' . $this->method);
|
||||
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -171,7 +169,7 @@ class RouteController extends LoadableRoute implements IControllerRoute
|
||||
*/
|
||||
public function setSettings(array $values, $merge = false)
|
||||
{
|
||||
if (isset($values['names'])) {
|
||||
if (isset($values['names']) === true) {
|
||||
$this->names = $values['names'];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RouteGroup extends Route implements IGroupRoute
|
||||
@@ -18,7 +20,7 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
*/
|
||||
public function matchDomain(Request $request)
|
||||
{
|
||||
if (count($this->domains) === 0) {
|
||||
if ($this->domains === null || count($this->domains) === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -26,7 +28,7 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
|
||||
$parameters = $this->parseParameters($domain, $request->getHost(), '.*');
|
||||
|
||||
if ($parameters !== null && count($parameters) > 0) {
|
||||
if ($parameters !== null && count($parameters) !== 0) {
|
||||
|
||||
$this->parameters = $parameters;
|
||||
|
||||
@@ -40,19 +42,33 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
/**
|
||||
* Method called to check if route matches
|
||||
*
|
||||
* @param string $url
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
public function matchRoute(Request $request)
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
/* Skip if prefix doesn't match */
|
||||
if ($this->prefix !== null && stripos($request->getUri(), $this->prefix) === false) {
|
||||
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->matchDomain($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add exception handler
|
||||
*
|
||||
* @param IExceptionHandler|string $handler
|
||||
* @return static $this
|
||||
*/
|
||||
public function addExceptionHandler($handler)
|
||||
{
|
||||
$this->exceptionHandlers[] = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set exception-handlers for group
|
||||
*
|
||||
@@ -130,24 +146,27 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
public function setSettings(array $values, $merge = false)
|
||||
{
|
||||
|
||||
if (isset($values['prefix'])) {
|
||||
if (isset($values['prefix']) === true) {
|
||||
$this->setPrefix($values['prefix'] . $this->prefix);
|
||||
}
|
||||
|
||||
if (isset($values['exceptionHandler'])) {
|
||||
if ($merge === false && isset($values['exceptionHandler']) === true) {
|
||||
$this->setExceptionHandlers((array)$values['exceptionHandler']);
|
||||
}
|
||||
|
||||
if (isset($values['domain'])) {
|
||||
if ($merge === false && isset($values['domain']) === true) {
|
||||
$this->setDomains((array)$values['domain']);
|
||||
}
|
||||
|
||||
if (isset($values['as'])) {
|
||||
if (isset($values['as']) === true) {
|
||||
|
||||
$name = $values['as'];
|
||||
|
||||
if ($this->name !== null && $merge !== false) {
|
||||
$this->name = $values['as'] . '.' . $this->name;
|
||||
} else {
|
||||
$this->name = $values['as'];
|
||||
$name .= '.' . $this->name;
|
||||
}
|
||||
|
||||
$this->name = $name;
|
||||
}
|
||||
|
||||
parent::setSettings($values, $merge);
|
||||
@@ -172,7 +191,7 @@ class RouteGroup extends Route implements IGroupRoute
|
||||
$values['as'] = $this->name;
|
||||
}
|
||||
|
||||
if (count($this->parameters) > 0) {
|
||||
if (count($this->parameters) !== 0) {
|
||||
$values['parameters'] = $this->parameters;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
|
||||
class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
|
||||
{
|
||||
protected $urlRegex = '/^%s\/?/u';
|
||||
|
||||
/**
|
||||
* Method called to check if route matches
|
||||
*
|
||||
* @param string $url
|
||||
* @param Request $request
|
||||
* @return bool
|
||||
*/
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
if ($this->prefix !== null) {
|
||||
/* Parse parameters from current route */
|
||||
$parameters = $this->parseParameters($this->prefix, $url);
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Set the parameters */
|
||||
$this->setParameters((array)$parameters);
|
||||
}
|
||||
|
||||
return $this->matchDomain($request);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -53,7 +54,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
/* Remove method/type */
|
||||
if (strpos($name, '.') !== false) {
|
||||
$name = substr($name, 0, strrpos($name, '.'));
|
||||
$name = (string)substr($name, 0, strrpos($name, '.'));
|
||||
}
|
||||
|
||||
return (strtolower($this->name) === strtolower($name));
|
||||
@@ -61,9 +62,9 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
|
||||
public function findUrl($method = null, $parameters = null, $name = null)
|
||||
{
|
||||
$method = array_search($name, $this->names, false);
|
||||
if ($method !== false) {
|
||||
return rtrim($this->url . $this->urls[$method], '/') . '/';
|
||||
$url = array_search($name, $this->names, false);
|
||||
if ($url !== false) {
|
||||
return rtrim($this->url . $this->urls[$url], '/') . '/';
|
||||
}
|
||||
|
||||
return $this->url;
|
||||
@@ -76,48 +77,50 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
return true;
|
||||
}
|
||||
|
||||
public function matchRoute(Request $request)
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$domainMatch = $this->matchRegex($request, $url);
|
||||
if ($domainMatch !== null) {
|
||||
return $domainMatch;
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
if ($regexMatch === false || (stripos($url, $this->url) !== 0 && strtolower($url) !== strtolower($this->url))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$route = rtrim($this->url, '/') . '/{id?}/{action?}';
|
||||
|
||||
$parameters = $this->parseParameters($route, $url);
|
||||
if ($parameters === null) {
|
||||
/* Parse parameters from current route */
|
||||
$this->parameters = $this->parseParameters($route, $url);
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($regexMatch === null && $this->parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->parameters = (array)$parameters;
|
||||
$action = strtolower(trim($this->parameters['action']));
|
||||
$id = $this->parameters['id'];
|
||||
|
||||
$action = isset($this->parameters['action']) ? $this->parameters['action'] : null;
|
||||
// Remove action parameter
|
||||
unset($this->parameters['action']);
|
||||
|
||||
$method = $request->getMethod();
|
||||
|
||||
// Delete
|
||||
if ($method === static::REQUEST_TYPE_DELETE && isset($this->parameters['id'])) {
|
||||
if ($method === static::REQUEST_TYPE_DELETE && $id !== null) {
|
||||
return $this->call($this->methodNames['destroy']);
|
||||
}
|
||||
|
||||
// Update
|
||||
if (isset($this->parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false)) {
|
||||
if ($id !== null && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT], false) === true) {
|
||||
return $this->call($this->methodNames['update']);
|
||||
}
|
||||
|
||||
// Edit
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id']) && strtolower($action) === 'edit') {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null && $action === 'edit') {
|
||||
return $this->call($this->methodNames['edit']);
|
||||
}
|
||||
|
||||
// Create
|
||||
if ($method === static::REQUEST_TYPE_GET && strtolower($action) === 'create') {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id === 'create') {
|
||||
return $this->call($this->methodNames['create']);
|
||||
}
|
||||
|
||||
@@ -127,7 +130,7 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
}
|
||||
|
||||
// Show
|
||||
if ($method === static::REQUEST_TYPE_GET && isset($this->parameters['id'])) {
|
||||
if ($method === static::REQUEST_TYPE_GET && $id !== null) {
|
||||
return $this->call($this->methodNames['show']);
|
||||
}
|
||||
|
||||
@@ -203,11 +206,11 @@ class RouteResource extends LoadableRoute implements IControllerRoute
|
||||
*/
|
||||
public function setSettings(array $values, $merge = false)
|
||||
{
|
||||
if (isset($values['names'])) {
|
||||
if (isset($values['names']) === true) {
|
||||
$this->names = $values['names'];
|
||||
}
|
||||
|
||||
if (isset($values['methods'])) {
|
||||
if (isset($values['methods']) === true) {
|
||||
$this->methodNames = $values['methods'];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter\Route;
|
||||
|
||||
use Pecee\Http\Request;
|
||||
@@ -11,27 +12,27 @@ class RouteUrl extends LoadableRoute
|
||||
$this->setCallback($callback);
|
||||
}
|
||||
|
||||
public function matchRoute(Request $request)
|
||||
public function matchRoute($url, Request $request)
|
||||
{
|
||||
$url = parse_url(urldecode($request->getUri()), PHP_URL_PATH);
|
||||
$url = rtrim($url, '/') . '/';
|
||||
|
||||
/* Match global regular-expression for route */
|
||||
$domainMatch = $this->matchRegex($request, $url);
|
||||
if ($domainMatch !== null) {
|
||||
return $domainMatch;
|
||||
}
|
||||
$regexMatch = $this->matchRegex($request, $url);
|
||||
|
||||
/* Make regular expression based on route */
|
||||
$parameters = $this->parseParameters($this->url, $url);
|
||||
if ($parameters === null) {
|
||||
if ($regexMatch === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->setParameters($parameters);
|
||||
/* Parse parameters from current route */
|
||||
$parameters = $this->parseParameters($this->url, $url);
|
||||
|
||||
/* If no custom regular expression or parameters was found on this route, we stop */
|
||||
if ($regexMatch === null && $parameters === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Set the parameters */
|
||||
$this->setParameters((array)$parameters);
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+179
-138
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Handlers\IExceptionHandler;
|
||||
@@ -9,6 +10,7 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
use Pecee\SimpleRouter\Route\IControllerRoute;
|
||||
use Pecee\SimpleRouter\Route\IGroupRoute;
|
||||
use Pecee\SimpleRouter\Route\ILoadableRoute;
|
||||
use Pecee\SimpleRouter\Route\IPartialGroupRoute;
|
||||
use Pecee\SimpleRouter\Route\IRoute;
|
||||
|
||||
class Router
|
||||
@@ -69,38 +71,7 @@ class Router
|
||||
*/
|
||||
protected $exceptionHandlers;
|
||||
|
||||
/**
|
||||
* The current loaded route
|
||||
* @var ILoadableRoute|null
|
||||
*/
|
||||
protected $loadedRoute;
|
||||
|
||||
/**
|
||||
* List over route changes (to avoid endless-looping)
|
||||
* @var array
|
||||
*/
|
||||
protected $routeRewrites = [];
|
||||
|
||||
/**
|
||||
* If the route has been rewritten/changed this property will contain the original url.
|
||||
* @var string
|
||||
*/
|
||||
protected $originalUrl;
|
||||
|
||||
/**
|
||||
* Get current router instance
|
||||
* @return static
|
||||
*/
|
||||
public static function getInstance()
|
||||
{
|
||||
if (static::$instance === null) {
|
||||
static::$instance = new static();
|
||||
}
|
||||
|
||||
return static::$instance;
|
||||
}
|
||||
|
||||
protected function __construct()
|
||||
public function __construct()
|
||||
{
|
||||
$this->reset();
|
||||
}
|
||||
@@ -143,6 +114,7 @@ class Router
|
||||
* @param array $routes
|
||||
* @param IGroupRoute|null $group
|
||||
* @param IRoute|null $parent
|
||||
* @throws NotFoundHttpException
|
||||
*/
|
||||
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null)
|
||||
{
|
||||
@@ -151,39 +123,12 @@ class Router
|
||||
|
||||
$exceptionHandlers = [];
|
||||
|
||||
/* @var $route IRoute */
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$route = $routes[$i];
|
||||
|
||||
/* @var $route IGroupRoute */
|
||||
if ($route instanceof IGroupRoute) {
|
||||
|
||||
$group = $route;
|
||||
|
||||
if ($route->getCallback() !== null && is_callable($route->getCallback())) {
|
||||
|
||||
$this->processingRoute = true;
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
|
||||
if ($route->matchRoute($this->request) === true) {
|
||||
|
||||
/* Add exception handlers */
|
||||
if (count($route->getExceptionHandlers()) > 0) {
|
||||
$exceptionHandlers += $route->getExceptionHandlers();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($group !== null) {
|
||||
|
||||
/* Add the parent group */
|
||||
$route->setGroup($group);
|
||||
}
|
||||
|
||||
if ($parent !== null) {
|
||||
|
||||
/* Add the parent route */
|
||||
@@ -194,15 +139,50 @@ class Router
|
||||
|
||||
}
|
||||
|
||||
if ($group !== null) {
|
||||
|
||||
/* Add the parent group */
|
||||
$route->setGroup($group);
|
||||
}
|
||||
|
||||
/* @var $route IGroupRoute */
|
||||
if ($route instanceof IGroupRoute) {
|
||||
|
||||
$group = $route;
|
||||
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
|
||||
/* Add exception handlers */
|
||||
if (count($route->getExceptionHandlers()) !== 0) {
|
||||
/** @noinspection AdditionOperationOnArraysInspection */
|
||||
$exceptionHandlers += $route->getExceptionHandlers();
|
||||
}
|
||||
|
||||
/* Only render partial group if it matches */
|
||||
if ($route instanceof IPartialGroupRoute) {
|
||||
$this->processingRoute = true;
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (($route instanceof IPartialGroupRoute) === false) {
|
||||
$this->processingRoute = true;
|
||||
$route->renderRoute($this->request);
|
||||
$this->processingRoute = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($route instanceof ILoadableRoute) {
|
||||
|
||||
/* Add the route to the map, so we can find the active one when all routes has been loaded */
|
||||
$this->processedRoutes[] = $route;
|
||||
}
|
||||
|
||||
if (count($this->routeStack) > 0) {
|
||||
if (count($this->routeStack) !== 0) {
|
||||
|
||||
/* Pop and grap the routes added when executing group callback earlier */
|
||||
/* Pop and grab the routes added when executing group callback earlier */
|
||||
$stack = $this->routeStack;
|
||||
$this->routeStack = [];
|
||||
|
||||
@@ -211,80 +191,99 @@ class Router
|
||||
}
|
||||
}
|
||||
|
||||
$this->exceptionHandlers = array_unique(array_merge($exceptionHandlers, $this->exceptionHandlers));
|
||||
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load routes
|
||||
* @throws NotFoundHttpException
|
||||
* @return void
|
||||
*/
|
||||
public function loadRoutes()
|
||||
{
|
||||
/* Initialize boot-managers */
|
||||
if (count($this->bootManagers) !== 0) {
|
||||
|
||||
$max = count($this->bootManagers) - 1;
|
||||
|
||||
/* @var $manager IRouterBootManager */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
$manager = $this->bootManagers[$i];
|
||||
$manager->boot($this->request);
|
||||
}
|
||||
}
|
||||
|
||||
/* Loop through each route-request */
|
||||
$this->processRoutes($this->routes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes the request
|
||||
*
|
||||
* @param bool $rewrite
|
||||
* @return string|mixed
|
||||
* @throws HttpException
|
||||
* @throws \Exception
|
||||
*/
|
||||
public function routeRequest($rewrite = false)
|
||||
{
|
||||
$this->loadedRoute = null;
|
||||
$routeNotAllowed = false;
|
||||
|
||||
try {
|
||||
/* Initialize boot-managers */
|
||||
if (count($this->bootManagers) > 0) {
|
||||
|
||||
$max = count($this->bootManagers) - 1;
|
||||
|
||||
/* @var $manager IRouterBootManager */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$manager = $this->bootManagers[$i];
|
||||
|
||||
$this->request = $manager->boot($this->request);
|
||||
|
||||
if (!($this->request instanceof Request)) {
|
||||
throw new HttpException('Bootmanager "' . get_class($manager) . '" must return instance of ' . Request::class, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($rewrite === false) {
|
||||
|
||||
/* Loop through each route-request */
|
||||
$this->processRoutes($this->routes);
|
||||
$this->loadRoutes();
|
||||
|
||||
if ($this->csrfVerifier !== null) {
|
||||
|
||||
/* Verify csrf token for request */
|
||||
$this->csrfVerifier->handle($this->request);
|
||||
}
|
||||
|
||||
$this->originalUrl = $this->request->getUri();
|
||||
}
|
||||
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
$max = count($this->processedRoutes) - 1;
|
||||
|
||||
/* @var $route IRoute */
|
||||
/* @var $route ILoadableRoute */
|
||||
for ($i = $max; $i >= 0; $i--) {
|
||||
|
||||
$route = $this->processedRoutes[$i];
|
||||
|
||||
/* If the route matches */
|
||||
if ($route->matchRoute($this->request) === true) {
|
||||
if ($route->matchRoute($url, $this->request) === true) {
|
||||
|
||||
/* Check if request method matches */
|
||||
if (count($route->getRequestMethods()) > 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
|
||||
if (count($route->getRequestMethods()) !== 0 && in_array($this->request->getMethod(), $route->getRequestMethods(), false) === false) {
|
||||
$routeNotAllowed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->loadedRoute = $route;
|
||||
$this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute);
|
||||
$route->loadMiddleware($this->request);
|
||||
|
||||
/* If the request has changed, we reinitialize the router */
|
||||
if ($this->request->getUri() !== $this->originalUrl && in_array($this->request->getUri(), $this->routeRewrites) === false) {
|
||||
$this->routeRewrites[] = $this->request->getUri();
|
||||
$this->routeRequest(true);
|
||||
$rewriteRoute = $this->request->getRewriteRoute();
|
||||
|
||||
return;
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
/* If the request has changed */
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
|
||||
unset($this->processedRoutes[$i]);
|
||||
$this->processedRoutes = array_values($this->processedRoutes);
|
||||
|
||||
return $this->routeRequest(true);
|
||||
}
|
||||
|
||||
/* Render route */
|
||||
$routeNotAllowed = false;
|
||||
$this->request->setUri($this->originalUrl);
|
||||
$this->loadedRoute->renderRoute($this->request);
|
||||
$this->request->setLoadedRoute($route);
|
||||
|
||||
break;
|
||||
return $route->renderRoute($this->request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,38 +292,72 @@ class Router
|
||||
}
|
||||
|
||||
if ($routeNotAllowed === true) {
|
||||
$this->handleException(new HttpException('Route or method not allowed', 403));
|
||||
$message = sprintf('Route "%s" or method "%s" not allowed.', $this->request->getUri()->getPath(), $this->request->getMethod());
|
||||
$this->handleException(new HttpException($message, 403));
|
||||
}
|
||||
|
||||
if ($this->loadedRoute === null) {
|
||||
$this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404));
|
||||
if ($this->request->getLoadedRoute() === null) {
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
if ($rewriteUrl !== null) {
|
||||
$message = sprintf('Route not found: "%s" (rewrite from: "%s")', $rewriteUrl, $this->request->getUri()->getPath());
|
||||
} else {
|
||||
$message = sprintf('Route not found: "%s"', $this->request->getUri()->getPath());
|
||||
}
|
||||
|
||||
$this->handleException(new NotFoundHttpException($message, 404));
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \Exception $e
|
||||
* @throws HttpException
|
||||
* @throws \Exception
|
||||
* @return string
|
||||
*/
|
||||
protected function handleException(\Exception $e)
|
||||
{
|
||||
$max = count($this->exceptionHandlers);
|
||||
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUri()->getPath();
|
||||
|
||||
/* @var $handler IExceptionHandler */
|
||||
for ($i = 0; $i < $max; $i++) {
|
||||
foreach ($this->exceptionHandlers as $key => $handler) {
|
||||
|
||||
$handler = $this->exceptionHandlers[$i];
|
||||
if (is_object($handler) === false) {
|
||||
$handler = new $handler();
|
||||
}
|
||||
|
||||
$handler = new $handler();
|
||||
|
||||
if (!($handler instanceof IExceptionHandler)) {
|
||||
if (($handler instanceof IExceptionHandler) === false) {
|
||||
throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500);
|
||||
}
|
||||
|
||||
$request = $handler->handleError($this->request, $this->loadedRoute, $e);
|
||||
try {
|
||||
|
||||
/* If the request has changed */
|
||||
if ($request !== null && $this->request->getUri() !== $this->originalUrl && in_array($request->getUri(), $this->routeRewrites) === false) {
|
||||
$this->request = $request;
|
||||
$this->routeRewrites[] = $request->getUri();
|
||||
$this->routeRequest(true);
|
||||
if ($handler->handleError($this->request, $e) !== null) {
|
||||
|
||||
$rewriteRoute = $this->request->getRewriteRoute();
|
||||
|
||||
if ($rewriteRoute !== null) {
|
||||
$rewriteRoute->loadMiddleware($this->request);
|
||||
|
||||
return $rewriteRoute->renderRoute($this->request);
|
||||
}
|
||||
|
||||
$rewriteUrl = $this->request->getRewriteUrl();
|
||||
|
||||
/* If the request has changed */
|
||||
if ($rewriteUrl !== null && $rewriteUrl !== $url) {
|
||||
unset($this->exceptionHandlers[$key]);
|
||||
$this->exceptionHandlers = array_values($this->exceptionHandlers);
|
||||
|
||||
return $this->routeRequest(true);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (\Exception $e) {
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,11 +366,11 @@ class Router
|
||||
|
||||
public function arrayToParams(array $getParams = [], $includeEmpty = true)
|
||||
{
|
||||
if (count($getParams) > 0) {
|
||||
if (count($getParams) !== 0) {
|
||||
|
||||
if ($includeEmpty === false) {
|
||||
$getParams = array_filter($getParams, function ($item) {
|
||||
return (!empty($item));
|
||||
return (trim($item) !== '');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -373,7 +406,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (strpos($name, '@') !== false) {
|
||||
if (is_string($name) === true && strpos($name, '@') !== false) {
|
||||
list($controller, $method) = array_map('strtolower', explode('@', $name));
|
||||
|
||||
if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) {
|
||||
@@ -382,7 +415,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Check if callback matches (if it's not a function) */
|
||||
if (strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) {
|
||||
if (is_string($name) === true && is_string($route->getCallback()) && strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && is_callable($route->getCallback()) === false) {
|
||||
|
||||
/* Check if the entire callback is matching */
|
||||
if (strpos($route->getCallback(), $name) === 0 || strtolower($route->getCallback()) === strtolower($name)) {
|
||||
@@ -423,6 +456,10 @@ class Router
|
||||
throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null');
|
||||
}
|
||||
|
||||
if ($name === '' && $parameters === '') {
|
||||
return '/';
|
||||
}
|
||||
|
||||
/* Only merge $_GET when all parameters are null */
|
||||
if ($name === null && $parameters === null && $getParams === null) {
|
||||
$getParams = $_GET;
|
||||
@@ -432,14 +469,14 @@ class Router
|
||||
|
||||
/* Return current route if no options has been specified */
|
||||
if ($name === null && $parameters === null) {
|
||||
$url = rtrim(parse_url($this->request->getUri(), PHP_URL_PATH), '/');
|
||||
|
||||
return (($url === '') ? '/' : $url . '/') . $this->arrayToParams($getParams);
|
||||
return $this->request->getUri()->getPath() . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
$loadedRoute = $this->request->getLoadedRoute();
|
||||
|
||||
/* If nothing is defined and a route is loaded we use that */
|
||||
if ($name === null && $this->loadedRoute !== null) {
|
||||
return $this->loadedRoute->findUrl($this->loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
|
||||
if ($name === null && $loadedRoute !== null) {
|
||||
return $loadedRoute->findUrl($loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
/* We try to find a match on the given name */
|
||||
@@ -450,7 +487,7 @@ class Router
|
||||
}
|
||||
|
||||
/* Using @ is most definitely a controller@method or alias@method */
|
||||
if (strpos($name, '@') !== false) {
|
||||
if (is_string($name) === true && strpos($name, '@') !== false) {
|
||||
list($controller, $method) = explode('@', $name);
|
||||
|
||||
/* Loop through all the routes to see if we can find a match */
|
||||
@@ -463,7 +500,7 @@ class Router
|
||||
$route = $this->processedRoutes[$i];
|
||||
|
||||
/* Check if the route contains the name/alias */
|
||||
if ($route->hasName($controller)) {
|
||||
if ($route->hasName($controller) === true) {
|
||||
return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams);
|
||||
}
|
||||
|
||||
@@ -476,7 +513,7 @@ class Router
|
||||
}
|
||||
|
||||
/* No result so we assume that someone is using a hardcoded url and join everything together. */
|
||||
$url = trim(join('/', array_merge((array)$name, (array)$parameters)), '/');
|
||||
$url = trim(implode('/', array_merge((array)$name, (array)$parameters)), '/');
|
||||
|
||||
return (($url === '') ? '/' : '/' . $url . '/') . $this->arrayToParams($getParams);
|
||||
}
|
||||
@@ -516,6 +553,19 @@ class Router
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set routes
|
||||
*
|
||||
* @param array $routes
|
||||
* @return static $this
|
||||
*/
|
||||
public function setRoutes(array $routes)
|
||||
{
|
||||
$this->routes = $routes;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current request
|
||||
*
|
||||
@@ -548,13 +598,4 @@ class Router
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get loaded route
|
||||
* @return ILoadableRoute|null
|
||||
*/
|
||||
public function getLoadedRoute()
|
||||
{
|
||||
return $this->loadedRoute;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,16 @@
|
||||
* This class is added so calls can be made statically like Router::get() making the code look pretty.
|
||||
* It also adds some extra functionality like default-namespace.
|
||||
*/
|
||||
|
||||
namespace Pecee\SimpleRouter;
|
||||
|
||||
use Pecee\Handlers\CallbackExceptionHandler;
|
||||
use Pecee\Http\Middleware\BaseCsrfVerifier;
|
||||
use Pecee\Http\Response;
|
||||
use Pecee\SimpleRouter\Exceptions\HttpException;
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException;
|
||||
use Pecee\SimpleRouter\Route\IRoute;
|
||||
use Pecee\SimpleRouter\Route\RoutePartialGroup;
|
||||
use Pecee\SimpleRouter\Route\RouteController;
|
||||
use Pecee\SimpleRouter\Route\RouteGroup;
|
||||
use Pecee\SimpleRouter\Route\RouteResource;
|
||||
@@ -33,15 +36,20 @@ class SimpleRouter
|
||||
*/
|
||||
protected static $response;
|
||||
|
||||
/**
|
||||
* Router instance
|
||||
* @var Router
|
||||
*/
|
||||
protected static $router;
|
||||
|
||||
/**
|
||||
* Start/route request
|
||||
*
|
||||
* @throws HttpException
|
||||
* @throws NotFoundHttpException
|
||||
* @throws HttpException|NotFoundHttpException|\Exception
|
||||
*/
|
||||
public static function start()
|
||||
{
|
||||
static::router()->routeRequest();
|
||||
echo static::router()->routeRequest();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -163,14 +171,41 @@ class SimpleRouter
|
||||
*/
|
||||
public static function group(array $settings = [], \Closure $callback)
|
||||
{
|
||||
if (is_callable($callback) === false) {
|
||||
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
|
||||
}
|
||||
|
||||
$group = new RouteGroup();
|
||||
$group->setCallback($callback);
|
||||
$group->setSettings($settings);
|
||||
|
||||
static::router()->addRoute($group);
|
||||
|
||||
return $group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Special group that has the same benefits as group but supports
|
||||
* parameters and which are only rendered when the url matches.
|
||||
*
|
||||
* @param string $url
|
||||
* @param array $settings
|
||||
* @param \Closure $callback
|
||||
* @throws \InvalidArgumentException
|
||||
* @return RoutePartialGroup
|
||||
*/
|
||||
public static function partialGroup($url, \Closure $callback, array $settings = [])
|
||||
{
|
||||
if (is_callable($callback) === false) {
|
||||
throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported');
|
||||
}
|
||||
|
||||
$settings['prefix'] = $url;
|
||||
|
||||
$group = new RoutePartialGroup();
|
||||
$group->setSettings($settings);
|
||||
$group->setCallback($callback);
|
||||
|
||||
static::router()->addRoute($group);
|
||||
|
||||
return $group;
|
||||
@@ -212,7 +247,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl
|
||||
* @return RouteUrl|IRoute
|
||||
*/
|
||||
public static function match(array $requestMethods, $url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -235,7 +270,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string|\Closure $callback
|
||||
* @param array|null $settings
|
||||
* @return RouteUrl
|
||||
* @return RouteUrl|IRoute
|
||||
*/
|
||||
public static function all($url, $callback, array $settings = null)
|
||||
{
|
||||
@@ -257,7 +292,7 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteController
|
||||
* @return RouteController|IRoute
|
||||
*/
|
||||
public static function controller($url, $controller, array $settings = null)
|
||||
{
|
||||
@@ -279,11 +314,12 @@ class SimpleRouter
|
||||
* @param string $url
|
||||
* @param string $controller
|
||||
* @param array|null $settings
|
||||
* @return RouteResource
|
||||
* @return RouteResource|IRoute
|
||||
*/
|
||||
public static function resource($url, $controller, array $settings = null)
|
||||
{
|
||||
$route = new RouteResource($url, $controller);
|
||||
$route = static::addDefaultNamespace($route);
|
||||
|
||||
if ($settings !== null) {
|
||||
$route->setSettings($settings);
|
||||
@@ -294,6 +330,28 @@ class SimpleRouter
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add exception callback handler.
|
||||
*
|
||||
* @param \Closure $callback
|
||||
* @return CallbackExceptionHandler $callbackHandler
|
||||
*/
|
||||
public static function error(\Closure $callback)
|
||||
{
|
||||
$routes = static::router()->getRoutes();
|
||||
|
||||
$callbackHandler = new CallbackExceptionHandler($callback);
|
||||
|
||||
$group = new RouteGroup();
|
||||
$group->addExceptionHandler($callbackHandler);
|
||||
|
||||
array_unshift($routes, $group);
|
||||
|
||||
static::router()->setRoutes($routes);
|
||||
|
||||
return $callbackHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get url for a route by using either name/alias, class or method name.
|
||||
*
|
||||
@@ -348,7 +406,11 @@ class SimpleRouter
|
||||
*/
|
||||
public static function router()
|
||||
{
|
||||
return Router::getInstance();
|
||||
if (static::$router === null) {
|
||||
static::$router = new Router();
|
||||
}
|
||||
|
||||
return static::$router;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -357,19 +419,38 @@ class SimpleRouter
|
||||
* @param IRoute $route
|
||||
* @return IRoute
|
||||
*/
|
||||
protected static function addDefaultNamespace(IRoute $route)
|
||||
public static function addDefaultNamespace(IRoute $route)
|
||||
{
|
||||
if (static::$defaultNamespace !== null) {
|
||||
$namespace = static::$defaultNamespace;
|
||||
|
||||
if ($route->getNamespace() !== null) {
|
||||
$namespace .= '\\' . $route->getNamespace();
|
||||
$callback = $route->getCallback();
|
||||
|
||||
/* Only add default namespace on relative callbacks */
|
||||
if ($callback === null || (is_string($callback) === true && $callback[0] !== '\\')) {
|
||||
|
||||
$namespace = static::$defaultNamespace;
|
||||
|
||||
$currentNamespace = $route->getNamespace();
|
||||
|
||||
if ($currentNamespace !== null) {
|
||||
$namespace .= '\\' . $currentNamespace;
|
||||
}
|
||||
|
||||
$route->setDefaultNamespace($namespace);
|
||||
|
||||
}
|
||||
|
||||
$route->setDefaultNamespace($namespace);
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default namespace
|
||||
* @return string
|
||||
*/
|
||||
public static function getDefaultNamespace()
|
||||
{
|
||||
return static::$defaultNamespace;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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,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,7 +2,7 @@
|
||||
|
||||
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)
|
||||
{
|
||||
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(new \Pecee\Http\Uri('/'));
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
$request->setUri(new \Pecee\Http\Uri('/'));
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
class ExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Exception $error)
|
||||
{
|
||||
global $stack;
|
||||
$stack[] = static::class;
|
||||
|
||||
throw new ResponseException('ExceptionHandler loaded');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerFirst implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 1 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerSecond implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 2 loaded' . chr(10);
|
||||
|
||||
$request->setUri('/');
|
||||
return $request;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
|
||||
class TestExceptionHandlerThird implements \Pecee\Handlers\IExceptionHandler
|
||||
{
|
||||
public function handleError(\Pecee\Http\Request $request, \Pecee\SimpleRouter\Route\ILoadableRoute &$route = null, \Exception $error)
|
||||
{
|
||||
echo 'ExceptionHandler 3 loaded' . chr(10);
|
||||
|
||||
throw new ExceptionHandlerException('All good!', 666);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
class ResourceController implements \Pecee\Controllers\IResourceController
|
||||
{
|
||||
|
||||
public function index()
|
||||
{
|
||||
echo 'index';
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
echo 'show ' . $id;
|
||||
}
|
||||
|
||||
public function store()
|
||||
{
|
||||
echo 'store';
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
echo 'create';
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
echo 'edit ' . $id;
|
||||
}
|
||||
|
||||
public function update($id)
|
||||
{
|
||||
echo 'update ' . $id;
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
echo 'destroy ' . $id;
|
||||
}
|
||||
}
|
||||
+26
-38
@@ -2,8 +2,7 @@
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -13,82 +12,71 @@ class GroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
$this->result = false;
|
||||
|
||||
SimpleRouter::group(['prefix' => '/group'], function () {
|
||||
TestRouter::group(['prefix' => '/group'], function () {
|
||||
$this->result = true;
|
||||
});
|
||||
|
||||
try {
|
||||
SimpleRouter::start();
|
||||
} catch (Exception $e) {
|
||||
// ignore RouteNotFound exception
|
||||
}
|
||||
TestRouter::debug('/', 'get');
|
||||
} catch(\Exception $e) {
|
||||
|
||||
}
|
||||
$this->assertTrue($this->result);
|
||||
}
|
||||
|
||||
public function testNestedGroup()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/api/v1/test');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/api/v1/test', 'get');
|
||||
|
||||
}
|
||||
|
||||
public function testManyRoutes()
|
||||
public function testMultipleRoutes()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/match');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
TestRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/api'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/test', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/test', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::get('/my/match', 'DummyController@start');
|
||||
TestRouter::get('/my/match', 'DummyController@method1');
|
||||
|
||||
SimpleRouter::group(['prefix' => '/service'], function () {
|
||||
TestRouter::group(['prefix' => '/service'], function () {
|
||||
|
||||
SimpleRouter::group(['prefix' => '/v1'], function () {
|
||||
SimpleRouter::get('/no-match', 'DummyController@start');
|
||||
TestRouter::group(['prefix' => '/v1'], function () {
|
||||
TestRouter::get('/no-match', 'DummyController@method1');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/match', 'get');
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/fancy/url/1');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
// Test array name
|
||||
SimpleRouter::get('/my/fancy/url/1', 'DummyController@start', ['as' => 'fancy1']);
|
||||
TestRouter::get('/my/fancy/url/1', 'DummyController@method1', ['as' => 'fancy1']);
|
||||
|
||||
// Test method name
|
||||
SimpleRouter::get('/my/fancy/url/2', 'DummyController@start')->setName('fancy2');
|
||||
TestRouter::get('/my/fancy/url/2', 'DummyController@method1')->setName('fancy2');
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debugNoReset('/my/fancy/url/1');
|
||||
|
||||
$this->assertEquals('/my/fancy/url/1/', SimpleRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', SimpleRouter::getUrl('fancy2'));
|
||||
$this->assertEquals('/my/fancy/url/1/', TestRouter::getUrl('fancy1'));
|
||||
$this->assertEquals('/my/fancy/url/2/', TestRouter::getUrl('fancy2'));
|
||||
|
||||
TestRouter::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
class TestRouter extends \Pecee\SimpleRouter\SimpleRouter
|
||||
{
|
||||
|
||||
public static function debugNoReset($testUri, $testMethod = 'get')
|
||||
{
|
||||
static::request()->setUri(new \Pecee\Http\Uri($testUri));
|
||||
static::request()->setMethod($testMethod);
|
||||
|
||||
static::start();
|
||||
}
|
||||
|
||||
public static function debug($testUri, $testMethod = 'get')
|
||||
{
|
||||
try {
|
||||
static::debugNoReset($testUri, $testMethod);
|
||||
} catch(\Exception $e) {
|
||||
static::router()->reset();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
static::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
public static function debugOutput($testUri, $testMethod = 'get')
|
||||
{
|
||||
$response = null;
|
||||
|
||||
// Route request
|
||||
ob_start();
|
||||
static::debug($testUri, $testMethod);
|
||||
$response = ob_get_contents();
|
||||
ob_end_clean();
|
||||
|
||||
// Return response
|
||||
return $response;
|
||||
}
|
||||
|
||||
}
|
||||
+12
-19
@@ -3,39 +3,32 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class MiddlewareTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
public function testMiddlewareFound()
|
||||
{
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
$this->setExpectedException(MiddlewareLoadedException::class);
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start', ['middleware' => 'DummyMiddleware']);
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler'], function () {
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1', ['middleware' => 'DummyMiddleware']);
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
|
||||
}
|
||||
|
||||
public function testNestedMiddlewareLoad()
|
||||
public function testNestedMiddlewareDontLoad()
|
||||
{
|
||||
$this->setExpectedException('MiddlewareLoadedException');
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
TestRouter::group(['exceptionHandler' => 'ExceptionHandler', 'middleware' => 'DummyMiddleware'], function () {
|
||||
TestRouter::get('/middleware', 'DummyController@method1');
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterCallbackExceptionHandlerTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testCallbackExceptionHandler()
|
||||
{
|
||||
$this->setExpectedException(ExceptionHandlerException::class);
|
||||
|
||||
// Match normal route on alias
|
||||
TestRouter::get('/my-new-url', 'DummyController@method2');
|
||||
TestRouter::get('/my-url', 'DummyController@method1');
|
||||
|
||||
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $exception) {
|
||||
throw new ExceptionHandlerException();
|
||||
});
|
||||
|
||||
TestRouter::debugNoReset('/404-url', 'get');
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterControllerTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testGet()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'get');
|
||||
|
||||
$this->assertEquals('getTest', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testPost()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'post');
|
||||
|
||||
$this->assertEquals('postTest', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testPut()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::controller('/url', 'DummyController');
|
||||
|
||||
$response = TestRouter::debugOutput('/url/test', 'put');
|
||||
|
||||
$this->assertEquals('putTest', $response);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterPartialGroupTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testParameters()
|
||||
{
|
||||
$result1 = null;
|
||||
$result2 = null;
|
||||
|
||||
TestRouter::partialGroup('{param1}/{param2}', function ($param1 = null, $param2 = null) use (&$result1, &$result2) {
|
||||
$result1 = $param1;
|
||||
$result2 = $param2;
|
||||
|
||||
TestRouter::get('/', 'DummyController@method1');
|
||||
});
|
||||
|
||||
TestRouter::debug('/param1/param2', 'get');
|
||||
|
||||
$this->assertEquals('param1', $result1);
|
||||
$this->assertEquals('param2', $result2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
require_once 'Dummy/ResourceController.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterResourceTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
public function testResourceStore()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource', 'post');
|
||||
|
||||
$this->assertEquals('store', $response);
|
||||
}
|
||||
|
||||
public function testResourceCreate()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/create', 'get');
|
||||
|
||||
$this->assertEquals('create', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceIndex()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource', 'get');
|
||||
|
||||
$this->assertEquals('index', $response);
|
||||
}
|
||||
|
||||
public function testResourceDestroy()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'delete');
|
||||
|
||||
$this->assertEquals('destroy 38', $response);
|
||||
}
|
||||
|
||||
|
||||
public function testResourceEdit()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38/edit', 'get');
|
||||
|
||||
$this->assertEquals('edit 38', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceUpdate()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'put');
|
||||
|
||||
$this->assertEquals('update 38', $response);
|
||||
|
||||
}
|
||||
|
||||
public function testResourceGet()
|
||||
{
|
||||
TestRouter::resource('/resource', 'ResourceController');
|
||||
$response = TestRouter::debugOutput('/resource/38', 'get');
|
||||
|
||||
$this->assertEquals('show 38', $response);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ResponseException.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerFirst.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerSecond.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandlerThird.php';
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouteRewriteTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
|
||||
/**
|
||||
* Redirects to another route through 3 exception handlers.
|
||||
*
|
||||
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
|
||||
* the exceptionhandler is asking the router to reload.
|
||||
*
|
||||
* That means that the exceptionhandler is loaded again, but this time
|
||||
* the router ignores the same rewrite-route to avoid loop - loads
|
||||
* the second which have same behavior and is also ignored before
|
||||
* throwing the final Exception in ExceptionHandler 3.
|
||||
*
|
||||
* So this tests:
|
||||
* 1. If ExceptionHandlers loads
|
||||
* 2. If ExceptionHandlers load in the correct order
|
||||
* 3. If ExceptionHandlers can rewrite the page on error
|
||||
* 4. If the router can avoid redirect-loop due to developer has started loop.
|
||||
* 5. And finally if we reaches the last exception-handler and that the correct
|
||||
* exception-type is being thrown.
|
||||
*/
|
||||
public function testExceptionHandlerRewrite()
|
||||
{
|
||||
global $stack;
|
||||
$stack = [];
|
||||
|
||||
TestRouter::group(['exceptionHandler' => [ExceptionHandlerFirst::class, ExceptionHandlerSecond::class]], function () {
|
||||
|
||||
TestRouter::group(['exceptionHandler' => ExceptionHandlerThird::class], function () {
|
||||
|
||||
TestRouter::get('/my-path', 'DummyController@method1');
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
TestRouter::debug('/my-non-existing-path', 'get');
|
||||
} catch (\ResponseException $e) {
|
||||
|
||||
}
|
||||
|
||||
$expectedStack = [
|
||||
ExceptionHandlerFirst::class,
|
||||
ExceptionHandlerSecond::class,
|
||||
ExceptionHandlerThird::class,
|
||||
];
|
||||
|
||||
$this->assertEquals($expectedStack, $stack);
|
||||
|
||||
}
|
||||
|
||||
public function testRewriteExceptionMessage()
|
||||
{
|
||||
$this->setExpectedException(\Pecee\SimpleRouter\Exceptions\NotFoundHttpException::class);
|
||||
|
||||
TestRouter::error(function (\Pecee\Http\Request $request, \Exception $error) {
|
||||
|
||||
if (strtolower($request->getUri()->getPath()) == '/my/test') {
|
||||
$request->setRewriteUrl('/another-non-existing');
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
TestRouter::debug('/my/test', 'get');
|
||||
}
|
||||
|
||||
}
|
||||
+72
-97
@@ -3,12 +3,7 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Exceptions/ExceptionHandlerException.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerFirst.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerSecond.php';
|
||||
require_once 'Dummy/Handler/TestExceptionHandlerThird.php';
|
||||
|
||||
use Pecee\SimpleRouter\Exceptions\NotFoundHttpException as NotFoundHttpException;
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
@@ -16,113 +11,57 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testMultiParam()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1-param2');
|
||||
TestRouter::get('/test-{param1}-{param2}', function ($param1, $param2) {
|
||||
|
||||
SimpleRouter::get('/test-{param1}-{param2}', function($param1, $param2) {
|
||||
|
||||
if($param1 === 'param1' && $param2 === 'param2') {
|
||||
if ($param1 === 'param1' && $param2 === 'param2') {
|
||||
$this->result = true;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/test-param1-param2', 'get');
|
||||
|
||||
$this->assertTrue($this->result);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to another route through 3 exception handlers.
|
||||
*
|
||||
* You will see "ExceptionHandler 1 loaded" 2 times. This happen because
|
||||
* the exceptionhandler is asking the router to reload.
|
||||
*
|
||||
* That means that the exceptionhandler is loaded again, but this time
|
||||
* the router ignores the same rewrite-route to avoid loop - loads
|
||||
* the second which have same behavior and is also ignored before
|
||||
* throwing the final Exception in ExceptionHandler 3.
|
||||
*
|
||||
* So this tests:
|
||||
* 1. If ExceptionHandlers loads
|
||||
* 2. If ExceptionHandlers load in the correct order
|
||||
* 3. If ExceptionHandlers can rewrite the page on error
|
||||
* 4. If the router can avoid redirect-loop due to developer has started loop.
|
||||
* 5. And finally if we reaches the last exception-handler and that the correct
|
||||
* exception-type is being thrown.
|
||||
*/
|
||||
public function testNotFound()
|
||||
{
|
||||
$this->setExpectedException('ExceptionHandlerException');
|
||||
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1-param2');
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => ['TestExceptionHandlerFirst', 'TestExceptionHandlerSecond']], function () {
|
||||
|
||||
SimpleRouter::group(['exceptionHandler' => 'TestExceptionHandlerThird'], function () {
|
||||
|
||||
SimpleRouter::get('/non-existing-path', 'DummyController@start');
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
$this->setExpectedException('\Pecee\SimpleRouter\Exceptions\NotFoundHttpException');
|
||||
TestRouter::get('/non-existing-path', 'DummyController@method1');
|
||||
TestRouter::debug('/test-param1-param2', 'post');
|
||||
}
|
||||
|
||||
public function testGet()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'get');
|
||||
}
|
||||
|
||||
public function testPost()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::post('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::post('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
}
|
||||
|
||||
public function testPut()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('put');
|
||||
|
||||
SimpleRouter::put('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::put('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'put');
|
||||
}
|
||||
|
||||
public function testDelete()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('delete');
|
||||
|
||||
SimpleRouter::delete('/my/test/url', 'DummyController@start');
|
||||
SimpleRouter::start();
|
||||
TestRouter::delete('/my/test/url', 'DummyController@method1');
|
||||
TestRouter::debug('/my/test/url', 'delete');
|
||||
}
|
||||
|
||||
public function testMethodNotAllowed()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setUri('/my/test/url');
|
||||
SimpleRouter::request()->setMethod('post');
|
||||
|
||||
SimpleRouter::get('/my/test/url', 'DummyController@start');
|
||||
TestRouter::get('/my/test/url', 'DummyController@method1');
|
||||
|
||||
try {
|
||||
SimpleRouter::start();
|
||||
TestRouter::debug('/my/test/url', 'post');
|
||||
} catch (\Exception $e) {
|
||||
$this->assertEquals(403, $e->getCode());
|
||||
}
|
||||
@@ -130,43 +69,79 @@ class RouterRouteTest extends PHPUnit_Framework_TestCase
|
||||
|
||||
public function testSimpleParam()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test-param1');
|
||||
TestRouter::get('/test-{param1}', 'DummyController@param');
|
||||
$response = TestRouter::debugOutput('/test-param1', 'get');
|
||||
|
||||
SimpleRouter::get('/test-{param1}', 'DummyController@param');
|
||||
SimpleRouter::start();
|
||||
$this->assertEquals('param1', $response);
|
||||
}
|
||||
|
||||
public function testPathParamRegex()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test/path/123123');
|
||||
TestRouter::get('/{lang}/productscategories/{name}', 'DummyController@param', ['where' => ['lang' => '[a-z]+', 'name' => '[A-Za-z0-9\-]+']]);
|
||||
$response = TestRouter::debugOutput('/it/productscategories/system', 'get');
|
||||
|
||||
SimpleRouter::get('/test/path/{myParam}', 'DummyController@param', ['where' => ['myParam' => '([0-9]+)']]);
|
||||
SimpleRouter::start();
|
||||
$this->assertEquals('it, system', $response);
|
||||
}
|
||||
|
||||
public function testDomainRoute()
|
||||
public function testDomainAllowedRoute()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/test');
|
||||
SimpleRouter::request()->setHost('hello.world.com');
|
||||
|
||||
$this->result = false;
|
||||
|
||||
SimpleRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
SimpleRouter::get('/test', function ($subdomain = null) {
|
||||
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
TestRouter::get('/test', function ($subdomain = null) {
|
||||
$this->result = ($subdomain === 'hello');
|
||||
});
|
||||
});
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::request()->setHost('hello.world.com');
|
||||
TestRouter::debug('/test', 'get');
|
||||
|
||||
$this->assertTrue($this->result);
|
||||
|
||||
}
|
||||
|
||||
public function testDomainNotAllowedRoute()
|
||||
{
|
||||
$this->result = false;
|
||||
|
||||
TestRouter::group(['domain' => '{subdomain}.world.com'], function () {
|
||||
TestRouter::get('/test', function ($subdomain = null) {
|
||||
$this->result = ($subdomain === 'hello');
|
||||
});
|
||||
});
|
||||
|
||||
TestRouter::request()->setHost('other.world.com');
|
||||
|
||||
|
||||
TestRouter::debug('/test', 'get');
|
||||
|
||||
$this->assertFalse($this->result);
|
||||
|
||||
}
|
||||
|
||||
public function testRegEx()
|
||||
{
|
||||
TestRouter::get('/my/{path}', 'DummyController@method1')->where(['path' => '[a-zA-Z\-]+']);
|
||||
TestRouter::debug('/my/custom-path', 'get');
|
||||
}
|
||||
|
||||
public function testDefaultParameterRegex()
|
||||
{
|
||||
TestRouter::get('/my/{path}', 'DummyController@param', ['defaultParameterRegex' => '[\w\-]+']);
|
||||
$output = TestRouter::debugOutput('/my/custom-regex', 'get');
|
||||
|
||||
$this->assertEquals('custom-regex', $output);
|
||||
}
|
||||
|
||||
public function testDefaultParameterRegexGroup()
|
||||
{
|
||||
TestRouter::group(['defaultParameterRegex' => '[\w\-]+'], function() {
|
||||
TestRouter::get('/my/{path}', 'DummyController@param');
|
||||
});
|
||||
|
||||
$output = TestRouter::debugOutput('/my/custom-regex', 'get');
|
||||
|
||||
$this->assertEquals('custom-regex', $output);
|
||||
}
|
||||
|
||||
}
|
||||
+105
-46
@@ -3,111 +3,170 @@
|
||||
require_once 'Dummy/DummyMiddleware.php';
|
||||
require_once 'Dummy/DummyController.php';
|
||||
require_once 'Dummy/Handler/ExceptionHandler.php';
|
||||
|
||||
use Pecee\SimpleRouter\SimpleRouter as SimpleRouter;
|
||||
require_once 'Helpers/TestRouter.php';
|
||||
|
||||
class RouterUrlTest extends PHPUnit_Framework_TestCase
|
||||
{
|
||||
protected $result = false;
|
||||
|
||||
protected function getUrl($name = null, $parameters = null, array $getParams = [])
|
||||
public function testIssue253()
|
||||
{
|
||||
return SimpleRouter::getUrl($name, $parameters, $getParams);
|
||||
TestRouter::get('/', 'DummyController@method1');
|
||||
TestRouter::get('/page/{id?}', 'DummyController@method1');
|
||||
TestRouter::get('/test-output', function() {
|
||||
return 'return value';
|
||||
});
|
||||
|
||||
TestRouter::debugNoReset('/page/22', 'get');
|
||||
$this->assertEquals('/page/{id?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
$this->assertEquals('/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
$output = TestRouter::debugOutput('/test-output', 'get');
|
||||
$this->assertEquals('return value', $output);
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testUnicodeCharacters()
|
||||
{
|
||||
// Test spanish characters
|
||||
TestRouter::get('/cursos/listado/{listado?}/{category?}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-]+']);
|
||||
TestRouter::debugNoReset('/cursos/listado/especialidad/cirugía local', 'get');
|
||||
$this->assertEquals('/cursos/listado/{listado?}/{category?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
// Test danish characters
|
||||
TestRouter::get('/kategori/økse', 'DummyController@method1', ['defaultParameterRegex' => '[\w\ø]+']);
|
||||
TestRouter::debugNoReset('/kategori/økse', 'get');
|
||||
$this->assertEquals('/kategori/økse/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::get('/test/{param}', 'DummyController@method1', ['defaultParameterRegex' => '[\w\p{L}\s-\í]+']);
|
||||
TestRouter::debugNoReset('/test/Dermatología');
|
||||
|
||||
$parameters = TestRouter::request()->getLoadedRoute()->getParameters();
|
||||
|
||||
$this->assertEquals('Dermatología', $parameters['param']);
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testOptionalParameters()
|
||||
{
|
||||
TestRouter::get('/aviso/legal', 'DummyController@method1');
|
||||
TestRouter::get('/aviso/{aviso}', 'DummyController@method1');
|
||||
TestRouter::get('/pagina/{pagina}', 'DummyController@method1');
|
||||
TestRouter::get('/{pagina?}', 'DummyController@method1');
|
||||
|
||||
TestRouter::debugNoReset('/aviso/optional', 'get');
|
||||
$this->assertEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/pagina/optional', 'get');
|
||||
$this->assertEquals('/pagina/{pagina}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/optional', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertNotEquals('/aviso/{aviso}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::debugNoReset('/avisolegal', 'get');
|
||||
$this->assertEquals('/{pagina?}/', TestRouter::router()->getRequest()->getLoadedRoute()->getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testSimilarUrls()
|
||||
{
|
||||
// Match normal route on alias
|
||||
TestRouter::resource('/url11', 'DummyController@method1');
|
||||
TestRouter::resource('/url1', 'DummyController@method1', ['as' => 'match']);
|
||||
|
||||
TestRouter::debugNoReset('/url1', 'get');
|
||||
|
||||
$this->assertEquals(TestRouter::getUrl('match'), TestRouter::getUrl());
|
||||
|
||||
TestRouter::router()->reset();
|
||||
}
|
||||
|
||||
public function testUrls()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/');
|
||||
|
||||
// Match normal route on alias
|
||||
SimpleRouter::get('/', 'DummyController@silent', ['as' => 'home']);
|
||||
TestRouter::get('/', 'DummyController@method1', ['as' => 'home']);
|
||||
|
||||
SimpleRouter::get('/about', 'DummyController@about');
|
||||
TestRouter::get('/about', 'DummyController@about');
|
||||
|
||||
SimpleRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
TestRouter::group(['prefix' => '/admin', 'as' => 'admin'], function () {
|
||||
|
||||
// Match route with prefix on alias
|
||||
SimpleRouter::get('/{id?}', 'DummyController@start', ['as' => 'home']);
|
||||
TestRouter::get('/{id?}', 'DummyController@method2', ['as' => 'home']);
|
||||
|
||||
// Match controller with prefix and alias
|
||||
SimpleRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
TestRouter::controller('/users', 'DummyController', ['as' => 'users']);
|
||||
|
||||
// Match controller with prefix and NO alias
|
||||
SimpleRouter::controller('/pages', 'DummyController');
|
||||
TestRouter::controller('/pages', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
TestRouter::group(['prefix' => 'api', 'as' => 'api'], function () {
|
||||
|
||||
// Match resource controller
|
||||
SimpleRouter::resource('phones', 'DummyController');
|
||||
TestRouter::resource('phones', 'DummyController');
|
||||
|
||||
});
|
||||
|
||||
SimpleRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
TestRouter::controller('gadgets', 'DummyController', ['names' => ['getIphoneInfo' => 'iphone']]);
|
||||
|
||||
// Match controller with no prefix and no alias
|
||||
SimpleRouter::controller('/cats', 'CatsController');
|
||||
TestRouter::controller('/cats', 'CatsController');
|
||||
|
||||
// Pretend to load page
|
||||
SimpleRouter::start();
|
||||
TestRouter::debugNoReset('/', 'get');
|
||||
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', $this->getUrl('gadgets.iphone'));
|
||||
$this->assertEquals('/gadgets/iphoneinfo/', TestRouter::getUrl('gadgets.iphone'));
|
||||
|
||||
$this->assertEquals('/api/phones/create/', $this->getUrl('api.phones.create'));
|
||||
$this->assertEquals('/api/phones/create/', TestRouter::getUrl('api.phones.create'));
|
||||
|
||||
// Should match /
|
||||
$this->assertEquals('/', $this->getUrl('home'));
|
||||
$this->assertEquals('/', TestRouter::getUrl('home'));
|
||||
|
||||
// Should match /about/
|
||||
$this->assertEquals('/about/', $this->getUrl('DummyController@about'));
|
||||
$this->assertEquals('/about/', TestRouter::getUrl('DummyController@about'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', $this->getUrl('DummyController@start'));
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('DummyController@method2'));
|
||||
|
||||
// Should match /admin/
|
||||
$this->assertEquals('/admin/', $this->getUrl('admin.home'));
|
||||
$this->assertEquals('/admin/', TestRouter::getUrl('admin.home'));
|
||||
|
||||
// Should match /admin/2/
|
||||
$this->assertEquals('/admin/2/', $this->getUrl('admin.home', ['id' => 2]));
|
||||
$this->assertEquals('/admin/2/', TestRouter::getUrl('admin.home', ['id' => 2]));
|
||||
|
||||
// Should match /admin/users/
|
||||
$this->assertEquals('/admin/users/', $this->getUrl('admin.users'));
|
||||
$this->assertEquals('/admin/users/', TestRouter::getUrl('admin.users'));
|
||||
|
||||
// Should match /admin/users/home/
|
||||
$this->assertEquals('/admin/users/home/', $this->getUrl('admin.users@home'));
|
||||
$this->assertEquals('/admin/users/home/', TestRouter::getUrl('admin.users@home'));
|
||||
|
||||
// Should match /cats/
|
||||
$this->assertEquals('/cats/', $this->getUrl('CatsController'));
|
||||
$this->assertEquals('/cats/', TestRouter::getUrl('CatsController'));
|
||||
|
||||
// Should match /cats/view/
|
||||
$this->assertEquals('/cats/view/', $this->getUrl('CatsController', 'view'));
|
||||
$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', 'view'));
|
||||
|
||||
// Should match /cats/view/
|
||||
//$this->assertEquals('/cats/view/', $this->getUrl('CatsController', ['view']));
|
||||
//$this->assertEquals('/cats/view/', TestRouter::getUrl('CatsController', ['view']));
|
||||
|
||||
// Should match /cats/view/666
|
||||
$this->assertEquals('/cats/view/666/', $this->getUrl('CatsController@getView', ['666']));
|
||||
$this->assertEquals('/cats/view/666/', TestRouter::getUrl('CatsController@getView', ['666']));
|
||||
|
||||
// Should match /funny/man/
|
||||
$this->assertEquals('/funny/man/', $this->getUrl('/funny/man'));
|
||||
$this->assertEquals('/funny/man/', TestRouter::getUrl('/funny/man'));
|
||||
|
||||
// Should match /?jackdaniels=true&cola=yeah
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', $this->getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
$this->assertEquals('/?jackdaniels=true&cola=yeah', TestRouter::getUrl('home', null, ['jackdaniels' => 'true', 'cola' => 'yeah']));
|
||||
|
||||
}
|
||||
|
||||
public function testRegEx()
|
||||
{
|
||||
SimpleRouter::router()->reset();
|
||||
SimpleRouter::request()->setMethod('get');
|
||||
SimpleRouter::request()->setUri('/my/custom-path');
|
||||
|
||||
SimpleRouter::get('/my/{path}', 'DummyController@start')->where(['path' => '[a-zA-Z\-]+']);
|
||||
|
||||
SimpleRouter::start();
|
||||
TestRouter::router()->reset();
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user