mirror of
https://github.com/dannyvankooten/AltoRouter.git
synced 2025-08-07 00:46:51 +02:00
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
This commit is contained in:
486
AltoRouter.php
486
AltoRouter.php
@@ -11,277 +11,287 @@ The above copyright notice and this permission notice shall be included in all c
|
||||
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.
|
||||
*/
|
||||
|
||||
class AltoRouter {
|
||||
class AltoRouter
|
||||
{
|
||||
|
||||
/**
|
||||
* @var array Array of all routes (incl. named routes).
|
||||
*/
|
||||
protected $routes = array();
|
||||
/**
|
||||
* @var array Array of all routes (incl. named routes).
|
||||
*/
|
||||
protected $routes = [];
|
||||
|
||||
/**
|
||||
* @var array Array of all named routes.
|
||||
*/
|
||||
protected $namedRoutes = array();
|
||||
/**
|
||||
* @var array Array of all named routes.
|
||||
*/
|
||||
protected $namedRoutes = [];
|
||||
|
||||
/**
|
||||
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
|
||||
*/
|
||||
protected $basePath = '';
|
||||
/**
|
||||
* @var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
|
||||
*/
|
||||
protected $basePath = '';
|
||||
|
||||
/**
|
||||
* @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]++',
|
||||
'*' => '.+?',
|
||||
'**' => '.++',
|
||||
'' => '[^/\.]++'
|
||||
);
|
||||
/**
|
||||
* @var array Array of default match types (regex helpers)
|
||||
*/
|
||||
protected $matchTypes = [
|
||||
'i' => '[0-9]++',
|
||||
'a' => '[0-9A-Za-z]++',
|
||||
'h' => '[0-9A-Fa-f]++',
|
||||
'*' => '.+?',
|
||||
'**' => '.++',
|
||||
'' => '[^/\.]++'
|
||||
];
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
/**
|
||||
* Create router in one call from config.
|
||||
*
|
||||
* @param array $routes
|
||||
* @param string $basePath
|
||||
* @param array $matchTypes
|
||||
* @throws Exception
|
||||
*/
|
||||
public function __construct(array $routes = [], $basePath = '', $matchTypes = [])
|
||||
{
|
||||
$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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function setBasePath($basePath) {
|
||||
$this->basePath = $basePath;
|
||||
}
|
||||
/**
|
||||
* Set the base path.
|
||||
* Useful if you are running your application from a subdirectory.
|
||||
* @param string $basePath
|
||||
*/
|
||||
public function setBasePath($basePath)
|
||||
{
|
||||
$this->basePath = $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);
|
||||
}
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
|
||||
$this->routes[] = array($method, $route, $target, $name);
|
||||
$this->routes[] = [$method, $route, $target, $name];
|
||||
|
||||
if($name) {
|
||||
if(isset($this->namedRoutes[$name])) {
|
||||
throw new \Exception("Can not redeclare route '{$name}'");
|
||||
} else {
|
||||
$this->namedRoutes[$name] = $route;
|
||||
}
|
||||
if ($name) {
|
||||
if (isset($this->namedRoutes[$name])) {
|
||||
throw new RuntimeException("Can not redeclare route '{$name}'");
|
||||
}
|
||||
$this->namedRoutes[$name] = $route;
|
||||
}
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* 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 = [])
|
||||
{
|
||||
|
||||
/**
|
||||
* 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()) {
|
||||
// Check if named route exists
|
||||
if (!isset($this->namedRoutes[$routeName])) {
|
||||
throw new RuntimeException("Route '{$routeName}' does not exist.");
|
||||
}
|
||||
|
||||
// Check if named route exists
|
||||
if(!isset($this->namedRoutes[$routeName])) {
|
||||
throw new \Exception("Route '{$routeName}' does not exist.");
|
||||
}
|
||||
// Replace named parameters
|
||||
$route = $this->namedRoutes[$routeName];
|
||||
|
||||
// prepend base path to route url again
|
||||
$url = $this->basePath . $route;
|
||||
|
||||
// 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;
|
||||
|
||||
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
|
||||
if ($pre) {
|
||||
$block = substr($block, 1);
|
||||
}
|
||||
|
||||
foreach($matches as $index => $match) {
|
||||
list($block, $pre, $type, $param, $optional) = $match;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($pre) {
|
||||
$block = substr($block, 1);
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
if(isset($params[$param])) {
|
||||
// Part is found, replace for param value
|
||||
$url = str_replace($block, $params[$param], $url);
|
||||
} elseif ($optional && $index !== 0) {
|
||||
// Only strip preceeding slash if it's not at the base
|
||||
$url = str_replace($pre . $block, '', $url);
|
||||
} else {
|
||||
// Strip match block
|
||||
$url = str_replace($block, '', $url);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
|
||||
}
|
||||
$params = [];
|
||||
|
||||
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 = array();
|
||||
$match = false;
|
||||
// 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($methods, $route, $target, $name) = $handler;
|
||||
|
||||
// Strip query string (?a=b) from Request Url
|
||||
if (($strpos = strpos($requestUrl, '?')) !== false) {
|
||||
$requestUrl = substr($requestUrl, 0, $strpos);
|
||||
}
|
||||
$method_match = (stripos($methods, $requestMethod) !== false);
|
||||
|
||||
// set Request Method if it isn't passed as a parameter
|
||||
if($requestMethod === null) {
|
||||
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
|
||||
}
|
||||
// Method did not match, continue to next route.
|
||||
if (!$method_match) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach($this->routes as $handler) {
|
||||
list($methods, $route, $target, $name) = $handler;
|
||||
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;
|
||||
}
|
||||
|
||||
$method_match = (stripos($methods, $requestMethod) !== false);
|
||||
if ($match) {
|
||||
if ($params) {
|
||||
foreach ($params as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
unset($params[$key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Method did not match, continue to next route.
|
||||
if (!$method_match) continue;
|
||||
return [
|
||||
'target' => $target,
|
||||
'params' => $params,
|
||||
'name' => $name
|
||||
];
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
|
||||
if ($match) {
|
||||
if (isset($matchTypes[$type])) {
|
||||
$type = $matchTypes[$type];
|
||||
}
|
||||
if ($pre === '.') {
|
||||
$pre = '\.';
|
||||
}
|
||||
|
||||
if ($params) {
|
||||
foreach($params as $key => $value) {
|
||||
if(is_numeric($key)) unset($params[$key]);
|
||||
}
|
||||
}
|
||||
$optional = $optional !== '' ? '?' : null;
|
||||
|
||||
//Older versions of PCRE require the 'P' in (?P<named>)
|
||||
$pattern = '(?:'
|
||||
. ($pre !== '' ? $pre : null)
|
||||
. '('
|
||||
. ($param !== '' ? "?P<$param>" : null)
|
||||
. $type
|
||||
. ')'
|
||||
. $optional
|
||||
. ')'
|
||||
. $optional;
|
||||
|
||||
return array(
|
||||
'target' => $target,
|
||||
'params' => $params,
|
||||
'name' => $name
|
||||
);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compile the regex for a given route (EXPENSIVE)
|
||||
*/
|
||||
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;
|
||||
|
||||
if (isset($matchTypes[$type])) {
|
||||
$type = $matchTypes[$type];
|
||||
}
|
||||
if ($pre === '.') {
|
||||
$pre = '\.';
|
||||
}
|
||||
|
||||
$optional = $optional !== '' ? '?' : null;
|
||||
|
||||
//Older versions of PCRE require the 'P' in (?P<named>)
|
||||
$pattern = '(?:'
|
||||
. ($pre !== '' ? $pre : null)
|
||||
. '('
|
||||
. ($param !== '' ? "?P<$param>" : null)
|
||||
. $type
|
||||
. ')'
|
||||
. $optional
|
||||
. ')'
|
||||
. $optional;
|
||||
|
||||
$route = str_replace($block, $pattern, $route);
|
||||
}
|
||||
|
||||
}
|
||||
return "`^$route$`u";
|
||||
}
|
||||
$route = str_replace($block, $pattern, $route);
|
||||
}
|
||||
}
|
||||
return "`^$route$`u";
|
||||
}
|
||||
}
|
||||
|
@@ -24,7 +24,8 @@
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "5.7.*",
|
||||
"codeclimate/php-test-reporter": "dev-master"
|
||||
"codeclimate/php-test-reporter": "dev-master",
|
||||
"squizlabs/php_codesniffer": "3.4.2"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": ["AltoRouter.php"]
|
||||
|
@@ -12,10 +12,10 @@ if (file_exists($_SERVER['SCRIPT_FILENAME']) && pathinfo($_SERVER['SCRIPT_FILENA
|
||||
|
||||
$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();
|
||||
@@ -24,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
10
phpcs.xml
Normal 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>
|
File diff suppressed because it is too large
Load Diff
@@ -14,10 +14,11 @@
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
global $argv;
|
||||
$n = isset( $argv[1] ) ? intval( $argv[1] ) : 1000;
|
||||
$n = isset($argv[1]) ? intval($argv[1]) : 1000;
|
||||
|
||||
// generates a random request url
|
||||
function random_request_url() {
|
||||
function random_request_url()
|
||||
{
|
||||
$characters = 'abcdefghijklmnopqrstuvwxyz';
|
||||
$charactersLength = strlen($characters);
|
||||
$randomString = '/';
|
||||
@@ -26,45 +27,46 @@ function random_request_url() {
|
||||
for ($i = 0; $i < rand(5, 20); $i++) {
|
||||
$randomString .= $characters[rand(0, $charactersLength - 1)];
|
||||
|
||||
if( rand(1, 10) === 1 ) {
|
||||
$randomString .= '/';
|
||||
if (rand(1, 10) === 1) {
|
||||
$randomString .= '/';
|
||||
}
|
||||
}
|
||||
|
||||
// add dynamic route with 10% chance
|
||||
if ( rand(1, 10) === 1 ) {
|
||||
$randomString = rtrim( $randomString, '/' ) . '/[:part]';
|
||||
if (rand(1, 10) === 1) {
|
||||
$randomString = rtrim($randomString, '/') . '/[:part]';
|
||||
}
|
||||
|
||||
return $randomString;
|
||||
}
|
||||
|
||||
// generate a random request method
|
||||
function random_request_method() {
|
||||
static $methods = array( 'GET', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' );
|
||||
$random_key = array_rand( $methods );
|
||||
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 = array();
|
||||
for($i=0; $i<$n; $i++) {
|
||||
$requests[] = array(
|
||||
$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) {
|
||||
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;
|
||||
echo sprintf('Map time: %.2f ms', $map_time) . PHP_EOL;
|
||||
|
||||
|
||||
// pick random route to match
|
||||
@@ -75,19 +77,16 @@ $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;
|
||||
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;
|
||||
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;
|
||||
|
||||
|
||||
|
||||
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;
|
||||
|
Reference in New Issue
Block a user