1
0
mirror of https://github.com/dannyvankooten/AltoRouter.git synced 2025-08-20 07:11:19 +02:00

53 Commits

Author SHA1 Message Date
Danny van Kooten
c28df65f42 adhere to (mostly) PSR12, check codestyle in CI 2025-01-11 20:21:41 +01:00
Danny van Kooten
f440bb654d check php syntax with error_reporting=-1 2025-01-11 20:13:29 +01:00
Danny van Kooten
9931b97642 fix indentation 2025-01-05 21:33:28 +01:00
Danny van Kooten
41fcec6b8e Merge branch 'master' of github.com:dannyvankooten/AltoRouter 2025-01-05 21:30:50 +01:00
Danny van Kooten
9d62094f74 check php syntax on all supported versions 2025-01-05 21:30:35 +01:00
Danny van Kooten
bc6b911a6d Merge pull request #285 from xpetter/patch-1
Update AltoRouter.php for php 8.4
2024-12-16 14:27:40 +01:00
Petter
5159909a81 Update AltoRouter.php
fix for php 8.4 and keep php 7.3 support
2024-12-16 14:13:20 +01:00
Petter
71389237e5 Update AltoRouter.php for php 8.4
Fix for php8.4
AltoRouter::map(): Implicitly marking parameter $name as nullable is deprecated.
AltoRouter::match(): Implicitly marking parameter $requestUrl as nullable is deprecated.
AltoRouter::match(): Implicitly marking parameter $requestMethod as nullable is deprecated.
2024-12-16 10:00:57 +01:00
Danny van Kooten
36f67da100 bump required php version to 7.3 2023-11-30 10:10:31 +01:00
Danny van Kooten
4270bb5ca2 bump php version requirement to 7.0 and add types on all methods 2023-10-09 20:54:04 +02:00
Danny van Kooten
77a2e14681 fix phpcs issues 2023-10-09 20:49:37 +02:00
Danny van Kooten
f327fbb5bf test on php 8.2 and php 8.3 too 2023-10-09 20:46:07 +02:00
Danny van Kooten
63bb784d76 update links to point to docs 2023-10-09 20:23:45 +02:00
Danny van Kooten
bb7b009331 update phpunit to 9.6 & migrate config to latest schema 2023-10-09 19:46:04 +02:00
Danny van Kooten
20674b8953 address PHP8.x warnings about return type
this requires PHP 7.1 for the void return type, but only for running the
test suite.
2022-12-08 11:12:36 +01:00
Danny van Kooten
ac028a7f3f run tests only on php >= 7.3 2022-02-17 10:42:10 +01:00
Danny van Kooten
0a94ba4142 switch to GitHub actions for running test suite 2022-02-17 10:39:54 +01:00
Danny van Kooten
85c453b12c update phpunit to latest version 2022-02-17 10:31:41 +01:00
Danny van Kooten
f6fede4f94 Merge pull request #247 from aliazizi/patch-1
Check for empty request URI, thank you @aliazizi
2020-03-09 09:34:59 +01:00
Ali Akbar Azizi
4efac02fad Update AltoRouter.php
Check $request is empty string or not
2020-02-22 15:57:56 +03:30
Danny van Kooten
6ffb025022 use svg travis icon 2019-11-23 12:03:36 +01:00
Danny van Kooten
127f6e9699 fix #241 2019-11-23 12:01:41 +01:00
Danny van Kooten
a80bb36f11 add test for #241 2019-11-23 11:35:40 +01:00
Danny van Kooten
a51c74793a benchmark using real-life api for a better comparison 2019-11-10 21:16:42 +01:00
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
13 changed files with 1075 additions and 754 deletions

