Server IP : 213.176.29.180 / Your IP : 18.220.222.188 Web Server : Apache System : Linux 213.176.29.180.hostiran.name 4.18.0-553.22.1.el8_10.x86_64 #1 SMP Tue Sep 24 05:16:59 EDT 2024 x86_64 User : webtaragh ( 1001) PHP Version : 7.4.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON Directory (0750) : /home/webtaragh/.razor/../public_html/ |
[ Home ] | [ C0mmand ] | [ Upload File ] |
---|
fast-route/FastRoute.hhi 0000644 00000010723 14736103317 0011253 0 ustar 00 <?hh // decl namespace FastRoute { class BadRouteException extends \LogicException { } interface RouteParser { public function parse(string $route): array<array>; } class RouteCollector { public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator); public function addRoute(mixed $httpMethod, string $route, mixed $handler): void; public function getData(): array; } class Route { public function __construct(string $httpMethod, mixed $handler, string $regex, array $variables); public function matches(string $str): bool; } interface DataGenerator { public function addRoute(string $httpMethod, array $routeData, mixed $handler); public function getData(): array; } interface Dispatcher { const int NOT_FOUND = 0; const int FOUND = 1; const int METHOD_NOT_ALLOWED = 2; public function dispatch(string $httpMethod, string $uri): array; } function simpleDispatcher( (function(RouteCollector): void) $routeDefinitionCallback, shape( 'routeParser' => ?classname<RouteParser>, 'dataGenerator' => ?classname<DataGenerator>, 'dispatcher' => ?classname<Dispatcher>, 'routeCollector' => ?classname<RouteCollector>, ) $options = shape()): Dispatcher; function cachedDispatcher( (function(RouteCollector): void) $routeDefinitionCallback, shape( 'routeParser' => ?classname<RouteParser>, 'dataGenerator' => ?classname<DataGenerator>, 'dispatcher' => ?classname<Dispatcher>, 'routeCollector' => ?classname<RouteCollector>, 'cacheDisabled' => ?bool, 'cacheFile' => ?string, ) $options = shape()): Dispatcher; } namespace FastRoute\DataGenerator { abstract class RegexBasedAbstract implements \FastRoute\DataGenerator { protected abstract function getApproxChunkSize(); protected abstract function processChunk($regexToRoutesMap); public function addRoute(string $httpMethod, array $routeData, mixed $handler): void; public function getData(): array; } class CharCountBased extends RegexBasedAbstract { protected function getApproxChunkSize(): int; protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; } class GroupCountBased extends RegexBasedAbstract { protected function getApproxChunkSize(): int; protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; } class GroupPosBased extends RegexBasedAbstract { protected function getApproxChunkSize(): int; protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; } class MarkBased extends RegexBasedAbstract { protected function getApproxChunkSize(): int; protected function processChunk(array<string, string> $regexToRoutesMap): array<string, mixed>; } } namespace FastRoute\Dispatcher { abstract class RegexBasedAbstract implements \FastRoute\Dispatcher { protected abstract function dispatchVariableRoute(array<array> $routeData, string $uri): array; public function dispatch(string $httpMethod, string $uri): array; } class GroupPosBased extends RegexBasedAbstract { public function __construct(array $data); protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; } class GroupCountBased extends RegexBasedAbstract { public function __construct(array $data); protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; } class CharCountBased extends RegexBasedAbstract { public function __construct(array $data); protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; } class MarkBased extends RegexBasedAbstract { public function __construct(array $data); protected function dispatchVariableRoute(array<array> $routeData, string $uri): array; } } namespace FastRoute\RouteParser { class Std implements \FastRoute\RouteParser { const string VARIABLE_REGEX = <<<'REGEX' \{ \s* ([a-zA-Z][a-zA-Z0-9_]*) \s* (?: : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) )? \} REGEX; const string DEFAULT_DISPATCH_REGEX = '[^/]+'; public function parse(string $route): array<array>; } } fast-route/.hhconfig 0000644 00000000021 14736103317 0010421 0 ustar 00 assume_php=false fast-route/src/Dispatcher/CharCountBased.php 0000644 00000001411 14736103317 0015052 0 ustar 00 <?php namespace FastRoute\Dispatcher; class CharCountBased extends RegexBasedAbstract { public function __construct($data) { list($this->staticRouteMap, $this->variableRouteData) = $data; } protected function dispatchVariableRoute($routeData, $uri) { foreach ($routeData as $data) { if (!preg_match($data['regex'], $uri . $data['suffix'], $matches)) { continue; } list($handler, $varNames) = $data['routeMap'][end($matches)]; $vars = []; $i = 0; foreach ($varNames as $varName) { $vars[$varName] = $matches[++$i]; } return [self::FOUND, $handler, $vars]; } return [self::NOT_FOUND]; } } fast-route/src/Dispatcher/MarkBased.php 0000644 00000001365 14736103317 0014066 0 ustar 00 <?php namespace FastRoute\Dispatcher; class MarkBased extends RegexBasedAbstract { public function __construct($data) { list($this->staticRouteMap, $this->variableRouteData) = $data; } protected function dispatchVariableRoute($routeData, $uri) { foreach ($routeData as $data) { if (!preg_match($data['regex'], $uri, $matches)) { continue; } list($handler, $varNames) = $data['routeMap'][$matches['MARK']]; $vars = []; $i = 0; foreach ($varNames as $varName) { $vars[$varName] = $matches[++$i]; } return [self::FOUND, $handler, $vars]; } return [self::NOT_FOUND]; } } fast-route/src/Dispatcher/GroupCountBased.php 0000644 00000001372 14736103317 0015277 0 ustar 00 <?php namespace FastRoute\Dispatcher; class GroupCountBased extends RegexBasedAbstract { public function __construct($data) { list($this->staticRouteMap, $this->variableRouteData) = $data; } protected function dispatchVariableRoute($routeData, $uri) { foreach ($routeData as $data) { if (!preg_match($data['regex'], $uri, $matches)) { continue; } list($handler, $varNames) = $data['routeMap'][count($matches)]; $vars = []; $i = 0; foreach ($varNames as $varName) { $vars[$varName] = $matches[++$i]; } return [self::FOUND, $handler, $vars]; } return [self::NOT_FOUND]; } } fast-route/src/Dispatcher/GroupPosBased.php 0000644 00000001467 14736103317 0014755 0 ustar 00 <?php namespace FastRoute\Dispatcher; class GroupPosBased extends RegexBasedAbstract { public function __construct($data) { list($this->staticRouteMap, $this->variableRouteData) = $data; } protected function dispatchVariableRoute($routeData, $uri) { foreach ($routeData as $data) { if (!preg_match($data['regex'], $uri, $matches)) { continue; } // find first non-empty match for ($i = 1; '' === $matches[$i]; ++$i); list($handler, $varNames) = $data['routeMap'][$i]; $vars = []; foreach ($varNames as $varName) { $vars[$varName] = $matches[$i++]; } return [self::FOUND, $handler, $vars]; } return [self::NOT_FOUND]; } } fast-route/src/Dispatcher/RegexBasedAbstract.php 0000644 00000005314 14736103317 0015730 0 ustar 00 <?php namespace FastRoute\Dispatcher; use FastRoute\Dispatcher; abstract class RegexBasedAbstract implements Dispatcher { /** @var mixed[][] */ protected $staticRouteMap = []; /** @var mixed[] */ protected $variableRouteData = []; /** * @return mixed[] */ abstract protected function dispatchVariableRoute($routeData, $uri); public function dispatch($httpMethod, $uri) { if (isset($this->staticRouteMap[$httpMethod][$uri])) { $handler = $this->staticRouteMap[$httpMethod][$uri]; return [self::FOUND, $handler, []]; } $varRouteData = $this->variableRouteData; if (isset($varRouteData[$httpMethod])) { $result = $this->dispatchVariableRoute($varRouteData[$httpMethod], $uri); if ($result[0] === self::FOUND) { return $result; } } // For HEAD requests, attempt fallback to GET if ($httpMethod === 'HEAD') { if (isset($this->staticRouteMap['GET'][$uri])) { $handler = $this->staticRouteMap['GET'][$uri]; return [self::FOUND, $handler, []]; } if (isset($varRouteData['GET'])) { $result = $this->dispatchVariableRoute($varRouteData['GET'], $uri); if ($result[0] === self::FOUND) { return $result; } } } // If nothing else matches, try fallback routes if (isset($this->staticRouteMap['*'][$uri])) { $handler = $this->staticRouteMap['*'][$uri]; return [self::FOUND, $handler, []]; } if (isset($varRouteData['*'])) { $result = $this->dispatchVariableRoute($varRouteData['*'], $uri); if ($result[0] === self::FOUND) { return $result; } } // Find allowed methods for this URI by matching against all other HTTP methods as well $allowedMethods = []; foreach ($this->staticRouteMap as $method => $uriMap) { if ($method !== $httpMethod && isset($uriMap[$uri])) { $allowedMethods[] = $method; } } foreach ($varRouteData as $method => $routeData) { if ($method === $httpMethod) { continue; } $result = $this->dispatchVariableRoute($routeData, $uri); if ($result[0] === self::FOUND) { $allowedMethods[] = $method; } } // If there are no allowed methods the route simply does not exist if ($allowedMethods) { return [self::METHOD_NOT_ALLOWED, $allowedMethods]; } return [self::NOT_FOUND]; } } fast-route/src/RouteParser/Std.php 0000644 00000005046 14736103317 0013154 0 ustar 00 <?php namespace FastRoute\RouteParser; use FastRoute\BadRouteException; use FastRoute\RouteParser; /** * Parses route strings of the following form: * * "/user/{name}[/{id:[0-9]+}]" */ class Std implements RouteParser { const VARIABLE_REGEX = <<<'REGEX' \{ \s* ([a-zA-Z_][a-zA-Z0-9_-]*) \s* (?: : \s* ([^{}]*(?:\{(?-1)\}[^{}]*)*) )? \} REGEX; const DEFAULT_DISPATCH_REGEX = '[^/]+'; public function parse($route) { $routeWithoutClosingOptionals = rtrim($route, ']'); $numOptionals = strlen($route) - strlen($routeWithoutClosingOptionals); // Split on [ while skipping placeholders $segments = preg_split('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \[~x', $routeWithoutClosingOptionals); if ($numOptionals !== count($segments) - 1) { // If there are any ] in the middle of the route, throw a more specific error message if (preg_match('~' . self::VARIABLE_REGEX . '(*SKIP)(*F) | \]~x', $routeWithoutClosingOptionals)) { throw new BadRouteException('Optional segments can only occur at the end of a route'); } throw new BadRouteException("Number of opening '[' and closing ']' does not match"); } $currentRoute = ''; $routeDatas = []; foreach ($segments as $n => $segment) { if ($segment === '' && $n !== 0) { throw new BadRouteException('Empty optional part'); } $currentRoute .= $segment; $routeDatas[] = $this->parsePlaceholders($currentRoute); } return $routeDatas; } /** * Parses a route string that does not contain optional segments. * * @param string * @return mixed[] */ private function parsePlaceholders($route) { if (!preg_match_all( '~' . self::VARIABLE_REGEX . '~x', $route, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER )) { return [$route]; } $offset = 0; $routeData = []; foreach ($matches as $set) { if ($set[0][1] > $offset) { $routeData[] = substr($route, $offset, $set[0][1] - $offset); } $routeData[] = [ $set[1][0], isset($set[2]) ? trim($set[2][0]) : self::DEFAULT_DISPATCH_REGEX ]; $offset = $set[0][1] + strlen($set[0][0]); } if ($offset !== strlen($route)) { $routeData[] = substr($route, $offset); } return $routeData; } } fast-route/src/RouteCollector.php 0000644 00000007423 14736103317 0013115 0 ustar 00 <?php namespace FastRoute; class RouteCollector { /** @var RouteParser */ protected $routeParser; /** @var DataGenerator */ protected $dataGenerator; /** @var string */ protected $currentGroupPrefix; /** * Constructs a route collector. * * @param RouteParser $routeParser * @param DataGenerator $dataGenerator */ public function __construct(RouteParser $routeParser, DataGenerator $dataGenerator) { $this->routeParser = $routeParser; $this->dataGenerator = $dataGenerator; $this->currentGroupPrefix = ''; } /** * Adds a route to the collection. * * The syntax used in the $route string depends on the used route parser. * * @param string|string[] $httpMethod * @param string $route * @param mixed $handler */ public function addRoute($httpMethod, $route, $handler) { $route = $this->currentGroupPrefix . $route; $routeDatas = $this->routeParser->parse($route); foreach ((array) $httpMethod as $method) { foreach ($routeDatas as $routeData) { $this->dataGenerator->addRoute($method, $routeData, $handler); } } } /** * Create a route group with a common prefix. * * All routes created in the passed callback will have the given group prefix prepended. * * @param string $prefix * @param callable $callback */ public function addGroup($prefix, callable $callback) { $previousGroupPrefix = $this->currentGroupPrefix; $this->currentGroupPrefix = $previousGroupPrefix . $prefix; $callback($this); $this->currentGroupPrefix = $previousGroupPrefix; } /** * Adds a GET route to the collection * * This is simply an alias of $this->addRoute('GET', $route, $handler) * * @param string $route * @param mixed $handler */ public function get($route, $handler) { $this->addRoute('GET', $route, $handler); } /** * Adds a POST route to the collection * * This is simply an alias of $this->addRoute('POST', $route, $handler) * * @param string $route * @param mixed $handler */ public function post($route, $handler) { $this->addRoute('POST', $route, $handler); } /** * Adds a PUT route to the collection * * This is simply an alias of $this->addRoute('PUT', $route, $handler) * * @param string $route * @param mixed $handler */ public function put($route, $handler) { $this->addRoute('PUT', $route, $handler); } /** * Adds a DELETE route to the collection * * This is simply an alias of $this->addRoute('DELETE', $route, $handler) * * @param string $route * @param mixed $handler */ public function delete($route, $handler) { $this->addRoute('DELETE', $route, $handler); } /** * Adds a PATCH route to the collection * * This is simply an alias of $this->addRoute('PATCH', $route, $handler) * * @param string $route * @param mixed $handler */ public function patch($route, $handler) { $this->addRoute('PATCH', $route, $handler); } /** * Adds a HEAD route to the collection * * This is simply an alias of $this->addRoute('HEAD', $route, $handler) * * @param string $route * @param mixed $handler */ public function head($route, $handler) { $this->addRoute('HEAD', $route, $handler); } /** * Returns the collected route data, as provided by the data generator. * * @return array */ public function getData() { return $this->dataGenerator->getData(); } } fast-route/src/BadRouteException.php 0000644 00000000121 14736103317 0013520 0 ustar 00 <?php namespace FastRoute; class BadRouteException extends \LogicException { } fast-route/src/DataGenerator.php 0000644 00000001252 14736103317 0012662 0 ustar 00 <?php namespace FastRoute; interface DataGenerator { /** * Adds a route to the data generator. The route data uses the * same format that is returned by RouterParser::parser(). * * The handler doesn't necessarily need to be a callable, it * can be arbitrary data that will be returned when the route * matches. * * @param string $httpMethod * @param array $routeData * @param mixed $handler */ public function addRoute($httpMethod, $routeData, $handler); /** * Returns dispatcher data in some unspecified format, which * depends on the used method of dispatch. */ public function getData(); } fast-route/src/Route.php 0000644 00000001631 14736103317 0011241 0 ustar 00 <?php namespace FastRoute; class Route { /** @var string */ public $httpMethod; /** @var string */ public $regex; /** @var array */ public $variables; /** @var mixed */ public $handler; /** * Constructs a route (value object). * * @param string $httpMethod * @param mixed $handler * @param string $regex * @param array $variables */ public function __construct($httpMethod, $handler, $regex, $variables) { $this->httpMethod = $httpMethod; $this->handler = $handler; $this->regex = $regex; $this->variables = $variables; } /** * Tests whether this route matches the given string. * * @param string $str * * @return bool */ public function matches($str) { $regex = '~^' . $this->regex . '$~'; return (bool) preg_match($regex, $str); } } fast-route/src/RouteParser.php 0000644 00000002007 14736103317 0012414 0 ustar 00 <?php namespace FastRoute; interface RouteParser { /** * Parses a route string into multiple route data arrays. * * The expected output is defined using an example: * * For the route string "/fixedRoutePart/{varName}[/moreFixed/{varName2:\d+}]", if {varName} is interpreted as * a placeholder and [...] is interpreted as an optional route part, the expected result is: * * [ * // first route: without optional part * [ * "/fixedRoutePart/", * ["varName", "[^/]+"], * ], * // second route: with optional part * [ * "/fixedRoutePart/", * ["varName", "[^/]+"], * "/moreFixed/", * ["varName2", [0-9]+"], * ], * ] * * Here one route string was converted into two route data arrays. * * @param string $route Route string to parse * * @return mixed[][] Array of route data arrays */ public function parse($route); } fast-route/src/bootstrap.php 0000644 00000000446 14736103317 0012163 0 ustar 00 <?php namespace FastRoute; require __DIR__ . '/functions.php'; spl_autoload_register(function ($class) { if (strpos($class, 'FastRoute\\') === 0) { $name = substr($class, strlen('FastRoute')); require __DIR__ . strtr($name, '\\', DIRECTORY_SEPARATOR) . '.php'; } }); fast-route/src/DataGenerator/CharCountBased.php 0000644 00000001467 14736103317 0015517 0 ustar 00 <?php namespace FastRoute\DataGenerator; class CharCountBased extends RegexBasedAbstract { protected function getApproxChunkSize() { return 30; } protected function processChunk($regexToRoutesMap) { $routeMap = []; $regexes = []; $suffixLen = 0; $suffix = ''; $count = count($regexToRoutesMap); foreach ($regexToRoutesMap as $regex => $route) { $suffixLen++; $suffix .= "\t"; $regexes[] = '(?:' . $regex . '/(\t{' . $suffixLen . '})\t{' . ($count - $suffixLen) . '})'; $routeMap[$suffix] = [$route->handler, $route->variables]; } $regex = '~^(?|' . implode('|', $regexes) . ')$~'; return ['regex' => $regex, 'suffix' => '/' . $suffix, 'routeMap' => $routeMap]; } } fast-route/src/DataGenerator/MarkBased.php 0000644 00000001220 14736103317 0014506 0 ustar 00 <?php namespace FastRoute\DataGenerator; class MarkBased extends RegexBasedAbstract { protected function getApproxChunkSize() { return 30; } protected function processChunk($regexToRoutesMap) { $routeMap = []; $regexes = []; $markName = 'a'; foreach ($regexToRoutesMap as $regex => $route) { $regexes[] = $regex . '(*MARK:' . $markName . ')'; $routeMap[$markName] = [$route->handler, $route->variables]; ++$markName; } $regex = '~^(?|' . implode('|', $regexes) . ')$~'; return ['regex' => $regex, 'routeMap' => $routeMap]; } } fast-route/src/DataGenerator/GroupCountBased.php 0000644 00000001434 14736103317 0015730 0 ustar 00 <?php namespace FastRoute\DataGenerator; class GroupCountBased extends RegexBasedAbstract { protected function getApproxChunkSize() { return 10; } protected function processChunk($regexToRoutesMap) { $routeMap = []; $regexes = []; $numGroups = 0; foreach ($regexToRoutesMap as $regex => $route) { $numVariables = count($route->variables); $numGroups = max($numGroups, $numVariables); $regexes[] = $regex . str_repeat('()', $numGroups - $numVariables); $routeMap[$numGroups + 1] = [$route->handler, $route->variables]; ++$numGroups; } $regex = '~^(?|' . implode('|', $regexes) . ')$~'; return ['regex' => $regex, 'routeMap' => $routeMap]; } } fast-route/src/DataGenerator/GroupPosBased.php 0000644 00000001210 14736103317 0015371 0 ustar 00 <?php namespace FastRoute\DataGenerator; class GroupPosBased extends RegexBasedAbstract { protected function getApproxChunkSize() { return 10; } protected function processChunk($regexToRoutesMap) { $routeMap = []; $regexes = []; $offset = 1; foreach ($regexToRoutesMap as $regex => $route) { $regexes[] = $regex; $routeMap[$offset] = [$route->handler, $route->variables]; $offset += count($route->variables); } $regex = '~^(?:' . implode('|', $regexes) . ')$~'; return ['regex' => $regex, 'routeMap' => $routeMap]; } } fast-route/src/DataGenerator/RegexBasedAbstract.php 0000644 00000012111 14736103317 0016353 0 ustar 00 <?php namespace FastRoute\DataGenerator; use FastRoute\BadRouteException; use FastRoute\DataGenerator; use FastRoute\Route; abstract class RegexBasedAbstract implements DataGenerator { /** @var mixed[][] */ protected $staticRoutes = []; /** @var Route[][] */ protected $methodToRegexToRoutesMap = []; /** * @return int */ abstract protected function getApproxChunkSize(); /** * @return mixed[] */ abstract protected function processChunk($regexToRoutesMap); public function addRoute($httpMethod, $routeData, $handler) { if ($this->isStaticRoute($routeData)) { $this->addStaticRoute($httpMethod, $routeData, $handler); } else { $this->addVariableRoute($httpMethod, $routeData, $handler); } } /** * @return mixed[] */ public function getData() { if (empty($this->methodToRegexToRoutesMap)) { return [$this->staticRoutes, []]; } return [$this->staticRoutes, $this->generateVariableRouteData()]; } /** * @return mixed[] */ private function generateVariableRouteData() { $data = []; foreach ($this->methodToRegexToRoutesMap as $method => $regexToRoutesMap) { $chunkSize = $this->computeChunkSize(count($regexToRoutesMap)); $chunks = array_chunk($regexToRoutesMap, $chunkSize, true); $data[$method] = array_map([$this, 'processChunk'], $chunks); } return $data; } /** * @param int * @return int */ private function computeChunkSize($count) { $numParts = max(1, round($count / $this->getApproxChunkSize())); return (int) ceil($count / $numParts); } /** * @param mixed[] * @return bool */ private function isStaticRoute($routeData) { return count($routeData) === 1 && is_string($routeData[0]); } private function addStaticRoute($httpMethod, $routeData, $handler) { $routeStr = $routeData[0]; if (isset($this->staticRoutes[$httpMethod][$routeStr])) { throw new BadRouteException(sprintf( 'Cannot register two routes matching "%s" for method "%s"', $routeStr, $httpMethod )); } if (isset($this->methodToRegexToRoutesMap[$httpMethod])) { foreach ($this->methodToRegexToRoutesMap[$httpMethod] as $route) { if ($route->matches($routeStr)) { throw new BadRouteException(sprintf( 'Static route "%s" is shadowed by previously defined variable route "%s" for method "%s"', $routeStr, $route->regex, $httpMethod )); } } } $this->staticRoutes[$httpMethod][$routeStr] = $handler; } private function addVariableRoute($httpMethod, $routeData, $handler) { list($regex, $variables) = $this->buildRegexForRoute($routeData); if (isset($this->methodToRegexToRoutesMap[$httpMethod][$regex])) { throw new BadRouteException(sprintf( 'Cannot register two routes matching "%s" for method "%s"', $regex, $httpMethod )); } $this->methodToRegexToRoutesMap[$httpMethod][$regex] = new Route( $httpMethod, $handler, $regex, $variables ); } /** * @param mixed[] * @return mixed[] */ private function buildRegexForRoute($routeData) { $regex = ''; $variables = []; foreach ($routeData as $part) { if (is_string($part)) { $regex .= preg_quote($part, '~'); continue; } list($varName, $regexPart) = $part; if (isset($variables[$varName])) { throw new BadRouteException(sprintf( 'Cannot use the same placeholder "%s" twice', $varName )); } if ($this->regexHasCapturingGroups($regexPart)) { throw new BadRouteException(sprintf( 'Regex "%s" for parameter "%s" contains a capturing group', $regexPart, $varName )); } $variables[$varName] = $varName; $regex .= '(' . $regexPart . ')'; } return [$regex, $variables]; } /** * @param string * @return bool */ private function regexHasCapturingGroups($regex) { if (false === strpos($regex, '(')) { // Needs to have at least a ( to contain a capturing group return false; } // Semi-accurate detection for capturing groups return (bool) preg_match( '~ (?: \(\?\( | \[ [^\]\\\\]* (?: \\\\ . [^\]\\\\]* )* \] | \\\\ . ) (*SKIP)(*FAIL) | \( (?! \? (?! <(?![!=]) | P< | \' ) | \* ) ~x', $regex ); } } fast-route/src/functions.php 0000644 00000004766 14736103317 0012167 0 ustar 00 <?php namespace FastRoute; if (!function_exists('FastRoute\simpleDispatcher')) { /** * @param callable $routeDefinitionCallback * @param array $options * * @return Dispatcher */ function simpleDispatcher(callable $routeDefinitionCallback, array $options = []) { $options += [ 'routeParser' => 'FastRoute\\RouteParser\\Std', 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', 'routeCollector' => 'FastRoute\\RouteCollector', ]; /** @var RouteCollector $routeCollector */ $routeCollector = new $options['routeCollector']( new $options['routeParser'], new $options['dataGenerator'] ); $routeDefinitionCallback($routeCollector); return new $options['dispatcher']($routeCollector->getData()); } /** * @param callable $routeDefinitionCallback * @param array $options * * @return Dispatcher */ function cachedDispatcher(callable $routeDefinitionCallback, array $options = []) { $options += [ 'routeParser' => 'FastRoute\\RouteParser\\Std', 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', 'routeCollector' => 'FastRoute\\RouteCollector', 'cacheDisabled' => false, ]; if (!isset($options['cacheFile'])) { throw new \LogicException('Must specify "cacheFile" option'); } if (!$options['cacheDisabled'] && file_exists($options['cacheFile'])) { $dispatchData = require $options['cacheFile']; if (!is_array($dispatchData)) { throw new \RuntimeException('Invalid cache file "' . $options['cacheFile'] . '"'); } return new $options['dispatcher']($dispatchData); } $routeCollector = new $options['routeCollector']( new $options['routeParser'], new $options['dataGenerator'] ); $routeDefinitionCallback($routeCollector); /** @var RouteCollector $routeCollector */ $dispatchData = $routeCollector->getData(); if (!$options['cacheDisabled']) { file_put_contents( $options['cacheFile'], '<?php return ' . var_export($dispatchData, true) . ';' ); } return new $options['dispatcher']($dispatchData); } } fast-route/src/Dispatcher.php 0000644 00000001122 14736103317 0012224 0 ustar 00 <?php namespace FastRoute; interface Dispatcher { const NOT_FOUND = 0; const FOUND = 1; const METHOD_NOT_ALLOWED = 2; /** * Dispatches against the provided HTTP method verb and URI. * * Returns array with one of the following formats: * * [self::NOT_FOUND] * [self::METHOD_NOT_ALLOWED, ['GET', 'OTHER_ALLOWED_METHODS']] * [self::FOUND, $handler, ['varName' => 'value', ...]] * * @param string $httpMethod * @param string $uri * * @return array */ public function dispatch($httpMethod, $uri); } fast-route/README.md 0000644 00000025557 14736103317 0010137 0 ustar 00 FastRoute - Fast request router for PHP ======================================= This library provides a fast implementation of a regular expression based router. [Blog post explaining how the implementation works and why it is fast.][blog_post] Install ------- To install with composer: ```sh composer require nikic/fast-route ``` Requires PHP 5.4 or newer. Usage ----- Here's a basic usage example: ```php <?php require '/path/to/vendor/autoload.php'; $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET', '/users', 'get_all_users_handler'); // {id} must be a number (\d+) $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler'); // The /{title} suffix is optional $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler'); }); // Fetch method and URI from somewhere $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = $_SERVER['REQUEST_URI']; // Strip query string (?foo=bar) and decode URI if (false !== $pos = strpos($uri, '?')) { $uri = substr($uri, 0, $pos); } $uri = rawurldecode($uri); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::NOT_FOUND: // ... 404 Not Found break; case FastRoute\Dispatcher::METHOD_NOT_ALLOWED: $allowedMethods = $routeInfo[1]; // ... 405 Method Not Allowed break; case FastRoute\Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; // ... call $handler with $vars break; } ``` ### Defining routes The routes are defined by calling the `FastRoute\simpleDispatcher()` function, which accepts a callable taking a `FastRoute\RouteCollector` instance. The routes are added by calling `addRoute()` on the collector instance: ```php $r->addRoute($method, $routePattern, $handler); ``` The `$method` is an uppercase HTTP method string for which a certain route should match. It is possible to specify multiple valid methods using an array: ```php // These two calls $r->addRoute('GET', '/test', 'handler'); $r->addRoute('POST', '/test', 'handler'); // Are equivalent to this one call $r->addRoute(['GET', 'POST'], '/test', 'handler'); ``` By default the `$routePattern` uses a syntax where `{foo}` specifies a placeholder with name `foo` and matching the regex `[^/]+`. To adjust the pattern the placeholder matches, you can specify a custom pattern by writing `{bar:[0-9]+}`. Some examples: ```php // Matches /user/42, but not /user/xyz $r->addRoute('GET', '/user/{id:\d+}', 'handler'); // Matches /user/foobar, but not /user/foo/bar $r->addRoute('GET', '/user/{name}', 'handler'); // Matches /user/foo/bar as well $r->addRoute('GET', '/user/{name:.+}', 'handler'); ``` Custom patterns for route placeholders cannot use capturing groups. For example `{lang:(en|de)}` is not a valid placeholder, because `()` is a capturing group. Instead you can use either `{lang:en|de}` or `{lang:(?:en|de)}`. Furthermore parts of the route enclosed in `[...]` are considered optional, so that `/foo[bar]` will match both `/foo` and `/foobar`. Optional parts are only supported in a trailing position, not in the middle of a route. ```php // This route $r->addRoute('GET', '/user/{id:\d+}[/{name}]', 'handler'); // Is equivalent to these two routes $r->addRoute('GET', '/user/{id:\d+}', 'handler'); $r->addRoute('GET', '/user/{id:\d+}/{name}', 'handler'); // Multiple nested optional parts are possible as well $r->addRoute('GET', '/user[/{id:\d+}[/{name}]]', 'handler'); // This route is NOT valid, because optional parts can only occur at the end $r->addRoute('GET', '/user[/{id:\d+}]/{name}', 'handler'); ``` The `$handler` parameter does not necessarily have to be a callback, it could also be a controller class name or any other kind of data you wish to associate with the route. FastRoute only tells you which handler corresponds to your URI, how you interpret it is up to you. #### Shorcut methods for common request methods For the `GET`, `POST`, `PUT`, `PATCH`, `DELETE` and `HEAD` request methods shortcut methods are available. For example: ```php $r->get('/get-route', 'get_handler'); $r->post('/post-route', 'post_handler'); ``` Is equivalent to: ```php $r->addRoute('GET', '/get-route', 'get_handler'); $r->addRoute('POST', '/post-route', 'post_handler'); ``` #### Route Groups Additionally, you can specify routes inside of a group. All routes defined inside a group will have a common prefix. For example, defining your routes as: ```php $r->addGroup('/admin', function (RouteCollector $r) { $r->addRoute('GET', '/do-something', 'handler'); $r->addRoute('GET', '/do-another-thing', 'handler'); $r->addRoute('GET', '/do-something-else', 'handler'); }); ``` Will have the same result as: ```php $r->addRoute('GET', '/admin/do-something', 'handler'); $r->addRoute('GET', '/admin/do-another-thing', 'handler'); $r->addRoute('GET', '/admin/do-something-else', 'handler'); ``` Nested groups are also supported, in which case the prefixes of all the nested groups are combined. ### Caching The reason `simpleDispatcher` accepts a callback for defining the routes is to allow seamless caching. By using `cachedDispatcher` instead of `simpleDispatcher` you can cache the generated routing data and construct the dispatcher from the cached information: ```php <?php $dispatcher = FastRoute\cachedDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0'); $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1'); $r->addRoute('GET', '/user/{name}', 'handler2'); }, [ 'cacheFile' => __DIR__ . '/route.cache', /* required */ 'cacheDisabled' => IS_DEBUG_ENABLED, /* optional, enabled by default */ ]); ``` The second parameter to the function is an options array, which can be used to specify the cache file location, among other things. ### Dispatching a URI A URI is dispatched by calling the `dispatch()` method of the created dispatcher. This method accepts the HTTP method and a URI. Getting those two bits of information (and normalizing them appropriately) is your job - this library is not bound to the PHP web SAPIs. The `dispatch()` method returns an array whose first element contains a status code. It is one of `Dispatcher::NOT_FOUND`, `Dispatcher::METHOD_NOT_ALLOWED` and `Dispatcher::FOUND`. For the method not allowed status the second array element contains a list of HTTP methods allowed for the supplied URI. For example: [FastRoute\Dispatcher::METHOD_NOT_ALLOWED, ['GET', 'POST']] > **NOTE:** The HTTP specification requires that a `405 Method Not Allowed` response include the `Allow:` header to detail available methods for the requested resource. Applications using FastRoute should use the second array element to add this header when relaying a 405 response. For the found status the second array element is the handler that was associated with the route and the third array element is a dictionary of placeholder names to their values. For example: /* Routing against GET /user/nikic/42 */ [FastRoute\Dispatcher::FOUND, 'handler0', ['name' => 'nikic', 'id' => '42']] ### Overriding the route parser and dispatcher The routing process makes use of three components: A route parser, a data generator and a dispatcher. The three components adhere to the following interfaces: ```php <?php namespace FastRoute; interface RouteParser { public function parse($route); } interface DataGenerator { public function addRoute($httpMethod, $routeData, $handler); public function getData(); } interface Dispatcher { const NOT_FOUND = 0, FOUND = 1, METHOD_NOT_ALLOWED = 2; public function dispatch($httpMethod, $uri); } ``` The route parser takes a route pattern string and converts it into an array of route infos, where each route info is again an array of it's parts. The structure is best understood using an example: /* The route /user/{id:\d+}[/{name}] converts to the following array: */ [ [ '/user/', ['id', '\d+'], ], [ '/user/', ['id', '\d+'], '/', ['name', '[^/]+'], ], ] This array can then be passed to the `addRoute()` method of a data generator. After all routes have been added the `getData()` of the generator is invoked, which returns all the routing data required by the dispatcher. The format of this data is not further specified - it is tightly coupled to the corresponding dispatcher. The dispatcher accepts the routing data via a constructor and provides a `dispatch()` method, which you're already familiar with. The route parser can be overwritten individually (to make use of some different pattern syntax), however the data generator and dispatcher should always be changed as a pair, as the output from the former is tightly coupled to the input of the latter. The reason the generator and the dispatcher are separate is that only the latter is needed when using caching (as the output of the former is what is being cached.) When using the `simpleDispatcher` / `cachedDispatcher` functions from above the override happens through the options array: ```php <?php $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { /* ... */ }, [ 'routeParser' => 'FastRoute\\RouteParser\\Std', 'dataGenerator' => 'FastRoute\\DataGenerator\\GroupCountBased', 'dispatcher' => 'FastRoute\\Dispatcher\\GroupCountBased', ]); ``` The above options array corresponds to the defaults. By replacing `GroupCountBased` by `GroupPosBased` you could switch to a different dispatching strategy. ### A Note on HEAD Requests The HTTP spec requires servers to [support both GET and HEAD methods][2616-511]: > The methods GET and HEAD MUST be supported by all general-purpose servers To avoid forcing users to manually register HEAD routes for each resource we fallback to matching an available GET route for a given resource. The PHP web SAPI transparently removes the entity body from HEAD responses so this behavior has no effect on the vast majority of users. However, implementers using FastRoute outside the web SAPI environment (e.g. a custom server) MUST NOT send entity bodies generated in response to HEAD requests. If you are a non-SAPI user this is *your responsibility*; FastRoute has no purview to prevent you from breaking HTTP in such cases. Finally, note that applications MAY always specify their own HEAD method route for a given resource to bypass this behavior entirely. ### Credits This library is based on a router that [Levi Morrison][levi] implemented for the Aerys server. A large number of tests, as well as HTTP compliance considerations, were provided by [Daniel Lowrey][rdlowrey]. [2616-511]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1 "RFC 2616 Section 5.1.1" [blog_post]: http://nikic.github.io/2014/02/18/Fast-request-routing-using-regular-expressions.html [levi]: https://github.com/morrisonlevi [rdlowrey]: https://github.com/rdlowrey fast-route/LICENSE 0000644 00000002723 14736103317 0007653 0 ustar 00 Copyright (c) 2013 by Nikita Popov. Some rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.