1
0
mirror of https://github.com/dannyvankooten/AltoRouter.git synced 2025-08-20 23:31:18 +02:00

29 Commits
v1.2.0 ... 2.0

Author SHA1 Message Date
Danny van Kooten
7e2b48db00 type-hint array in constructor parameter too 2019-11-10 20:33:12 +01:00
Danny van Kooten
3a97b2c432 use short array notation in readme too 2019-11-10 20:32:52 +01:00
Danny van Kooten
98e97407de use vendored phpunit in travis 2019-11-10 20:27:38 +01:00
Danny van Kooten
17d00ed90e update readme 2019-11-10 20:26:36 +01:00
Danny van Kooten
a34caaf60c Merge pull request #234 from DevFelixDorn/code-maintainability
Add PHPCS & type-hinting for array function arguments. Use (CS enforced) short array notation everywhere. Thanks @DevFelixDorn
2019-11-10 20:18:39 +01:00
Félix Dorn
a01166760c phpcs formatting 2019-07-03 21:44:06 +02:00
Félix Dorn
cd918de64b add @covers on every test, remove array long syntax 2019-07-03 21:43:47 +02:00
Félix Dorn
2360f527b0 add type hinting, removed array long syntax 2019-07-03 21:40:17 +02:00
Félix Dorn
24360d6162 add php-cs to match with PSR2 requirements 2019-07-03 21:39:35 +02:00
Danny van Kooten
dce6efdea2 fix phpunit on older php versions 2019-02-07 09:52:34 +01:00
Danny van Kooten
ecb5f69042 use travis phpunit so that we can test on lower php versions too 2019-02-07 09:44:18 +01:00
Danny van Kooten
9e9767e8fa add support for php's built-in web server to example. #226 2019-02-07 09:38:22 +01:00
Danny van Kooten
87d93b6840 update benchmark 2019-02-07 09:16:23 +01:00
Danny van Kooten
9bdfc55eb3 fix tests by making compileRoute protected instead 2019-02-07 09:16:13 +01:00
Danny van Kooten
df96d7270c update to phpunit 7.5 2019-02-06 20:13:21 +01:00
Danny van Kooten
e2a07ec452 test recent php versions, stop testing 5.3-5.5 2019-02-06 20:01:07 +01:00
Danny van Kooten
ca2d425bc6 add example for url generation to readme 2018-08-19 11:51:01 +02:00
Danny van Kooten
281c5631db add license to main php file too 2018-08-19 11:47:59 +02:00
Danny van Kooten
58299f4d0d add license file 2018-08-19 11:47:09 +02:00
Danny van Kooten
1ff4165b28 improve benchmark by preparing first, matching & only mapping two routes 2017-04-10 16:36:22 +02:00
Koen Punt
689670f4dc Merge pull request #99 from koenpunt/bare-optional-parameter
Allow for optional parameters on bare/root url
2017-04-04 20:37:25 +02:00
Koen Punt
72dd5199bd multi optional 2017-04-02 20:41:58 +02:00
Koen Punt
be64536dcb prevent strip of preceding slash at base 2017-04-02 20:41:10 +02:00
Koen Punt
f18a57d481 add failing test for generate 2016-12-30 00:11:18 +01:00
Koen Punt
e72248c744 add failing test for #98 2016-12-30 00:11:18 +01:00
Koen Punt
693752b77a simplify loop for non-param substring (#131)
optimize comparison using strcmp functions
2016-06-21 23:27:25 +02:00
Danny van Kooten
a8ee8e875f Merge pull request #130 from dannyvankooten/strpos-request-method
Use `stripos` to compare request method (instead of `explode` + `in_array`) for improved performance.
2016-06-21 22:37:56 +02:00
Danny van Kooten
48524b67cb Add benchmark script to tests directory for easy benchmarking. 2016-06-21 15:27:21 +02:00
Danny van Kooten
6fe6f4b196 Use stripos to compare request method, instead of explode + in_array. 2015-11-03 08:13:51 +07:00
10 changed files with 971 additions and 719 deletions

View File

@@ -1,17 +1,16 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
- 7.1
- 7.2
- 7.3
install:
- composer update --prefer-source
script:
- ./vendor/bin/phpunit
- vendor/bin/phpunit
after_script:
- ./vendor/bin/test-reporter
- vendor/bin/test-reporter
env:
global:
secure: XnXSc7nxJMIrm/EJ1KuwlN4f+sj2R/sR0IFHdOdbOfMKyZ/u6WEgZ3vNrdeAsisiC/QUJJ00DGku1pAl3t3Hzvam0N/SiHtXjB1ZLVbX00S1PEZ6Z+h9zoaUBXWoN6+0OdKN0Xjmj2lwvTpvUxUZXNabilOw0F9WS/+JasofqBQ=

View File

@@ -1,294 +1,297 @@
<?php
/*
MIT License
class AltoRouter {
Copyright (c) 2012 Danny van Kooten <hi@dannyvankooten.com>
/**
* @var array Array of all routes (incl. named routes).
*/
protected $routes = array();
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/**
* @var array Array of all named routes.
*/
protected $namedRoutes = array();
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/**
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/
protected $basePath = '';
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @var array Array of default match types (regex helpers)
*/
protected $matchTypes = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
);
class AltoRouter
{
/**
* Create router in one call from config.
*
* @param array $routes
* @param string $basePath
* @param array $matchTypes
*/
public function __construct( $routes = array(), $basePath = '', $matchTypes = array() ) {
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
}
/**
* Retrieves all routes.
* Useful if you want to process or display routes.
* @return array All routes.
*/
public function getRoutes() {
return $this->routes;
}
/**
* @var array Array of all routes (incl. named routes).
*/
protected $routes = [];
/**
* Add multiple routes at once from array in the following format:
*
* $routes = array(
* array($method, $route, $target, $name)
* );
*
* @param array $routes
* @return void
* @author Koen Punt
* @throws Exception
*/
public function addRoutes($routes){
if(!is_array($routes) && !$routes instanceof Traversable) {
throw new \Exception('Routes should be an array or an instance of Traversable');
}
foreach($routes as $route) {
call_user_func_array(array($this, 'map'), $route);
}
}
/**
* @var array Array of all named routes.
*/
protected $namedRoutes = [];
/**
* Set the base path.
* Useful if you are running your application from a subdirectory.
*/
public function setBasePath($basePath) {
$this->basePath = $basePath;
}
/**
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/
protected $basePath = '';
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* @param array $matchTypes The key is the name and the value is the regex.
*/
public function addMatchTypes($matchTypes) {
$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
}
/**
* @var array Array of default match types (regex helpers)
*/
protected $matchTypes = [
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
];
/**
* Map a route to a target
*
* @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE)
* @param string $route The route regex, custom regex must start with an @. You can use multiple pre-set regex filters, like [i:id]
* @param mixed $target The target where this route should point to. Can be anything.
* @param string $name Optional name of this route. Supply if you want to reverse route this url in your application.
* @throws Exception
*/
public function map($method, $route, $target, $name = null) {
/**
* Create router in one call from config.
*
* @param array $routes
* @param string $basePath
* @param array $matchTypes
* @throws Exception
*/
public function __construct(array $routes = [], $basePath = '', array $matchTypes = [])
{
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
}
$this->routes[] = array($method, $route, $target, $name);
/**
* Retrieves all routes.
* Useful if you want to process or display routes.
* @return array All routes.
*/
public function getRoutes()
{
return $this->routes;
}
if($name) {
if(isset($this->namedRoutes[$name])) {
throw new \Exception("Can not redeclare route '{$name}'");
} else {
$this->namedRoutes[$name] = $route;
}
/**
* Add multiple routes at once from array in the following format:
*
* $routes = [
* [$method, $route, $target, $name]
* ];
*
* @param array $routes
* @return void
* @author Koen Punt
* @throws Exception
*/
public function addRoutes($routes)
{
if (!is_array($routes) && !$routes instanceof Traversable) {
throw new RuntimeException('Routes should be an array or an instance of Traversable');
}
foreach ($routes as $route) {
call_user_func_array([$this, 'map'], $route);
}
}
}
/**
* Set the base path.
* Useful if you are running your application from a subdirectory.
* @param string $basePath
*/
public function setBasePath($basePath)
{
$this->basePath = $basePath;
}
return;
}
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* @param array $matchTypes The key is the name and the value is the regex.
*/
public function addMatchTypes(array $matchTypes)
{
$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
}
/**
* Reversed routing
*
* Generate the URL for a named route. Replace regexes with supplied parameters
*
* @param string $routeName The name of the route.
* @param array @params Associative array of parameters to replace placeholders with.
* @return string The URL of the route with named parameters in place.
* @throws Exception
*/
public function generate($routeName, array $params = array()) {
/**
* Map a route to a target
*
* @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE)
* @param string $route The route regex, custom regex must start with an @. You can use multiple pre-set regex filters, like [i:id]
* @param mixed $target The target where this route should point to. Can be anything.
* @param string $name Optional name of this route. Supply if you want to reverse route this url in your application.
* @throws Exception
*/
public function map($method, $route, $target, $name = null)
{
// Check if named route exists
if(!isset($this->namedRoutes[$routeName])) {
throw new \Exception("Route '{$routeName}' does not exist.");
}
$this->routes[] = [$method, $route, $target, $name];
// Replace named parameters
$route = $this->namedRoutes[$routeName];
// prepend base path to route url again
$url = $this->basePath . $route;
if ($name) {
if (isset($this->namedRoutes[$name])) {
throw new RuntimeException("Can not redeclare route '{$name}'");
}
$this->namedRoutes[$name] = $route;
}
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
return;
}
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
/**
* Reversed routing
*
* Generate the URL for a named route. Replace regexes with supplied parameters
*
* @param string $routeName The name of the route.
* @param array @params Associative array of parameters to replace placeholders with.
* @return string The URL of the route with named parameters in place.
* @throws Exception
*/
public function generate($routeName, array $params = [])
{
if ($pre) {
$block = substr($block, 1);
}
// Check if named route exists
if (!isset($this->namedRoutes[$routeName])) {
throw new RuntimeException("Route '{$routeName}' does not exist.");
}
if(isset($params[$param])) {
$url = str_replace($block, $params[$param], $url);
} elseif ($optional) {
$url = str_replace($pre . $block, '', $url);
}
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
// prepend base path to route url again
$url = $this->basePath . $route;
}
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach ($matches as $index => $match) {
list($block, $pre, $type, $param, $optional) = $match;
return $url;
}
if ($pre) {
$block = substr($block, 1);
}
/**
* Match a given Request Url against stored routes
* @param string $requestUrl
* @param string $requestMethod
* @return array|boolean Array with route information on success, false on failure (no match).
*/
public function match($requestUrl = null, $requestMethod = null) {
if (isset($params[$param])) {
// Part is found, replace for param value
$url = str_replace($block, $params[$param], $url);
} elseif ($optional && $index !== 0) {
// Only strip preceding slash if it's not at the base
$url = str_replace($pre . $block, '', $url);
} else {
// Strip match block
$url = str_replace($block, '', $url);
}
}
}
$params = array();
$match = false;
return $url;
}
// set Request Url if it isn't passed as parameter
if($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
/**
* Match a given Request Url against stored routes
* @param string $requestUrl
* @param string $requestMethod
* @return array|boolean Array with route information on success, false on failure (no match).
*/
public function match($requestUrl = null, $requestMethod = null)
{
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
$params = [];
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
// set Request Url if it isn't passed as parameter
if ($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// set Request Method if it isn't passed as a parameter
if($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
foreach($this->routes as $handler) {
list($method, $_route, $target, $name) = $handler;
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
$methods = explode('|', $method);
$method_match = false;
// set Request Method if it isn't passed as a parameter
if ($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
// Check if request method matches. If not, abandon early. (CHEAP)
foreach($methods as $method) {
if (strcasecmp($requestMethod, $method) === 0) {
$method_match = true;
break;
}
}
foreach ($this->routes as $handler) {
list($methods, $route, $target, $name) = $handler;
// Method did not match, continue to next route.
if(!$method_match) continue;
$method_match = (stripos($methods, $requestMethod) !== false);
// Check for a wildcard (matches all)
if ($_route === '*') {
$match = true;
} elseif (isset($_route[0]) && $_route[0] === '@') {
$pattern = '`' . substr($_route, 1) . '`u';
$match = preg_match($pattern, $requestUrl, $params);
} else {
$route = null;
$regex = false;
$j = 0;
$n = isset($_route[0]) ? $_route[0] : null;
$i = 0;
// Method did not match, continue to next route.
if (!$method_match) {
continue;
}
// Find the longest non-regex substring and match it against the URI
while (true) {
if (!isset($_route[$i])) {
break;
} elseif (false === $regex) {
$c = $n;
$regex = $c === '[' || $c === '(' || $c === '.';
if (false === $regex && false !== isset($_route[$i+1])) {
$n = $_route[$i + 1];
$regex = $n === '?' || $n === '+' || $n === '*' || $n === '{';
}
if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) {
continue 2;
}
$j++;
}
$route .= $_route[$i++];
}
if ($route === '*') {
// * wildcard (matches all)
$match = true;
} elseif (isset($route[0]) && $route[0] === '@') {
// @ regex delimiter
$pattern = '`' . substr($route, 1) . '`u';
$match = preg_match($pattern, $requestUrl, $params) === 1;
} elseif (($position = strpos($route, '[')) === false) {
// No params in url, do string comparison
$match = strcmp($requestUrl, $route) === 0;
} else {
// Compare longest non-param string with url
if (strncmp($requestUrl, $route, $position) !== 0) {
continue;
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params) === 1;
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params);
}
if ($match) {
if ($params) {
foreach ($params as $key => $value) {
if (is_numeric($key)) {
unset($params[$key]);
}
}
}
if(($match == true || $match > 0)) {
return [
'target' => $target,
'params' => $params,
'name' => $name
];
}
}
return false;
}
if($params) {
foreach($params as $key => $value) {
if(is_numeric($key)) unset($params[$key]);
}
}
/**
* Compile the regex for a given route (EXPENSIVE)
* @param $route
* @return string
*/
protected function compileRoute($route)
{
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes;
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
return array(
'target' => $target,
'params' => $params,
'name' => $name
);
}
}
return false;
}
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';
}
/**
* Compile the regex for a given route (EXPENSIVE)
*/
private function compileRoute($route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$optional = $optional !== '' ? '?' : null;
$matchTypes = $this->matchTypes;
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. ')'
. $optional
. ')'
. $optional;
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';
}
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. '))'
. ($optional !== '' ? '?' : null);
$route = str_replace($block, $pattern, $route);
}
}
return "`^$route$`u";
}
$route = str_replace($block, $pattern, $route);
}
}
return "`^$route$`u";
}
}