20
.github/workflows/php-check-syntax.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Check PHP syntax
on: [ push, pull_request ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
php-versions: ['7.3', '7.4', '8.0', '8.1', '8.2', '8.3', 'highest']
steps:
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
- name: checkout repo
uses: actions/checkout@v3
- run: composer run check-syntax

42
.github/workflows/php.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: PHP
on: [ push, pull_request ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
php-versions: [ '7.3', 'highest' ]
steps:
- uses: actions/checkout@v2
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
tools: composer
- name: Validate composer.json and composer.lock
run: composer validate
- name: Get composer cache directory
id: composer-cache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
- name: Cache dependencies
uses: actions/cache@v2
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --no-progress
- name: Check codestyle
run: composer run-script check-codestyle
- name: Run test suite
run: composer run-script test

1
.gitignore vendored
View File

@@ -6,3 +6,4 @@ build
vendor
composer.lock
phpunit.xml
.phpunit.result.cache

View File

@@ -1,22 +0,0 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
install:
- composer update --prefer-source
script:
- ./vendor/bin/phpunit
after_script:
- ./vendor/bin/test-reporter
env:
global:
secure: XnXSc7nxJMIrm/EJ1KuwlN4f+sj2R/sR0IFHdOdbOfMKyZ/u6WEgZ3vNrdeAsisiC/QUJJ00DGku1pAl3t3Hzvam0N/SiHtXjB1ZLVbX00S1PEZ6Z+h9zoaUBXWoN6+0OdKN0Xjmj2lwvTpvUxUZXNabilOw0F9WS/+JasofqBQ=
sudo: false
cache:
directories:
- vendor
- $HOME/.composer/cache

View File

@@ -1,294 +1,300 @@
<?php
class AltoRouter {
/*
MIT License
/**
* @var array Array of all routes (incl. named routes).
*/
protected $routes = array();
Copyright (c) 2012 Danny van Kooten <hi@dannyvankooten.com>
/**
* @var array Array of all named routes.
*/
protected $namedRoutes = 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 string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/
protected $basePath = '';
The above copyright notice and this permission notice shall be included in all copies or substantial portions of 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]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
);
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.
*/
/**
* 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;
}
class AltoRouter
{
/**
* @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 = [], string $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(): array
{
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(string $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(string $method, string $route, $target, ?string $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)) {
/**
* 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(string $routeName, array $params = []): string
{
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
// Check if named route exists
if (!isset($this->namedRoutes[$routeName])) {
throw new RuntimeException("Route '{$routeName}' does not exist.");
}
if ($pre) {
$block = substr($block, 1);
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
if(isset($params[$param])) {
$url = str_replace($block, $params[$param], $url);
} elseif ($optional) {
$url = str_replace($pre . $block, '', $url);
}
}
// 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 ($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 preceding 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) {
return $url;
}
$params = array();
$match = false;
/**
* 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(?string $requestUrl = null, ?string $requestMethod = null)
{
// set Request Url if it isn't passed as parameter
if($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
$params = [];
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
// set Request Url if it isn't passed as parameter
if ($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
// set Request Method if it isn't passed as a parameter
if($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
foreach($this->routes as $handler) {
list($method, $_route, $target, $name) = $handler;
$lastRequestUrlChar = $requestUrl ? $requestUrl[strlen($requestUrl) - 1] : '';
$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 before moving on to regex
// Check if last character before param is a slash, because it could be optional if param is optional too (see https://github.com/dannyvankooten/AltoRouter/issues/241)
if (strncmp($requestUrl, $route, $position) !== 0 && ($lastRequestUrlChar === '/' || $route[$position - 1] !== '/')) {
continue;
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params);
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params) === 1;
}
if(($match == true || $match > 0)) {
if ($match) {
if ($params) {
foreach ($params as $key => $value) {
if (is_numeric($key)) {
unset($params[$key]);
}
}
}
if($params) {
foreach($params as $key => $value) {
if(is_numeric($key)) unset($params[$key]);
}
}
return [
'target' => $target,
'params' => $params,
'name' => $name
];
}
}
return array(
'target' => $target,
'params' => $params,
'name' => $name
);
}
}
return false;
}
return false;
}
/**
* Compile the regex for a given route (EXPENSIVE)
*/
private function compileRoute($route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
/**
* Compile the regex for a given route (EXPENSIVE)
* @param string $route
* @return string
*/
protected function compileRoute(string $route): string
{
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes;
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
$matchTypes = $this->matchTypes;
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';
}
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 !== '' ? '?' : 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";
}
}

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,23 @@
# 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 ![PHP status](https://github.com/dannyvankooten/AltoRouter/workflows/PHP/badge.svg) [![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)
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,13 +30,13 @@ $router->map( 'GET|POST', '/users/[i:id]/', function( $id ) {
## Getting started
You need PHP >= 5.3 to use AltoRouter.
You need PHP >= 7.3 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)
- [Map your routes](http://altorouter.com/usage/mapping-routes.html)
- [Match requests](http://altorouter.com/usage/matching-requests.html)
- [Process the request your preferred way](http://altorouter.com/usage/processing-requests.html)
- [Install AltoRouter](https://dannyvankooten.github.io/AltoRouter//usage/install.html)
- [Rewrite all requests to AltoRouter](https://dannyvankooten.github.io/AltoRouter//usage/rewrite-requests.html)
- [Map your routes](https://dannyvankooten.github.io/AltoRouter//usage/mapping-routes.html)
- [Match requests](https://dannyvankooten.github.io/AltoRouter//usage/matching-requests.html)
- [Process the request your preferred way](https://dannyvankooten.github.io/AltoRouter//usage/processing-requests.html)
## Contributors
- [Danny van Kooten](https://github.com/dannyvankooten)
@@ -42,9 +46,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,16 +20,18 @@
}
],
"require": {
"php": ">=5.3.0"
"php": ">=7.3"
},
"require-dev": {
"phpunit/phpunit": "4.5.*",
"codeclimate/php-test-reporter": "dev-master"
"phpunit/phpunit": "9.6.*",
"squizlabs/php_codesniffer": "3.6.2"
},
"autoload": {
"classmap": ["AltoRouter.php"]
},
"scripts": {
"test": "vendor/bin/phpunit"
"test": "phpunit",
"check-syntax": "find . -name '*.php' -not -path './vendor/*' -print0 | xargs -0 -n1 php --define error_reporting=-1 -l",
"check-codestyle": "phpcs -ns"
}
}

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>

11
phpcs.xml Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<ruleset name="rules">
<description>rules</description>
<rule ref="PSR12">
<exclude name="PSR1.Classes.ClassDeclaration.MissingNamespace" />
</rule>
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
<file>AltoRouter.php</file>
<file>examples/</file>
<arg name="colors"/>
</ruleset>

View File

@@ -1,17 +1,17 @@
<phpunit
colors="true"
verbose="true">
<testsuites>
<testsuite name="altorouter">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<filter>
<blacklist>
<directory>./vendor/</directory>
</blacklist>
</filter>
<logging>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
</phpunit>
<?xml version="1.0"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" verbose="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<file>./AltoRouter.php</file>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
</report>
</coverage>
<testsuites>
<testsuite name="altorouter">
<directory>./tests/</directory>
</testsuite>
</testsuites>
<logging/>
</phpunit>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,106 @@
<?php
/**
* Benchmark Altorouter
*
* Usage: php ./tests/benchmark-parse-api.php <iterations>
*
* Options:
*
* <iterations>:
* The number of routes to map & match. Defaults to 1000.
*/
require __DIR__ . '/../vendor/autoload.php';
$routes = [
["POST", "/1/classes/[a:className]"],
["GET", "/1/classes/[a:className]/[i:objectId]"],
["PUT", "/1/classes/[a:className]/[i:objectId]"],
["GET", "/1/classes/[a:className]"],
["DELETE", "/1/classes/[a:className]/[i:objectId]"],
// Users
["POST", "/1/users"],
["GET", "/1/login"],
["GET", "/1/users/[i:objectId]"],
["PUT", "/1/users/[i:objectId]"],
["GET", "/1/users"],
["DELETE", "/1/users/[i:objectId]"],
["POST", "/1/requestPasswordReset"],
// Roles
["POST", "/1/roles"],
["GET", "/1/roles/[i:objectId]"],
["PUT", "/1/roles/[i:objectId]"],
["GET", "/1/roles"],
["DELETE", "/1/roles/[i:objectId]"],
// Files
["POST", "/1/files/:fileName"],
// Analytics
["POST", "/1/events/[a:eventName]"],
// Push Notifications
["POST", "/1/push"],
// Installations
["POST", "/1/installations"],
["GET", "/1/installations/[i:objectId]"],
["PUT", "/1/installations/[i:objectId]"],
["GET", "/1/installations"],
["DELETE", "/1/installations/[i:objectId]"],
// Cloud Functions
["POST", "/1/functions"],
];
$total_time = 0;
$router = new AltoRouter();
// map requests
$start = microtime(true);
foreach ($routes as $r) {
$router->map($r[0], $r[1], '');
}
$end = microtime(true);
$time = $end - $start;
$total_time += $time;
echo sprintf('Map time: %.3f ms', $time * 1000) . PHP_EOL;
// match a static route
$start = microtime(true);
$router->match('/1/login', 'GET');
$end = microtime(true);
$time = $end - $start;
$total_time += $time;
echo sprintf('Match time (existing route, no params): %.3f ms', $time * 1000) . PHP_EOL;
// match a route with 1 parameter
$start = microtime(true);
$res = $router->match('/1/classes/foo', 'GET');
$end = microtime(true);
$time = $end - $start;
$total_time += $time;
echo sprintf('Match time (existing route, 1 param): %.3f ms', $time * 1000) . PHP_EOL;
// match a route with 2 parameters
$start = microtime(true);
$res = $router->match('/1/classes/foo/500', 'GET');
$end = microtime(true);
$time = $end - $start;
$total_time += $time;
echo sprintf('Match time (existing route, 2 params): %.3f ms', $time * 1000) . PHP_EOL;
// match unexisting route
$start = microtime(true);
$router->match('/55-foo-bar', 'GET');
$end = microtime(true);
$time = $end - $start;
$total_time += $time;
echo sprintf('Match time (unexisting route): %.3f ms', $time * 1000) . PHP_EOL;
// print totals
echo sprintf('Total time: %.3f ms', $total_time * 1000) . 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;