updated-packages
This commit is contained in:
501
vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php
vendored
Normal file
501
vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherDumper.php
vendored
Normal file
@@ -0,0 +1,501 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher\Dumper;
|
||||
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||||
use Symfony\Component\Routing\Route;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
|
||||
/**
|
||||
* CompiledUrlMatcherDumper creates PHP arrays to be used with CompiledUrlMatcher.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
* @author Tobias Schultze <http://tobion.de>
|
||||
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
class CompiledUrlMatcherDumper extends MatcherDumper
|
||||
{
|
||||
private $expressionLanguage;
|
||||
private $signalingException;
|
||||
|
||||
/**
|
||||
* @var ExpressionFunctionProviderInterface[]
|
||||
*/
|
||||
private $expressionLanguageProviders = [];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function dump(array $options = [])
|
||||
{
|
||||
return <<<EOF
|
||||
<?php
|
||||
|
||||
/**
|
||||
* This file has been auto-generated
|
||||
* by the Symfony Routing Component.
|
||||
*/
|
||||
|
||||
return [
|
||||
{$this->generateCompiledRoutes()}];
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
|
||||
{
|
||||
$this->expressionLanguageProviders[] = $provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the arrays for CompiledUrlMatcher's constructor.
|
||||
*/
|
||||
public function getCompiledRoutes(bool $forDump = false): array
|
||||
{
|
||||
// Group hosts by same-suffix, re-order when possible
|
||||
$matchHost = false;
|
||||
$routes = new StaticPrefixCollection();
|
||||
foreach ($this->getRoutes()->all() as $name => $route) {
|
||||
if ($host = $route->getHost()) {
|
||||
$matchHost = true;
|
||||
$host = '/'.strtr(strrev($host), '}.{', '(/)');
|
||||
}
|
||||
|
||||
$routes->addRoute($host ?: '/(.*)', [$name, $route]);
|
||||
}
|
||||
|
||||
if ($matchHost) {
|
||||
$compiledRoutes = [true];
|
||||
$routes = $routes->populateCollection(new RouteCollection());
|
||||
} else {
|
||||
$compiledRoutes = [false];
|
||||
$routes = $this->getRoutes();
|
||||
}
|
||||
|
||||
[$staticRoutes, $dynamicRoutes] = $this->groupStaticRoutes($routes);
|
||||
|
||||
$conditions = [null];
|
||||
$compiledRoutes[] = $this->compileStaticRoutes($staticRoutes, $conditions);
|
||||
$chunkLimit = \count($dynamicRoutes);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
$this->signalingException = new \RuntimeException('Compilation failed: regular expression is too large');
|
||||
$compiledRoutes = array_merge($compiledRoutes, $this->compileDynamicRoutes($dynamicRoutes, $matchHost, $chunkLimit, $conditions));
|
||||
|
||||
break;
|
||||
} catch (\Exception $e) {
|
||||
if (1 < $chunkLimit && $this->signalingException === $e) {
|
||||
$chunkLimit = 1 + ($chunkLimit >> 1);
|
||||
continue;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
if ($forDump) {
|
||||
$compiledRoutes[2] = $compiledRoutes[4];
|
||||
}
|
||||
unset($conditions[0]);
|
||||
|
||||
if ($conditions) {
|
||||
foreach ($conditions as $expression => $condition) {
|
||||
$conditions[$expression] = "case {$condition}: return {$expression};";
|
||||
}
|
||||
|
||||
$checkConditionCode = <<<EOF
|
||||
static function (\$condition, \$context, \$request) { // \$checkCondition
|
||||
switch (\$condition) {
|
||||
{$this->indent(implode("\n", $conditions), 3)}
|
||||
}
|
||||
}
|
||||
EOF;
|
||||
$compiledRoutes[4] = $forDump ? $checkConditionCode.",\n" : eval('return '.$checkConditionCode.';');
|
||||
} else {
|
||||
$compiledRoutes[4] = $forDump ? " null, // \$checkCondition\n" : null;
|
||||
}
|
||||
|
||||
return $compiledRoutes;
|
||||
}
|
||||
|
||||
private function generateCompiledRoutes(): string
|
||||
{
|
||||
[$matchHost, $staticRoutes, $regexpCode, $dynamicRoutes, $checkConditionCode] = $this->getCompiledRoutes(true);
|
||||
|
||||
$code = self::export($matchHost).', // $matchHost'."\n";
|
||||
|
||||
$code .= '[ // $staticRoutes'."\n";
|
||||
foreach ($staticRoutes as $path => $routes) {
|
||||
$code .= sprintf(" %s => [\n", self::export($path));
|
||||
foreach ($routes as $route) {
|
||||
$code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
|
||||
}
|
||||
$code .= " ],\n";
|
||||
}
|
||||
$code .= "],\n";
|
||||
|
||||
$code .= sprintf("[ // \$regexpList%s\n],\n", $regexpCode);
|
||||
|
||||
$code .= '[ // $dynamicRoutes'."\n";
|
||||
foreach ($dynamicRoutes as $path => $routes) {
|
||||
$code .= sprintf(" %s => [\n", self::export($path));
|
||||
foreach ($routes as $route) {
|
||||
$code .= sprintf(" [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
|
||||
}
|
||||
$code .= " ],\n";
|
||||
}
|
||||
$code .= "],\n";
|
||||
$code = preg_replace('/ => \[\n (\[.+?),\n \],/', ' => [$1],', $code);
|
||||
|
||||
return $this->indent($code, 1).$checkConditionCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits static routes from dynamic routes, so that they can be matched first, using a simple switch.
|
||||
*/
|
||||
private function groupStaticRoutes(RouteCollection $collection): array
|
||||
{
|
||||
$staticRoutes = $dynamicRegex = [];
|
||||
$dynamicRoutes = new RouteCollection();
|
||||
|
||||
foreach ($collection->all() as $name => $route) {
|
||||
$compiledRoute = $route->compile();
|
||||
$staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
|
||||
$hostRegex = $compiledRoute->getHostRegex();
|
||||
$regex = $compiledRoute->getRegex();
|
||||
if ($hasTrailingSlash = '/' !== $route->getPath()) {
|
||||
$pos = strrpos($regex, '$');
|
||||
$hasTrailingSlash = '/' === $regex[$pos - 1];
|
||||
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
|
||||
}
|
||||
|
||||
if (!$compiledRoute->getPathVariables()) {
|
||||
$host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
|
||||
$url = $route->getPath();
|
||||
if ($hasTrailingSlash) {
|
||||
$url = substr($url, 0, -1);
|
||||
}
|
||||
foreach ($dynamicRegex as [$hostRx, $rx, $prefix]) {
|
||||
if (('' === $prefix || str_starts_with($url, $prefix)) && (preg_match($rx, $url) || preg_match($rx, $url.'/')) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
|
||||
$dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
|
||||
$dynamicRoutes->add($name, $route);
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
|
||||
$staticRoutes[$url][$name] = [$route, $hasTrailingSlash];
|
||||
} else {
|
||||
$dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
|
||||
$dynamicRoutes->add($name, $route);
|
||||
}
|
||||
}
|
||||
|
||||
return [$staticRoutes, $dynamicRoutes];
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles static routes in a switch statement.
|
||||
*
|
||||
* Condition-less paths are put in a static array in the switch's default, with generic matching logic.
|
||||
* Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
private function compileStaticRoutes(array $staticRoutes, array &$conditions): array
|
||||
{
|
||||
if (!$staticRoutes) {
|
||||
return [];
|
||||
}
|
||||
$compiledRoutes = [];
|
||||
|
||||
foreach ($staticRoutes as $url => $routes) {
|
||||
$compiledRoutes[$url] = [];
|
||||
foreach ($routes as $name => [$route, $hasTrailingSlash]) {
|
||||
$compiledRoutes[$url][] = $this->compileRoute($route, $name, (!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex()) ?: null, $hasTrailingSlash, false, $conditions);
|
||||
}
|
||||
}
|
||||
|
||||
return $compiledRoutes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a regular expression followed by a switch statement to match dynamic routes.
|
||||
*
|
||||
* The regular expression matches both the host and the pathinfo at the same time. For stellar performance,
|
||||
* it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible.
|
||||
*
|
||||
* Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23).
|
||||
* This name is used to "switch" to the additional logic required to match the final route.
|
||||
*
|
||||
* Condition-less paths are put in a static array in the switch's default, with generic matching logic.
|
||||
* Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
|
||||
*
|
||||
* Last but not least:
|
||||
* - Because it is not possible to mix unicode/non-unicode patterns in a single regexp, several of them can be generated.
|
||||
* - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the
|
||||
* matching-but-failing subpattern is excluded by replacing its name by "(*F)", which forces a failure-to-match.
|
||||
* To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur.
|
||||
*/
|
||||
private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array
|
||||
{
|
||||
if (!$collection->all()) {
|
||||
return [[], [], ''];
|
||||
}
|
||||
$regexpList = [];
|
||||
$code = '';
|
||||
$state = (object) [
|
||||
'regexMark' => 0,
|
||||
'regex' => [],
|
||||
'routes' => [],
|
||||
'mark' => 0,
|
||||
'markTail' => 0,
|
||||
'hostVars' => [],
|
||||
'vars' => [],
|
||||
];
|
||||
$state->getVars = static function ($m) use ($state) {
|
||||
if ('_route' === $m[1]) {
|
||||
return '?:';
|
||||
}
|
||||
|
||||
$state->vars[] = $m[1];
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
$chunkSize = 0;
|
||||
$prev = null;
|
||||
$perModifiers = [];
|
||||
foreach ($collection->all() as $name => $route) {
|
||||
preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
|
||||
if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {
|
||||
$chunkSize = 1;
|
||||
$routes = new RouteCollection();
|
||||
$perModifiers[] = [$rx[0], $routes];
|
||||
$prev = $rx[0];
|
||||
}
|
||||
$routes->add($name, $route);
|
||||
}
|
||||
|
||||
foreach ($perModifiers as [$modifiers, $routes]) {
|
||||
$prev = false;
|
||||
$perHost = [];
|
||||
foreach ($routes->all() as $name => $route) {
|
||||
$regex = $route->compile()->getHostRegex();
|
||||
if ($prev !== $regex) {
|
||||
$routes = new RouteCollection();
|
||||
$perHost[] = [$regex, $routes];
|
||||
$prev = $regex;
|
||||
}
|
||||
$routes->add($name, $route);
|
||||
}
|
||||
$prev = false;
|
||||
$rx = '{^(?';
|
||||
$code .= "\n {$state->mark} => ".self::export($rx);
|
||||
$startingMark = $state->mark;
|
||||
$state->mark += \strlen($rx);
|
||||
$state->regex = $rx;
|
||||
|
||||
foreach ($perHost as [$hostRegex, $routes]) {
|
||||
if ($matchHost) {
|
||||
if ($hostRegex) {
|
||||
preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx);
|
||||
$state->vars = [];
|
||||
$hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.';
|
||||
$state->hostVars = $state->vars;
|
||||
} else {
|
||||
$hostRegex = '(?:(?:[^./]*+\.)++)';
|
||||
$state->hostVars = [];
|
||||
}
|
||||
$state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?");
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
$prev = true;
|
||||
}
|
||||
|
||||
$tree = new StaticPrefixCollection();
|
||||
foreach ($routes->all() as $name => $route) {
|
||||
preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
|
||||
|
||||
$state->vars = [];
|
||||
$regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
|
||||
if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
|
||||
$regex = substr($regex, 0, -1);
|
||||
}
|
||||
$hasTrailingVar = (bool) preg_match('#\{\w+\}/?$#', $route->getPath());
|
||||
|
||||
$tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]);
|
||||
}
|
||||
|
||||
$code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);
|
||||
}
|
||||
if ($matchHost) {
|
||||
$code .= "\n .')'";
|
||||
$state->regex .= ')';
|
||||
}
|
||||
$rx = ")/?$}{$modifiers}";
|
||||
$code .= "\n .'{$rx}',";
|
||||
$state->regex .= $rx;
|
||||
$state->markTail = 0;
|
||||
|
||||
// if the regex is too large, throw a signaling exception to recompute with smaller chunk size
|
||||
set_error_handler(function ($type, $message) { throw str_contains($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); });
|
||||
try {
|
||||
preg_match($state->regex, '');
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
$regexpList[$startingMark] = $state->regex;
|
||||
}
|
||||
|
||||
$state->routes[$state->mark][] = [null, null, null, null, false, false, 0];
|
||||
unset($state->getVars);
|
||||
|
||||
return [$regexpList, $state->routes, $code];
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a regexp tree of subpatterns that matches nested same-prefix routes.
|
||||
*
|
||||
* @param \stdClass $state A simple state object that keeps track of the progress of the compilation,
|
||||
* and gathers the generated switch's "case" and "default" statements
|
||||
*/
|
||||
private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string
|
||||
{
|
||||
$code = '';
|
||||
$prevRegex = null;
|
||||
$routes = $tree->getRoutes();
|
||||
|
||||
foreach ($routes as $i => $route) {
|
||||
if ($route instanceof StaticPrefixCollection) {
|
||||
$prevRegex = null;
|
||||
$prefix = substr($route->getPrefix(), $prefixLen);
|
||||
$state->mark += \strlen($rx = "|{$prefix}(?");
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
$code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions));
|
||||
$code .= "\n .')'";
|
||||
$state->regex .= ')';
|
||||
++$state->markTail;
|
||||
continue;
|
||||
}
|
||||
|
||||
[$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route;
|
||||
$compiledRoute = $route->compile();
|
||||
$vars = array_merge($state->hostVars, $vars);
|
||||
|
||||
if ($compiledRoute->getRegex() === $prevRegex) {
|
||||
$state->routes[$state->mark][] = $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions);
|
||||
continue;
|
||||
}
|
||||
|
||||
$state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen;
|
||||
$state->markTail = 2 + \strlen($state->mark);
|
||||
$rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark);
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
|
||||
$prevRegex = $compiledRoute->getRegex();
|
||||
$state->routes[$state->mark] = [$this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions)];
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a single Route to PHP code used to match it against the path info.
|
||||
*/
|
||||
private function compileRoute(Route $route, string $name, $vars, bool $hasTrailingSlash, bool $hasTrailingVar, array &$conditions): array
|
||||
{
|
||||
$defaults = $route->getDefaults();
|
||||
|
||||
if (isset($defaults['_canonical_route'])) {
|
||||
$name = $defaults['_canonical_route'];
|
||||
unset($defaults['_canonical_route']);
|
||||
}
|
||||
|
||||
if ($condition = $route->getCondition()) {
|
||||
$condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request']);
|
||||
$condition = $conditions[$condition] ?? $conditions[$condition] = (str_contains($condition, '$request') ? 1 : -1) * \count($conditions);
|
||||
} else {
|
||||
$condition = null;
|
||||
}
|
||||
|
||||
return [
|
||||
['_route' => $name] + $defaults,
|
||||
$vars,
|
||||
array_flip($route->getMethods()) ?: null,
|
||||
array_flip($route->getSchemes()) ?: null,
|
||||
$hasTrailingSlash,
|
||||
$hasTrailingVar,
|
||||
$condition,
|
||||
];
|
||||
}
|
||||
|
||||
private function getExpressionLanguage(): ExpressionLanguage
|
||||
{
|
||||
if (null === $this->expressionLanguage) {
|
||||
if (!class_exists(ExpressionLanguage::class)) {
|
||||
throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
|
||||
}
|
||||
$this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
|
||||
}
|
||||
|
||||
return $this->expressionLanguage;
|
||||
}
|
||||
|
||||
private function indent(string $code, int $level = 1): string
|
||||
{
|
||||
return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public static function export($value): string
|
||||
{
|
||||
if (null === $value) {
|
||||
return 'null';
|
||||
}
|
||||
if (!\is_array($value)) {
|
||||
if (\is_object($value)) {
|
||||
throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.');
|
||||
}
|
||||
|
||||
return str_replace("\n", '\'."\n".\'', var_export($value, true));
|
||||
}
|
||||
if (!$value) {
|
||||
return '[]';
|
||||
}
|
||||
|
||||
$i = 0;
|
||||
$export = '[';
|
||||
|
||||
foreach ($value as $k => $v) {
|
||||
if ($i === $k) {
|
||||
++$i;
|
||||
} else {
|
||||
$export .= self::export($k).' => ';
|
||||
|
||||
if (\is_int($k) && $i < $k) {
|
||||
$i = 1 + $k;
|
||||
}
|
||||
}
|
||||
|
||||
$export .= self::export($v).', ';
|
||||
}
|
||||
|
||||
return substr_replace($export, ']', -2);
|
||||
}
|
||||
}
|
@@ -15,23 +15,26 @@ use Symfony\Component\Routing\Exception\MethodNotAllowedException;
|
||||
use Symfony\Component\Routing\Exception\NoConfigurationException;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface;
|
||||
use Symfony\Component\Routing\RequestContext;
|
||||
|
||||
/**
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @property RequestContext $context
|
||||
*/
|
||||
trait PhpMatcherTrait
|
||||
trait CompiledUrlMatcherTrait
|
||||
{
|
||||
private $matchHost = false;
|
||||
private $staticRoutes = array();
|
||||
private $regexpList = array();
|
||||
private $dynamicRoutes = array();
|
||||
private $staticRoutes = [];
|
||||
private $regexpList = [];
|
||||
private $dynamicRoutes = [];
|
||||
private $checkCondition;
|
||||
|
||||
public function match($pathinfo)
|
||||
public function match($pathinfo): array
|
||||
{
|
||||
$allow = $allowSchemes = array();
|
||||
$allow = $allowSchemes = [];
|
||||
if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) {
|
||||
return $ret;
|
||||
}
|
||||
@@ -39,9 +42,9 @@ trait PhpMatcherTrait
|
||||
throw new MethodNotAllowedException(array_keys($allow));
|
||||
}
|
||||
if (!$this instanceof RedirectableUrlMatcherInterface) {
|
||||
throw new ResourceNotFoundException();
|
||||
throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
}
|
||||
if (!\in_array($this->context->getMethod(), array('HEAD', 'GET'), true)) {
|
||||
if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) {
|
||||
// no-op
|
||||
} elseif ($allowSchemes) {
|
||||
redirect_scheme:
|
||||
@@ -54,8 +57,8 @@ trait PhpMatcherTrait
|
||||
} finally {
|
||||
$this->context->setScheme($scheme);
|
||||
}
|
||||
} elseif ('/' !== $pathinfo) {
|
||||
$pathinfo = '/' !== $pathinfo[-1] ? $pathinfo.'/' : substr($pathinfo, 0, -1);
|
||||
} elseif ('/' !== $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/') {
|
||||
$pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo;
|
||||
if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) {
|
||||
return $this->redirect($pathinfo, $ret['_route']) + $ret;
|
||||
}
|
||||
@@ -64,16 +67,16 @@ trait PhpMatcherTrait
|
||||
}
|
||||
}
|
||||
|
||||
throw new ResourceNotFoundException();
|
||||
throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
}
|
||||
|
||||
private function doMatch(string $rawPathinfo, array &$allow = array(), array &$allowSchemes = array()): ?array
|
||||
private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = []): array
|
||||
{
|
||||
$allow = $allowSchemes = array();
|
||||
$pathinfo = rawurldecode($rawPathinfo) ?: '/';
|
||||
$allow = $allowSchemes = [];
|
||||
$pathinfo = rawurldecode($pathinfo) ?: '/';
|
||||
$trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
|
||||
$context = $this->context;
|
||||
$requestMethod = $canonicalMethod = $context->getMethod();
|
||||
$trimmedPathinfo = '/' !== $pathinfo && '/' === $pathinfo[-1] ? substr($pathinfo, 0, -1) : $pathinfo;
|
||||
|
||||
if ($this->matchHost) {
|
||||
$host = strtolower($context->getHost());
|
||||
@@ -82,20 +85,13 @@ trait PhpMatcherTrait
|
||||
if ('HEAD' === $requestMethod) {
|
||||
$canonicalMethod = 'GET';
|
||||
}
|
||||
$supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface;
|
||||
|
||||
foreach ($this->staticRoutes[$trimmedPathinfo] ?? array() as list($ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, $condition)) {
|
||||
foreach ($this->staticRoutes[$trimmedPathinfo] ?? [] as [$ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition]) {
|
||||
if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('/' === $pathinfo || $hasTrailingSlash === ('/' === $pathinfo[-1])) {
|
||||
// no-op
|
||||
} elseif ($this instanceof RedirectableUrlMatcherInterface) {
|
||||
return null;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($requiredHost) {
|
||||
if ('#' !== $requiredHost[0] ? $requiredHost !== $host : !preg_match($requiredHost, $host, $hostMatches)) {
|
||||
continue;
|
||||
@@ -106,13 +102,19 @@ trait PhpMatcherTrait
|
||||
}
|
||||
}
|
||||
|
||||
$hasRequiredScheme = !$requiredSchemes || isset($requiredSchemes[$context->getScheme()]);
|
||||
if ($requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) {
|
||||
if ($hasRequiredScheme) {
|
||||
$allow += $requiredMethods;
|
||||
if ('/' !== $pathinfo && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
|
||||
if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) {
|
||||
return $allow = $allowSchemes = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$hasRequiredScheme = !$requiredSchemes || isset($requiredSchemes[$context->getScheme()]);
|
||||
if ($hasRequiredScheme && $requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) {
|
||||
$allow += $requiredMethods;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$hasRequiredScheme) {
|
||||
$allowSchemes += $requiredSchemes;
|
||||
continue;
|
||||
@@ -125,16 +127,30 @@ trait PhpMatcherTrait
|
||||
|
||||
foreach ($this->regexpList as $offset => $regex) {
|
||||
while (preg_match($regex, $matchedPathinfo, $matches)) {
|
||||
foreach ($this->dynamicRoutes[$m = (int) $matches['MARK']] as list($ret, $vars, $requiredMethods, $requiredSchemes, $hasTrailingSlash, $condition)) {
|
||||
if ($condition && !($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) {
|
||||
continue;
|
||||
foreach ($this->dynamicRoutes[$m = (int) $matches['MARK']] as [$ret, $vars, $requiredMethods, $requiredSchemes, $hasTrailingSlash, $hasTrailingVar, $condition]) {
|
||||
if (null !== $condition) {
|
||||
if (0 === $condition) { // marks the last route in the regexp
|
||||
continue 3;
|
||||
}
|
||||
if (!($this->checkCondition)($condition, $context, 0 < $condition ? $request ?? $request = $this->request ?: $this->createRequest($pathinfo) : null)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if ('/' === $pathinfo || (!$hasTrailingSlash ? '/' !== $pathinfo[-1] || !preg_match($regex, substr($pathinfo, 0, -1), $n) || $m !== (int) $n['MARK'] : '/' === $pathinfo[-1])) {
|
||||
// no-op
|
||||
} elseif ($this instanceof RedirectableUrlMatcherInterface) {
|
||||
return null;
|
||||
} else {
|
||||
$hasTrailingVar = $trimmedPathinfo !== $pathinfo && $hasTrailingVar;
|
||||
|
||||
if ($hasTrailingVar && ($hasTrailingSlash || (null === $n = $matches[\count($vars)] ?? null) || '/' !== ($n[-1] ?? '/')) && preg_match($regex, $this->matchHost ? $host.'.'.$trimmedPathinfo : $trimmedPathinfo, $n) && $m === (int) $n['MARK']) {
|
||||
if ($hasTrailingSlash) {
|
||||
$matches = $n;
|
||||
} else {
|
||||
$hasTrailingVar = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
|
||||
if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) {
|
||||
return $allow = $allowSchemes = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -144,15 +160,13 @@ trait PhpMatcherTrait
|
||||
}
|
||||
}
|
||||
|
||||
$hasRequiredScheme = !$requiredSchemes || isset($requiredSchemes[$context->getScheme()]);
|
||||
if ($requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) {
|
||||
if ($hasRequiredScheme) {
|
||||
$allow += $requiredMethods;
|
||||
}
|
||||
if ($requiredSchemes && !isset($requiredSchemes[$context->getScheme()])) {
|
||||
$allowSchemes += $requiredSchemes;
|
||||
continue;
|
||||
}
|
||||
if (!$hasRequiredScheme) {
|
||||
$allowSchemes += $requiredSchemes;
|
||||
|
||||
if ($requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) {
|
||||
$allow += $requiredMethods;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -168,6 +182,6 @@ trait PhpMatcherTrait
|
||||
throw new NoConfigurationException();
|
||||
}
|
||||
|
||||
return null;
|
||||
return [];
|
||||
}
|
||||
}
|
@@ -24,11 +24,9 @@ interface MatcherDumperInterface
|
||||
* Dumps a set of routes to a string representation of executable code
|
||||
* that can then be used to match a request against these routes.
|
||||
*
|
||||
* @param array $options An array of options
|
||||
*
|
||||
* @return string Executable code
|
||||
*/
|
||||
public function dump(array $options = array());
|
||||
public function dump(array $options = []);
|
||||
|
||||
/**
|
||||
* Gets the routes to dump.
|
||||
|
@@ -11,10 +11,7 @@
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher\Dumper;
|
||||
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||||
use Symfony\Component\Routing\Route;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3, use "CompiledUrlMatcherDumper" instead.', PhpMatcherDumper::class), \E_USER_DEPRECATED);
|
||||
|
||||
/**
|
||||
* PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
|
||||
@@ -23,17 +20,11 @@ use Symfony\Component\Routing\RouteCollection;
|
||||
* @author Tobias Schultze <http://tobion.de>
|
||||
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @deprecated since Symfony 4.3, use CompiledUrlMatcherDumper instead.
|
||||
*/
|
||||
class PhpMatcherDumper extends MatcherDumper
|
||||
class PhpMatcherDumper extends CompiledUrlMatcherDumper
|
||||
{
|
||||
private $expressionLanguage;
|
||||
private $signalingException;
|
||||
|
||||
/**
|
||||
* @var ExpressionFunctionProviderInterface[]
|
||||
*/
|
||||
private $expressionLanguageProviders = array();
|
||||
|
||||
/**
|
||||
* Dumps a set of routes to a PHP class.
|
||||
*
|
||||
@@ -46,20 +37,24 @@ class PhpMatcherDumper extends MatcherDumper
|
||||
*
|
||||
* @return string A PHP class representing the matcher class
|
||||
*/
|
||||
public function dump(array $options = array())
|
||||
public function dump(array $options = [])
|
||||
{
|
||||
$options = array_replace(array(
|
||||
$options = array_replace([
|
||||
'class' => 'ProjectUrlMatcher',
|
||||
'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
|
||||
), $options);
|
||||
], $options);
|
||||
|
||||
// trailing slash support is only enabled if we know how to redirect the user
|
||||
$interfaces = class_implements($options['base_class']);
|
||||
$code = parent::dump();
|
||||
$code = preg_replace('#\n ([^ ].*?) // \$(\w++)$#m', "\n \$this->$2 = $1", $code);
|
||||
$code = str_replace(",\n $", ";\n $", $code);
|
||||
$code = substr($code, strpos($code, '$this') - 4, -5).";\n";
|
||||
$code = preg_replace('/^ \$this->\w++ = (?:null|false|\[\n \]);\n/m', '', $code);
|
||||
$code = str_replace("\n ", "\n ", "\n".$code);
|
||||
|
||||
return <<<EOF
|
||||
<?php
|
||||
|
||||
use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherTrait;
|
||||
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherTrait;
|
||||
use Symfony\Component\Routing\RequestContext;
|
||||
|
||||
/**
|
||||
@@ -68,422 +63,13 @@ use Symfony\Component\Routing\RequestContext;
|
||||
*/
|
||||
class {$options['class']} extends {$options['base_class']}
|
||||
{
|
||||
use PhpMatcherTrait;
|
||||
use CompiledUrlMatcherTrait;
|
||||
|
||||
public function __construct(RequestContext \$context)
|
||||
{
|
||||
\$this->context = \$context;
|
||||
{$this->generateProperties()} }
|
||||
\$this->context = \$context;{$code} }
|
||||
}
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
|
||||
{
|
||||
$this->expressionLanguageProviders[] = $provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the code for the match method implementing UrlMatcherInterface.
|
||||
*/
|
||||
private function generateProperties(): string
|
||||
{
|
||||
// Group hosts by same-suffix, re-order when possible
|
||||
$matchHost = false;
|
||||
$routes = new StaticPrefixCollection();
|
||||
foreach ($this->getRoutes()->all() as $name => $route) {
|
||||
if ($host = $route->getHost()) {
|
||||
$matchHost = true;
|
||||
$host = '/'.strtr(strrev($host), '}.{', '(/)');
|
||||
}
|
||||
|
||||
$routes->addRoute($host ?: '/(.*)', array($name, $route));
|
||||
}
|
||||
|
||||
if ($matchHost) {
|
||||
$code = '$this->matchHost = true;'."\n";
|
||||
$routes = $routes->populateCollection(new RouteCollection());
|
||||
} else {
|
||||
$code = '';
|
||||
$routes = $this->getRoutes();
|
||||
}
|
||||
|
||||
list($staticRoutes, $dynamicRoutes) = $this->groupStaticRoutes($routes);
|
||||
|
||||
$conditions = array(null);
|
||||
$code .= $this->compileStaticRoutes($staticRoutes, $conditions);
|
||||
$chunkLimit = \count($dynamicRoutes);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
$this->signalingException = new \RuntimeException('preg_match(): Compilation failed: regular expression is too large');
|
||||
$code .= $this->compileDynamicRoutes($dynamicRoutes, $matchHost, $chunkLimit, $conditions);
|
||||
break;
|
||||
} catch (\Exception $e) {
|
||||
if (1 < $chunkLimit && $this->signalingException === $e) {
|
||||
$chunkLimit = 1 + ($chunkLimit >> 1);
|
||||
continue;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
unset($conditions[0]);
|
||||
|
||||
if (!$conditions) {
|
||||
return $this->indent($code, 2);
|
||||
}
|
||||
|
||||
foreach ($conditions as $expression => $condition) {
|
||||
$conditions[$expression] = "case {$condition}: return {$expression};";
|
||||
}
|
||||
|
||||
return $this->indent($code, 2).<<<EOF
|
||||
\$this->checkCondition = static function (\$condition, \$context, \$request) {
|
||||
switch (\$condition) {
|
||||
{$this->indent(implode("\n", $conditions), 4)}
|
||||
}
|
||||
};
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits static routes from dynamic routes, so that they can be matched first, using a simple switch.
|
||||
*/
|
||||
private function groupStaticRoutes(RouteCollection $collection): array
|
||||
{
|
||||
$staticRoutes = $dynamicRegex = array();
|
||||
$dynamicRoutes = new RouteCollection();
|
||||
|
||||
foreach ($collection->all() as $name => $route) {
|
||||
$compiledRoute = $route->compile();
|
||||
$hostRegex = $compiledRoute->getHostRegex();
|
||||
$regex = $compiledRoute->getRegex();
|
||||
if ($hasTrailingSlash = '/' !== $route->getPath()) {
|
||||
$pos = strrpos($regex, '$');
|
||||
$hasTrailingSlash = '/' === $regex[$pos - 1];
|
||||
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
|
||||
}
|
||||
|
||||
if (!$compiledRoute->getPathVariables()) {
|
||||
$host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
|
||||
$url = $route->getPath();
|
||||
if ($hasTrailingSlash) {
|
||||
$url = substr($url, 0, -1);
|
||||
}
|
||||
foreach ($dynamicRegex as list($hostRx, $rx)) {
|
||||
if (preg_match($rx, $url) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
|
||||
$dynamicRegex[] = array($hostRegex, $regex);
|
||||
$dynamicRoutes->add($name, $route);
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
|
||||
$staticRoutes[$url][$name] = array($route, $hasTrailingSlash);
|
||||
} else {
|
||||
$dynamicRegex[] = array($hostRegex, $regex);
|
||||
$dynamicRoutes->add($name, $route);
|
||||
}
|
||||
}
|
||||
|
||||
return array($staticRoutes, $dynamicRoutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles static routes in a switch statement.
|
||||
*
|
||||
* Condition-less paths are put in a static array in the switch's default, with generic matching logic.
|
||||
* Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
private function compileStaticRoutes(array $staticRoutes, array &$conditions): string
|
||||
{
|
||||
if (!$staticRoutes) {
|
||||
return '';
|
||||
}
|
||||
$code = '';
|
||||
|
||||
foreach ($staticRoutes as $url => $routes) {
|
||||
$code .= self::export($url)." => array(\n";
|
||||
foreach ($routes as $name => list($route, $hasTrailingSlash)) {
|
||||
$code .= $this->compileRoute($route, $name, !$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex() ?: null, $hasTrailingSlash, $conditions);
|
||||
}
|
||||
$code .= "),\n";
|
||||
}
|
||||
|
||||
if ($code) {
|
||||
return "\$this->staticRoutes = array(\n{$this->indent($code, 1)});\n";
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a regular expression followed by a switch statement to match dynamic routes.
|
||||
*
|
||||
* The regular expression matches both the host and the pathinfo at the same time. For stellar performance,
|
||||
* it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible.
|
||||
*
|
||||
* Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23).
|
||||
* This name is used to "switch" to the additional logic required to match the final route.
|
||||
*
|
||||
* Condition-less paths are put in a static array in the switch's default, with generic matching logic.
|
||||
* Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
|
||||
*
|
||||
* Last but not least:
|
||||
* - Because it is not possibe to mix unicode/non-unicode patterns in a single regexp, several of them can be generated.
|
||||
* - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the
|
||||
* matching-but-failing subpattern is blacklisted by replacing its name by "(*F)", which forces a failure-to-match.
|
||||
* To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur.
|
||||
*/
|
||||
private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): string
|
||||
{
|
||||
if (!$collection->all()) {
|
||||
return '';
|
||||
}
|
||||
$code = '';
|
||||
$state = (object) array(
|
||||
'regex' => '',
|
||||
'routes' => '',
|
||||
'mark' => 0,
|
||||
'markTail' => 0,
|
||||
'hostVars' => array(),
|
||||
'vars' => array(),
|
||||
);
|
||||
$state->getVars = static function ($m) use ($state) {
|
||||
if ('_route' === $m[1]) {
|
||||
return '?:';
|
||||
}
|
||||
|
||||
$state->vars[] = $m[1];
|
||||
|
||||
return '';
|
||||
};
|
||||
|
||||
$chunkSize = 0;
|
||||
$prev = null;
|
||||
$perModifiers = array();
|
||||
foreach ($collection->all() as $name => $route) {
|
||||
preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
|
||||
if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {
|
||||
$chunkSize = 1;
|
||||
$routes = new RouteCollection();
|
||||
$perModifiers[] = array($rx[0], $routes);
|
||||
$prev = $rx[0];
|
||||
}
|
||||
$routes->add($name, $route);
|
||||
}
|
||||
|
||||
foreach ($perModifiers as list($modifiers, $routes)) {
|
||||
$prev = false;
|
||||
$perHost = array();
|
||||
foreach ($routes->all() as $name => $route) {
|
||||
$regex = $route->compile()->getHostRegex();
|
||||
if ($prev !== $regex) {
|
||||
$routes = new RouteCollection();
|
||||
$perHost[] = array($regex, $routes);
|
||||
$prev = $regex;
|
||||
}
|
||||
$routes->add($name, $route);
|
||||
}
|
||||
$prev = false;
|
||||
$rx = '{^(?';
|
||||
$code .= "\n {$state->mark} => ".self::export($rx);
|
||||
$state->mark += \strlen($rx);
|
||||
$state->regex = $rx;
|
||||
|
||||
foreach ($perHost as list($hostRegex, $routes)) {
|
||||
if ($matchHost) {
|
||||
if ($hostRegex) {
|
||||
preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx);
|
||||
$state->vars = array();
|
||||
$hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.';
|
||||
$state->hostVars = $state->vars;
|
||||
} else {
|
||||
$hostRegex = '(?:(?:[^./]*+\.)++)';
|
||||
$state->hostVars = array();
|
||||
}
|
||||
$state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?");
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
$prev = true;
|
||||
}
|
||||
|
||||
$tree = new StaticPrefixCollection();
|
||||
foreach ($routes->all() as $name => $route) {
|
||||
preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
|
||||
|
||||
$state->vars = array();
|
||||
$regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
|
||||
if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
|
||||
$regex = substr($regex, 0, -1);
|
||||
}
|
||||
|
||||
$tree->addRoute($regex, array($name, $regex, $state->vars, $route, $hasTrailingSlash));
|
||||
}
|
||||
|
||||
$code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);
|
||||
}
|
||||
if ($matchHost) {
|
||||
$code .= "\n .')'";
|
||||
$state->regex .= ')';
|
||||
}
|
||||
$rx = ")(?:/?)$}{$modifiers}";
|
||||
$code .= "\n .'{$rx}',";
|
||||
$state->regex .= $rx;
|
||||
$state->markTail = 0;
|
||||
|
||||
// if the regex is too large, throw a signaling exception to recompute with smaller chunk size
|
||||
set_error_handler(function ($type, $message) { throw 0 === strpos($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); });
|
||||
try {
|
||||
preg_match($state->regex, '');
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
}
|
||||
|
||||
unset($state->getVars);
|
||||
|
||||
return "\$this->regexpList = array({$code}\n);\n"
|
||||
."\$this->dynamicRoutes = array(\n{$this->indent($state->routes, 1)});\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a regexp tree of subpatterns that matches nested same-prefix routes.
|
||||
*
|
||||
* @param \stdClass $state A simple state object that keeps track of the progress of the compilation,
|
||||
* and gathers the generated switch's "case" and "default" statements
|
||||
*/
|
||||
private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string
|
||||
{
|
||||
$code = '';
|
||||
$prevRegex = null;
|
||||
$routes = $tree->getRoutes();
|
||||
|
||||
foreach ($routes as $i => $route) {
|
||||
if ($route instanceof StaticPrefixCollection) {
|
||||
$prevRegex = null;
|
||||
$prefix = substr($route->getPrefix(), $prefixLen);
|
||||
$state->mark += \strlen($rx = "|{$prefix}(?");
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
$code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions));
|
||||
$code .= "\n .')'";
|
||||
$state->regex .= ')';
|
||||
++$state->markTail;
|
||||
continue;
|
||||
}
|
||||
|
||||
list($name, $regex, $vars, $route, $hasTrailingSlash) = $route;
|
||||
$compiledRoute = $route->compile();
|
||||
$vars = array_merge($state->hostVars, $vars);
|
||||
|
||||
if ($compiledRoute->getRegex() === $prevRegex) {
|
||||
$state->routes = substr_replace($state->routes, $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $conditions), -3, 0);
|
||||
continue;
|
||||
}
|
||||
|
||||
$state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen;
|
||||
$state->markTail = 2 + \strlen($state->mark);
|
||||
$rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark);
|
||||
$code .= "\n .".self::export($rx);
|
||||
$state->regex .= $rx;
|
||||
|
||||
$prevRegex = $compiledRoute->getRegex();
|
||||
$state->routes .= sprintf("%s => array(\n%s),\n", $state->mark, $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $conditions));
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a single Route to PHP code used to match it against the path info.
|
||||
*/
|
||||
private function compileRoute(Route $route, string $name, $vars, bool $hasTrailingSlash, array &$conditions): string
|
||||
{
|
||||
$defaults = $route->getDefaults();
|
||||
|
||||
if (isset($defaults['_canonical_route'])) {
|
||||
$name = $defaults['_canonical_route'];
|
||||
unset($defaults['_canonical_route']);
|
||||
}
|
||||
|
||||
if ($condition = $route->getCondition()) {
|
||||
$condition = $this->getExpressionLanguage()->compile($condition, array('context', 'request'));
|
||||
$condition = $conditions[$condition] ?? $conditions[$condition] = (false !== strpos($condition, '$request') ? 1 : -1) * \count($conditions);
|
||||
} else {
|
||||
$condition = 'null';
|
||||
}
|
||||
|
||||
return sprintf(
|
||||
" array(%s, %s, %s, %s, %s, %s),\n",
|
||||
self::export(array('_route' => $name) + $defaults),
|
||||
self::export($vars),
|
||||
self::export(array_flip($route->getMethods()) ?: null),
|
||||
self::export(array_flip($route->getSchemes()) ?: null),
|
||||
self::export($hasTrailingSlash),
|
||||
$condition
|
||||
);
|
||||
}
|
||||
|
||||
private function getExpressionLanguage()
|
||||
{
|
||||
if (null === $this->expressionLanguage) {
|
||||
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
|
||||
throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
|
||||
}
|
||||
$this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
|
||||
}
|
||||
|
||||
return $this->expressionLanguage;
|
||||
}
|
||||
|
||||
private function indent($code, $level = 1)
|
||||
{
|
||||
$code = preg_replace('/ => array\(\n (array\(.+),\n\),/', ' => array($1),', $code);
|
||||
|
||||
return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public static function export($value): string
|
||||
{
|
||||
if (null === $value) {
|
||||
return 'null';
|
||||
}
|
||||
if (!\is_array($value)) {
|
||||
if (\is_object($value)) {
|
||||
throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.');
|
||||
}
|
||||
|
||||
return str_replace("\n", '\'."\n".\'', var_export($value, true));
|
||||
}
|
||||
if (!$value) {
|
||||
return 'array()';
|
||||
}
|
||||
|
||||
$i = 0;
|
||||
$export = 'array(';
|
||||
|
||||
foreach ($value as $k => $v) {
|
||||
if ($i === $k) {
|
||||
++$i;
|
||||
} else {
|
||||
$export .= self::export($k).' => ';
|
||||
|
||||
if (\is_int($k) && $i < $k) {
|
||||
$i = 1 + $k;
|
||||
}
|
||||
}
|
||||
|
||||
$export .= self::export($v).', ';
|
||||
}
|
||||
|
||||
return substr_replace($export, ')', -2);
|
||||
}
|
||||
}
|
||||
|
@@ -28,17 +28,17 @@ class StaticPrefixCollection
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
private $staticPrefixes = array();
|
||||
private $staticPrefixes = [];
|
||||
|
||||
/**
|
||||
* @var string[]
|
||||
*/
|
||||
private $prefixes = array();
|
||||
private $prefixes = [];
|
||||
|
||||
/**
|
||||
* @var array[]|self[]
|
||||
*/
|
||||
private $items = array();
|
||||
private $items = [];
|
||||
|
||||
public function __construct(string $prefix = '/')
|
||||
{
|
||||
@@ -65,12 +65,12 @@ class StaticPrefixCollection
|
||||
*/
|
||||
public function addRoute(string $prefix, $route)
|
||||
{
|
||||
list($prefix, $staticPrefix) = $this->getCommonPrefix($prefix, $prefix);
|
||||
[$prefix, $staticPrefix] = $this->getCommonPrefix($prefix, $prefix);
|
||||
|
||||
for ($i = \count($this->items) - 1; 0 <= $i; --$i) {
|
||||
$item = $this->items[$i];
|
||||
|
||||
list($commonPrefix, $commonStaticPrefix) = $this->getCommonPrefix($prefix, $this->prefixes[$i]);
|
||||
[$commonPrefix, $commonStaticPrefix] = $this->getCommonPrefix($prefix, $this->prefixes[$i]);
|
||||
|
||||
if ($this->prefix === $commonPrefix) {
|
||||
// the new route and a previous one have no common prefix, let's see if they are exclusive to each others
|
||||
@@ -104,9 +104,9 @@ class StaticPrefixCollection
|
||||
} else {
|
||||
// the new route and a previous one have a common prefix, let's merge them
|
||||
$child = new self($commonPrefix);
|
||||
list($child->prefixes[0], $child->staticPrefixes[0]) = $child->getCommonPrefix($this->prefixes[$i], $this->prefixes[$i]);
|
||||
list($child->prefixes[1], $child->staticPrefixes[1]) = $child->getCommonPrefix($prefix, $prefix);
|
||||
$child->items = array($this->items[$i], $route);
|
||||
[$child->prefixes[0], $child->staticPrefixes[0]] = $child->getCommonPrefix($this->prefixes[$i], $this->prefixes[$i]);
|
||||
[$child->prefixes[1], $child->staticPrefixes[1]] = $child->getCommonPrefix($prefix, $prefix);
|
||||
$child->items = [$this->items[$i], $route];
|
||||
|
||||
$this->staticPrefixes[$i] = $commonStaticPrefix;
|
||||
$this->prefixes[$i] = $commonPrefix;
|
||||
@@ -149,7 +149,7 @@ class StaticPrefixCollection
|
||||
$baseLength = \strlen($this->prefix);
|
||||
$end = min(\strlen($prefix), \strlen($anotherPrefix));
|
||||
$staticLength = null;
|
||||
set_error_handler(array(__CLASS__, 'handleError'));
|
||||
set_error_handler([__CLASS__, 'handleError']);
|
||||
|
||||
for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {
|
||||
if ('(' === $prefix[$i]) {
|
||||
@@ -192,11 +192,11 @@ class StaticPrefixCollection
|
||||
} while (0b10 === (\ord($prefix[$i]) >> 6));
|
||||
}
|
||||
|
||||
return array(substr($prefix, 0, $i), substr($prefix, 0, $staticLength ?? $i));
|
||||
return [substr($prefix, 0, $i), substr($prefix, 0, $staticLength ?? $i)];
|
||||
}
|
||||
|
||||
public static function handleError($type, $msg)
|
||||
public static function handleError(int $type, string $msg)
|
||||
{
|
||||
return 0 === strpos($msg, 'preg_match(): Compilation failed: lookbehind assertion is not fixed length');
|
||||
return str_contains($msg, 'Compilation failed: lookbehind assertion is not fixed length');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user