9
LICENSE.md Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2012 Danny van Kooten <hi@dannyvankooten.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,19 +1,22 @@
# AltoRouter [![Build Status](https://api.travis-ci.org/dannyvankooten/AltoRouter.png)](http://travis-ci.org/dannyvankooten/AltoRouter) [![Latest Stable Version](https://poser.pugx.org/altorouter/altorouter/v/stable.svg)](https://packagist.org/packages/altorouter/altorouter) [![License](https://poser.pugx.org/altorouter/altorouter/license.svg)](https://packagist.org/packages/altorouter/altorouter) [![Code Climate](https://codeclimate.com/github/dannyvankooten/AltoRouter/badges/gpa.svg)](https://codeclimate.com/github/dannyvankooten/AltoRouter) [![Test Coverage](https://codeclimate.com/github/dannyvankooten/AltoRouter/badges/coverage.svg)](https://codeclimate.com/github/dannyvankooten/AltoRouter)
AltoRouter is a small but powerful routing class for PHP 5.3+, heavily inspired by [klein.php](https://github.com/chriso/klein.php/).
AltoRouter is a small but powerful routing class, heavily inspired by [klein.php](https://github.com/chriso/klein.php/).
```php
$router = new AltoRouter();
// map homepage
$router->map( 'GET', '/', function() {
$router->map('GET', '/', function() {
require __DIR__ . '/views/home.php';
});
// map users details page
$router->map( 'GET|POST', '/users/[i:id]/', function( $id ) {
// dynamic named route
$router->map('GET|POST', '/users/[i:id]/', function($id) {
$user = .....
require __DIR__ . '/views/user/details.php';
});
}, 'user-details');
// echo URL to user-details page for ID 5
echo $router->generate('user-details', ['id' => 5]); // Output: "/users/5"
```
## Features
@@ -26,7 +29,7 @@ $router->map( 'GET|POST', '/users/[i:id]/', function( $id ) {
## Getting started
You need PHP >= 5.3 to use AltoRouter.
You need PHP >= 5.6 to use AltoRouter, although we highly recommend you [use an officially supported PHP version](https://secure.php.net/supported-versions.php) that is not EOL.
- [Install AltoRouter](http://altorouter.com/usage/install.html)
- [Rewrite all requests to AltoRouter](http://altorouter.com/usage/rewrite-requests.html)
@@ -42,9 +45,9 @@ You need PHP >= 5.3 to use AltoRouter.
## License
(MIT License)
MIT License
Copyright (c) 2012-2015 Danny van Kooten <hi@dannyvankooten.com>
Copyright (c) 2012 Danny van Kooten <hi@dannyvankooten.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@@ -20,11 +20,12 @@
}
],
"require": {
"php": ">=5.3.0"
"php": ">=5.6.0"
},
"require-dev": {
"phpunit/phpunit": "4.5.*",
"codeclimate/php-test-reporter": "dev-master"
"phpunit/phpunit": "5.7.*",
"codeclimate/php-test-reporter": "dev-master",
"squizlabs/php_codesniffer": "3.4.2"
},
"autoload": {
"classmap": ["AltoRouter.php"]

View File

@@ -1,13 +1,21 @@
<?php
require '../../AltoRouter.php';
require __DIR__ . '/../../AltoRouter.php';
/**
* This can be useful if you're using PHP's built-in web server, to serve files like images or css
* @link https://secure.php.net/manual/en/features.commandline.webserver.php
*/
if (file_exists($_SERVER['SCRIPT_FILENAME']) && pathinfo($_SERVER['SCRIPT_FILENAME'], PATHINFO_EXTENSION) !== 'php') {
return;
}
$router = new AltoRouter();
$router->setBasePath('/AltoRouter/examples/basic');
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
$router->map('GET|POST', '/', 'home#index', 'home');
$router->map('GET', '/users/', ['c' => 'UserController', 'a' => 'ListAction']);
$router->map('GET', '/users/[i:id]', 'users#show', 'users_show');
$router->map('POST', '/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
// match current request
$match = $router->match();
@@ -16,12 +24,12 @@ $match = $router->match();
<h3>Current request: </h3>
<pre>
Target: <?php var_dump($match['target']); ?>
Params: <?php var_dump($match['params']); ?>
Name: <?php var_dump($match['name']); ?>
Target: <?php var_dump($match['target']); ?>
Params: <?php var_dump($match['params']); ?>
Name: <?php var_dump($match['name']); ?>
</pre>
<h3>Try these requests: </h3>
<p><a href="<?php echo $router->generate('home'); ?>">GET <?php echo $router->generate('home'); ?></a></p>
<p><a href="<?php echo $router->generate('users_show', array('id' => 5)); ?>">GET <?php echo $router->generate('users_show', array('id' => 5)); ?></a></p>
<p><form action="<?php echo $router->generate('users_do', array('id' => 10, 'action' => 'update')); ?>" method="post"><button type="submit"><?php echo $router->generate('users_do', array('id' => 10, 'action' => 'update')); ?></button></form></p>
<p><a href="<?php echo $router->generate('users_show', ['id' => 5]); ?>">GET <?php echo $router->generate('users_show', ['id' => 5]); ?></a></p>
<p><form action="<?php echo $router->generate('users_do', ['id' => 10, 'action' => 'update']); ?>" method="post"><button type="submit"><?php echo $router->generate('users_do', ['id' => 10, 'action' => 'update']); ?></button></form></p>

10
phpcs.xml Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<ruleset name="rules">
<description>rules</description>
<rule ref="PSR2"/>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
<file>tests</file>
<file>AltoRouter.php</file>
<file>examples/</file>
<arg name="colors"/>
</ruleset>

View File

@@ -7,9 +7,9 @@
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory>./vendor/</directory>
</blacklist>
<whitelist>
<file>./AltoRouter.php</file>
</whitelist>
</filter>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>

File diff suppressed because it is too large Load Diff

92
tests/benchmark.php Normal file
View File

@@ -0,0 +1,92 @@
<?php
/**
* Benchmark Altorouter
*
* Usage: php ./tests/benchmark.php <iterations>
*
* Options:
*
* <iterations>:
* The number of routes to map & match. Defaults to 1000.
*/
require __DIR__ . '/../vendor/autoload.php';
global $argv;
$n = isset($argv[1]) ? intval($argv[1]) : 1000;
// generates a random request url
function random_request_url()
{
$characters = 'abcdefghijklmnopqrstuvwxyz';
$charactersLength = strlen($characters);
$randomString = '/';
// create random path of 5-20 characters
for ($i = 0; $i < rand(5, 20); $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
if (rand(1, 10) === 1) {
$randomString .= '/';
}
}
// add dynamic route with 10% chance
if (rand(1, 10) === 1) {
$randomString = rtrim($randomString, '/') . '/[:part]';
}
return $randomString;
}
// generate a random request method
function random_request_method()
{
static $methods = [ 'GET', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' ];
$random_key = array_rand($methods);
return $methods[ $random_key ];
}
// prepare benchmark data
$requests = [];
for ($i=0; $i<$n; $i++) {
$requests[] = [
'method' => random_request_method(),
'url' => random_request_url(),
];
}
$router = new AltoRouter();
// map requests
$start = microtime(true);
foreach ($requests as $r) {
$router->map($r['method'], $r['url'], '');
}
$end = microtime(true);
$map_time = ($end - $start) * 1000;
echo sprintf('Map time: %.2f ms', $map_time) . PHP_EOL;
// pick random route to match
$r = $requests[array_rand($requests)];
// match random known route
$start = microtime(true);
$router->match($r['url'], $r['method']);
$end = microtime(true);
$match_time_known_route = ($end - $start) * 1000;
echo sprintf('Match time (known route): %.2f ms', $match_time_known_route) . PHP_EOL;
// match unexisting route
$start = microtime(true);
$router->match('/55-foo-bar', 'GET');
$end = microtime(true);
$match_time_unknown_route = ($end - $start) * 1000;
echo sprintf('Match time (unknown route): %.2f ms', $match_time_unknown_route) . PHP_EOL;
// print totals
echo sprintf('Total time: %.2f seconds', ($map_time + $match_time_known_route + $match_time_unknown_route)) . PHP_EOL;
echo sprintf('Memory usage: %d KB', round(memory_get_usage() / 1024)) . PHP_EOL;
echo sprintf('Peak memory usage: %d KB', round(memory_get_peak_usage(true) / 1024)) . PHP_EOL;