Upgrade framework
This commit is contained in:
31
vendor/symfony/routing/Matcher/CompiledUrlMatcher.php
vendored
Normal file
31
vendor/symfony/routing/Matcher/CompiledUrlMatcher.php
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
<?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;
|
||||
|
||||
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherTrait;
|
||||
use Symfony\Component\Routing\RequestContext;
|
||||
|
||||
/**
|
||||
* Matches URLs based on rules dumped by CompiledUrlMatcherDumper.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
class CompiledUrlMatcher extends UrlMatcher
|
||||
{
|
||||
use CompiledUrlMatcherTrait;
|
||||
|
||||
public function __construct(array $compiledRoutes, RequestContext $context)
|
||||
{
|
||||
$this->context = $context;
|
||||
[$this->matchHost, $this->staticRoutes, $this->regexpList, $this->dynamicRoutes, $this->checkCondition] = $compiledRoutes;
|
||||
}
|
||||
}
|
||||
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 ?\Exception $signalingException = null;
|
||||
|
||||
/**
|
||||
* @var ExpressionFunctionProviderInterface[]
|
||||
*/
|
||||
private array $expressionLanguageProviders = [];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function dump(array $options = []): string
|
||||
{
|
||||
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, string|array|null $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 (!isset($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(mixed $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);
|
||||
}
|
||||
}
|
||||
191
vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php
vendored
Normal file
191
vendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php
vendored
Normal file
@@ -0,0 +1,191 @@
|
||||
<?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\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 CompiledUrlMatcherTrait
|
||||
{
|
||||
private bool $matchHost = false;
|
||||
private array $staticRoutes = [];
|
||||
private array $regexpList = [];
|
||||
private array $dynamicRoutes = [];
|
||||
|
||||
/**
|
||||
* @var callable|null
|
||||
*/
|
||||
private $checkCondition;
|
||||
|
||||
public function match(string $pathinfo): array
|
||||
{
|
||||
$allow = $allowSchemes = [];
|
||||
if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) {
|
||||
return $ret;
|
||||
}
|
||||
if ($allow) {
|
||||
throw new MethodNotAllowedException(array_keys($allow));
|
||||
}
|
||||
if (!$this instanceof RedirectableUrlMatcherInterface) {
|
||||
throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
}
|
||||
if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) {
|
||||
// no-op
|
||||
} elseif ($allowSchemes) {
|
||||
redirect_scheme:
|
||||
$scheme = $this->context->getScheme();
|
||||
$this->context->setScheme(key($allowSchemes));
|
||||
try {
|
||||
if ($ret = $this->doMatch($pathinfo)) {
|
||||
return $this->redirect($pathinfo, $ret['_route'], $this->context->getScheme()) + $ret;
|
||||
}
|
||||
} finally {
|
||||
$this->context->setScheme($scheme);
|
||||
}
|
||||
} elseif ('/' !== $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/') {
|
||||
$pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo;
|
||||
if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) {
|
||||
return $this->redirect($pathinfo, $ret['_route']) + $ret;
|
||||
}
|
||||
if ($allowSchemes) {
|
||||
goto redirect_scheme;
|
||||
}
|
||||
}
|
||||
|
||||
throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
}
|
||||
|
||||
private function doMatch(string $pathinfo, array &$allow = [], array &$allowSchemes = []): array
|
||||
{
|
||||
$allow = $allowSchemes = [];
|
||||
$pathinfo = rawurldecode($pathinfo) ?: '/';
|
||||
$trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
|
||||
$context = $this->context;
|
||||
$requestMethod = $canonicalMethod = $context->getMethod();
|
||||
|
||||
if ($this->matchHost) {
|
||||
$host = strtolower($context->getHost());
|
||||
}
|
||||
|
||||
if ('HEAD' === $requestMethod) {
|
||||
$canonicalMethod = 'GET';
|
||||
}
|
||||
$supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface;
|
||||
|
||||
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 ($requiredHost) {
|
||||
if ('{' !== $requiredHost[0] ? $requiredHost !== $host : !preg_match($requiredHost, $host, $hostMatches)) {
|
||||
continue;
|
||||
}
|
||||
if ('{' === $requiredHost[0] && $hostMatches) {
|
||||
$hostMatches['_route'] = $ret['_route'];
|
||||
$ret = $this->mergeDefaults($hostMatches, $ret);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
$matchedPathinfo = $this->matchHost ? $host.'.'.$pathinfo : $pathinfo;
|
||||
|
||||
foreach ($this->regexpList as $offset => $regex) {
|
||||
while (preg_match($regex, $matchedPathinfo, $matches)) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
foreach ($vars as $i => $v) {
|
||||
if (isset($matches[1 + $i])) {
|
||||
$ret[$v] = $matches[1 + $i];
|
||||
}
|
||||
}
|
||||
|
||||
if ($requiredSchemes && !isset($requiredSchemes[$context->getScheme()])) {
|
||||
$allowSchemes += $requiredSchemes;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($requiredMethods && !isset($requiredMethods[$canonicalMethod]) && !isset($requiredMethods[$requestMethod])) {
|
||||
$allow += $requiredMethods;
|
||||
continue;
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
$regex = substr_replace($regex, 'F', $m - $offset, 1 + \strlen($m));
|
||||
$offset += \strlen($m);
|
||||
}
|
||||
}
|
||||
|
||||
if ('/' === $pathinfo && !$allow && !$allowSchemes) {
|
||||
throw new NoConfigurationException();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* Collection of routes.
|
||||
*
|
||||
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class DumperCollection implements \IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* @var DumperCollection|null
|
||||
*/
|
||||
private $parent;
|
||||
|
||||
/**
|
||||
* @var DumperCollection[]|DumperRoute[]
|
||||
*/
|
||||
private $children = array();
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $attributes = array();
|
||||
|
||||
/**
|
||||
* Returns the children routes and collections.
|
||||
*
|
||||
* @return self[]|DumperRoute[]
|
||||
*/
|
||||
public function all()
|
||||
{
|
||||
return $this->children;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a route or collection.
|
||||
*
|
||||
* @param DumperRoute|DumperCollection The route or collection
|
||||
*/
|
||||
public function add($child)
|
||||
{
|
||||
if ($child instanceof self) {
|
||||
$child->setParent($this);
|
||||
}
|
||||
$this->children[] = $child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets children.
|
||||
*
|
||||
* @param array $children The children
|
||||
*/
|
||||
public function setAll(array $children)
|
||||
{
|
||||
foreach ($children as $child) {
|
||||
if ($child instanceof self) {
|
||||
$child->setParent($this);
|
||||
}
|
||||
}
|
||||
$this->children = $children;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator over the children.
|
||||
*
|
||||
* @return \Iterator|DumperCollection[]|DumperRoute[] The iterator
|
||||
*/
|
||||
public function getIterator()
|
||||
{
|
||||
return new \ArrayIterator($this->children);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the root of the collection.
|
||||
*
|
||||
* @return self The root collection
|
||||
*/
|
||||
public function getRoot()
|
||||
{
|
||||
return (null !== $this->parent) ? $this->parent->getRoot() : $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the parent collection.
|
||||
*
|
||||
* @return self|null The parent collection or null if the collection has no parent
|
||||
*/
|
||||
protected function getParent()
|
||||
{
|
||||
return $this->parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the parent collection.
|
||||
*
|
||||
* @param DumperCollection $parent The parent collection
|
||||
*/
|
||||
protected function setParent(DumperCollection $parent)
|
||||
{
|
||||
$this->parent = $parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the attribute is defined.
|
||||
*
|
||||
* @param string $name The attribute name
|
||||
*
|
||||
* @return bool true if the attribute is defined, false otherwise
|
||||
*/
|
||||
public function hasAttribute($name)
|
||||
{
|
||||
return array_key_exists($name, $this->attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an attribute by name.
|
||||
*
|
||||
* @param string $name The attribute name
|
||||
* @param mixed $default Default value is the attribute doesn't exist
|
||||
*
|
||||
* @return mixed The attribute value
|
||||
*/
|
||||
public function getAttribute($name, $default = null)
|
||||
{
|
||||
return $this->hasAttribute($name) ? $this->attributes[$name] : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets an attribute by name.
|
||||
*
|
||||
* @param string $name The attribute name
|
||||
* @param mixed $value The attribute value
|
||||
*/
|
||||
public function setAttribute($name, $value)
|
||||
{
|
||||
$this->attributes[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets multiple attributes.
|
||||
*
|
||||
* @param array $attributes The attributes
|
||||
*/
|
||||
public function setAttributes($attributes)
|
||||
{
|
||||
$this->attributes = $attributes;
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
<?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\Routing\Route;
|
||||
|
||||
/**
|
||||
* Container for a Route.
|
||||
*
|
||||
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class DumperRoute
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* @var Route
|
||||
*/
|
||||
private $route;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $name The route name
|
||||
* @param Route $route The route
|
||||
*/
|
||||
public function __construct($name, Route $route)
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->route = $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the route name.
|
||||
*
|
||||
* @return string The route name
|
||||
*/
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the route.
|
||||
*
|
||||
* @return Route The route
|
||||
*/
|
||||
public function getRoute()
|
||||
{
|
||||
return $this->route;
|
||||
}
|
||||
}
|
||||
@@ -20,16 +20,8 @@ use Symfony\Component\Routing\RouteCollection;
|
||||
*/
|
||||
abstract class MatcherDumper implements MatcherDumperInterface
|
||||
{
|
||||
/**
|
||||
* @var RouteCollection
|
||||
*/
|
||||
private $routes;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param RouteCollection $routes The RouteCollection to dump
|
||||
*/
|
||||
public function __construct(RouteCollection $routes)
|
||||
{
|
||||
$this->routes = $routes;
|
||||
@@ -38,7 +30,7 @@ abstract class MatcherDumper implements MatcherDumperInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getRoutes()
|
||||
public function getRoutes(): RouteCollection
|
||||
{
|
||||
return $this->routes;
|
||||
}
|
||||
|
||||
@@ -23,17 +23,11 @@ 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 = []): string;
|
||||
|
||||
/**
|
||||
* Gets the routes to dump.
|
||||
*
|
||||
* @return RouteCollection A RouteCollection instance
|
||||
*/
|
||||
public function getRoutes();
|
||||
public function getRoutes(): RouteCollection;
|
||||
}
|
||||
|
||||
@@ -1,431 +0,0 @@
|
||||
<?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\Routing\Route;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
|
||||
/**
|
||||
* PhpMatcherDumper creates a PHP class able to match URLs for a given set of routes.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
* @author Tobias Schultze <http://tobion.de>
|
||||
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
|
||||
*/
|
||||
class PhpMatcherDumper extends MatcherDumper
|
||||
{
|
||||
private $expressionLanguage;
|
||||
|
||||
/**
|
||||
* @var ExpressionFunctionProviderInterface[]
|
||||
*/
|
||||
private $expressionLanguageProviders = array();
|
||||
|
||||
/**
|
||||
* Dumps a set of routes to a PHP class.
|
||||
*
|
||||
* Available options:
|
||||
*
|
||||
* * class: The class name
|
||||
* * base_class: The base class name
|
||||
*
|
||||
* @param array $options An array of options
|
||||
*
|
||||
* @return string A PHP class representing the matcher class
|
||||
*/
|
||||
public function dump(array $options = array())
|
||||
{
|
||||
$options = array_replace(array(
|
||||
'class' => 'ProjectUrlMatcher',
|
||||
'base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
|
||||
), $options);
|
||||
|
||||
// trailing slash support is only enabled if we know how to redirect the user
|
||||
$interfaces = class_implements($options['base_class']);
|
||||
$supportsRedirections = isset($interfaces['Symfony\\Component\\Routing\\Matcher\\RedirectableUrlMatcherInterface']);
|
||||
|
||||
return <<<EOF
|
||||
<?php
|
||||
|
||||
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\RequestContext;
|
||||
|
||||
/**
|
||||
* {$options['class']}.
|
||||
*
|
||||
* This class has been auto-generated
|
||||
* by the Symfony Routing Component.
|
||||
*/
|
||||
class {$options['class']} extends {$options['base_class']}
|
||||
{
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct(RequestContext \$context)
|
||||
{
|
||||
\$this->context = \$context;
|
||||
}
|
||||
|
||||
{$this->generateMatchMethod($supportsRedirections)}
|
||||
}
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
|
||||
{
|
||||
$this->expressionLanguageProviders[] = $provider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the code for the match method implementing UrlMatcherInterface.
|
||||
*
|
||||
* @param bool $supportsRedirections Whether redirections are supported by the base class
|
||||
*
|
||||
* @return string Match method as PHP code
|
||||
*/
|
||||
private function generateMatchMethod($supportsRedirections)
|
||||
{
|
||||
$code = rtrim($this->compileRoutes($this->getRoutes(), $supportsRedirections), "\n");
|
||||
|
||||
return <<<EOF
|
||||
public function match(\$pathinfo)
|
||||
{
|
||||
\$allow = array();
|
||||
\$pathinfo = rawurldecode(\$pathinfo);
|
||||
\$trimmedPathinfo = rtrim(\$pathinfo, '/');
|
||||
\$context = \$this->context;
|
||||
\$request = \$this->request;
|
||||
\$requestMethod = \$canonicalMethod = \$context->getMethod();
|
||||
\$scheme = \$context->getScheme();
|
||||
|
||||
if ('HEAD' === \$requestMethod) {
|
||||
\$canonicalMethod = 'GET';
|
||||
}
|
||||
|
||||
|
||||
$code
|
||||
|
||||
throw 0 < count(\$allow) ? new MethodNotAllowedException(array_unique(\$allow)) : new ResourceNotFoundException();
|
||||
}
|
||||
EOF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates PHP code to match a RouteCollection with all its routes.
|
||||
*
|
||||
* @param RouteCollection $routes A RouteCollection instance
|
||||
* @param bool $supportsRedirections Whether redirections are supported by the base class
|
||||
*
|
||||
* @return string PHP code
|
||||
*/
|
||||
private function compileRoutes(RouteCollection $routes, $supportsRedirections)
|
||||
{
|
||||
$fetchedHost = false;
|
||||
$groups = $this->groupRoutesByHostRegex($routes);
|
||||
$code = '';
|
||||
|
||||
foreach ($groups as $collection) {
|
||||
if (null !== $regex = $collection->getAttribute('host_regex')) {
|
||||
if (!$fetchedHost) {
|
||||
$code .= " \$host = \$context->getHost();\n\n";
|
||||
$fetchedHost = true;
|
||||
}
|
||||
|
||||
$code .= sprintf(" if (preg_match(%s, \$host, \$hostMatches)) {\n", var_export($regex, true));
|
||||
}
|
||||
|
||||
$tree = $this->buildStaticPrefixCollection($collection);
|
||||
$groupCode = $this->compileStaticPrefixRoutes($tree, $supportsRedirections);
|
||||
|
||||
if (null !== $regex) {
|
||||
// apply extra indention at each line (except empty ones)
|
||||
$groupCode = preg_replace('/^.{2,}$/m', ' $0', $groupCode);
|
||||
$code .= $groupCode;
|
||||
$code .= " }\n\n";
|
||||
} else {
|
||||
$code .= $groupCode;
|
||||
}
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
private function buildStaticPrefixCollection(DumperCollection $collection)
|
||||
{
|
||||
$prefixCollection = new StaticPrefixCollection();
|
||||
|
||||
foreach ($collection as $dumperRoute) {
|
||||
$prefix = $dumperRoute->getRoute()->compile()->getStaticPrefix();
|
||||
$prefixCollection->addRoute($prefix, $dumperRoute);
|
||||
}
|
||||
|
||||
$prefixCollection->optimizeGroups();
|
||||
|
||||
return $prefixCollection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates PHP code to match a tree of routes.
|
||||
*
|
||||
* @param StaticPrefixCollection $collection A StaticPrefixCollection instance
|
||||
* @param bool $supportsRedirections Whether redirections are supported by the base class
|
||||
* @param string $ifOrElseIf Either "if" or "elseif" to influence chaining.
|
||||
*
|
||||
* @return string PHP code
|
||||
*/
|
||||
private function compileStaticPrefixRoutes(StaticPrefixCollection $collection, $supportsRedirections, $ifOrElseIf = 'if')
|
||||
{
|
||||
$code = '';
|
||||
$prefix = $collection->getPrefix();
|
||||
|
||||
if (!empty($prefix) && '/' !== $prefix) {
|
||||
$code .= sprintf(" %s (0 === strpos(\$pathinfo, %s)) {\n", $ifOrElseIf, var_export($prefix, true));
|
||||
}
|
||||
|
||||
$ifOrElseIf = 'if';
|
||||
|
||||
foreach ($collection->getItems() as $route) {
|
||||
if ($route instanceof StaticPrefixCollection) {
|
||||
$code .= $this->compileStaticPrefixRoutes($route, $supportsRedirections, $ifOrElseIf);
|
||||
$ifOrElseIf = 'elseif';
|
||||
} else {
|
||||
$code .= $this->compileRoute($route[1]->getRoute(), $route[1]->getName(), $supportsRedirections, $prefix)."\n";
|
||||
$ifOrElseIf = 'if';
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($prefix) && '/' !== $prefix) {
|
||||
$code .= " }\n\n";
|
||||
// apply extra indention at each line (except empty ones)
|
||||
$code = preg_replace('/^.{2,}$/m', ' $0', $code);
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a single Route to PHP code used to match it against the path info.
|
||||
*
|
||||
* @param Route $route A Route instance
|
||||
* @param string $name The name of the Route
|
||||
* @param bool $supportsRedirections Whether redirections are supported by the base class
|
||||
* @param string|null $parentPrefix The prefix of the parent collection used to optimize the code
|
||||
*
|
||||
* @return string PHP code
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
private function compileRoute(Route $route, $name, $supportsRedirections, $parentPrefix = null)
|
||||
{
|
||||
$code = '';
|
||||
$compiledRoute = $route->compile();
|
||||
$conditions = array();
|
||||
$hasTrailingSlash = false;
|
||||
$matches = false;
|
||||
$hostMatches = false;
|
||||
$methods = $route->getMethods();
|
||||
|
||||
$supportsTrailingSlash = $supportsRedirections && (!$methods || in_array('HEAD', $methods) || in_array('GET', $methods));
|
||||
$regex = $compiledRoute->getRegex();
|
||||
|
||||
if (!count($compiledRoute->getPathVariables()) && false !== preg_match('#^(.)\^(?P<url>.*?)\$\1#'.(substr($regex, -1) === 'u' ? 'u' : ''), $regex, $m)) {
|
||||
if ($supportsTrailingSlash && substr($m['url'], -1) === '/') {
|
||||
$conditions[] = sprintf('%s === $trimmedPathinfo', var_export(rtrim(str_replace('\\', '', $m['url']), '/'), true));
|
||||
$hasTrailingSlash = true;
|
||||
} else {
|
||||
$conditions[] = sprintf('%s === $pathinfo', var_export(str_replace('\\', '', $m['url']), true));
|
||||
}
|
||||
} else {
|
||||
if ($compiledRoute->getStaticPrefix() && $compiledRoute->getStaticPrefix() !== $parentPrefix) {
|
||||
$conditions[] = sprintf('0 === strpos($pathinfo, %s)', var_export($compiledRoute->getStaticPrefix(), true));
|
||||
}
|
||||
|
||||
if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) {
|
||||
$regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2);
|
||||
$hasTrailingSlash = true;
|
||||
}
|
||||
$conditions[] = sprintf('preg_match(%s, $pathinfo, $matches)', var_export($regex, true));
|
||||
|
||||
$matches = true;
|
||||
}
|
||||
|
||||
if ($compiledRoute->getHostVariables()) {
|
||||
$hostMatches = true;
|
||||
}
|
||||
|
||||
if ($route->getCondition()) {
|
||||
$conditions[] = $this->getExpressionLanguage()->compile($route->getCondition(), array('context', 'request'));
|
||||
}
|
||||
|
||||
$conditions = implode(' && ', $conditions);
|
||||
|
||||
$code .= <<<EOF
|
||||
// $name
|
||||
if ($conditions) {
|
||||
|
||||
EOF;
|
||||
|
||||
$gotoname = 'not_'.preg_replace('/[^A-Za-z0-9_]/', '', $name);
|
||||
|
||||
if ($methods) {
|
||||
if (1 === count($methods)) {
|
||||
if ($methods[0] === 'HEAD') {
|
||||
$code .= <<<EOF
|
||||
if ('HEAD' !== \$requestMethod) {
|
||||
\$allow[] = 'HEAD';
|
||||
goto $gotoname;
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
} else {
|
||||
$code .= <<<EOF
|
||||
if ('$methods[0]' !== \$canonicalMethod) {
|
||||
\$allow[] = '$methods[0]';
|
||||
goto $gotoname;
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
}
|
||||
} else {
|
||||
$methodVariable = 'requestMethod';
|
||||
|
||||
if (in_array('GET', $methods)) {
|
||||
// Since we treat HEAD requests like GET requests we don't need to match it.
|
||||
$methodVariable = 'canonicalMethod';
|
||||
$methods = array_filter($methods, function ($method) { return 'HEAD' !== $method; });
|
||||
}
|
||||
|
||||
if (1 === count($methods)) {
|
||||
$code .= <<<EOF
|
||||
if ('$methods[0]' !== \$$methodVariable) {
|
||||
\$allow[] = '$methods[0]';
|
||||
goto $gotoname;
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
} else {
|
||||
$methods = implode("', '", $methods);
|
||||
$code .= <<<EOF
|
||||
if (!in_array(\$$methodVariable, array('$methods'))) {
|
||||
\$allow = array_merge(\$allow, array('$methods'));
|
||||
goto $gotoname;
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasTrailingSlash) {
|
||||
$code .= <<<EOF
|
||||
if (substr(\$pathinfo, -1) !== '/') {
|
||||
return \$this->redirect(\$pathinfo.'/', '$name');
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
if ($schemes = $route->getSchemes()) {
|
||||
if (!$supportsRedirections) {
|
||||
throw new \LogicException('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.');
|
||||
}
|
||||
$schemes = str_replace("\n", '', var_export(array_flip($schemes), true));
|
||||
$code .= <<<EOF
|
||||
\$requiredSchemes = $schemes;
|
||||
if (!isset(\$requiredSchemes[\$scheme])) {
|
||||
return \$this->redirect(\$pathinfo, '$name', key(\$requiredSchemes));
|
||||
}
|
||||
|
||||
|
||||
EOF;
|
||||
}
|
||||
|
||||
// optimize parameters array
|
||||
if ($matches || $hostMatches) {
|
||||
$vars = array();
|
||||
if ($hostMatches) {
|
||||
$vars[] = '$hostMatches';
|
||||
}
|
||||
if ($matches) {
|
||||
$vars[] = '$matches';
|
||||
}
|
||||
$vars[] = "array('_route' => '$name')";
|
||||
|
||||
$code .= sprintf(
|
||||
" return \$this->mergeDefaults(array_replace(%s), %s);\n",
|
||||
implode(', ', $vars),
|
||||
str_replace("\n", '', var_export($route->getDefaults(), true))
|
||||
);
|
||||
} elseif ($route->getDefaults()) {
|
||||
$code .= sprintf(" return %s;\n", str_replace("\n", '', var_export(array_replace($route->getDefaults(), array('_route' => $name)), true)));
|
||||
} else {
|
||||
$code .= sprintf(" return array('_route' => '%s');\n", $name);
|
||||
}
|
||||
$code .= " }\n";
|
||||
|
||||
if ($methods) {
|
||||
$code .= " $gotoname:\n";
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups consecutive routes having the same host regex.
|
||||
*
|
||||
* The result is a collection of collections of routes having the same host regex.
|
||||
*
|
||||
* @param RouteCollection $routes A flat RouteCollection
|
||||
*
|
||||
* @return DumperCollection A collection with routes grouped by host regex in sub-collections
|
||||
*/
|
||||
private function groupRoutesByHostRegex(RouteCollection $routes)
|
||||
{
|
||||
$groups = new DumperCollection();
|
||||
$currentGroup = new DumperCollection();
|
||||
$currentGroup->setAttribute('host_regex', null);
|
||||
$groups->add($currentGroup);
|
||||
|
||||
foreach ($routes as $name => $route) {
|
||||
$hostRegex = $route->compile()->getHostRegex();
|
||||
if ($currentGroup->getAttribute('host_regex') !== $hostRegex) {
|
||||
$currentGroup = new DumperCollection();
|
||||
$currentGroup->setAttribute('host_regex', $hostRegex);
|
||||
$groups->add($currentGroup);
|
||||
}
|
||||
$currentGroup->add(new DumperRoute($name, $route));
|
||||
}
|
||||
|
||||
return $groups;
|
||||
}
|
||||
|
||||
private function getExpressionLanguage()
|
||||
{
|
||||
if (null === $this->expressionLanguage) {
|
||||
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
|
||||
throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
|
||||
}
|
||||
$this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
|
||||
}
|
||||
|
||||
return $this->expressionLanguage;
|
||||
}
|
||||
}
|
||||
@@ -11,228 +11,193 @@
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher\Dumper;
|
||||
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
|
||||
/**
|
||||
* Prefix tree of routes preserving routes order.
|
||||
*
|
||||
* @author Frank de Jonge <info@frankdejonge.nl>
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class StaticPrefixCollection
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $prefix;
|
||||
private string $prefix;
|
||||
|
||||
/**
|
||||
* @var array[]|StaticPrefixCollection[]
|
||||
* @var string[]
|
||||
*/
|
||||
private $items = array();
|
||||
private array $staticPrefixes = [];
|
||||
|
||||
/**
|
||||
* @var int
|
||||
* @var string[]
|
||||
*/
|
||||
private $matchStart = 0;
|
||||
private array $prefixes = [];
|
||||
|
||||
public function __construct($prefix = '')
|
||||
/**
|
||||
* @var array[]|self[]
|
||||
*/
|
||||
private array $items = [];
|
||||
|
||||
public function __construct(string $prefix = '/')
|
||||
{
|
||||
$this->prefix = $prefix;
|
||||
}
|
||||
|
||||
public function getPrefix()
|
||||
public function getPrefix(): string
|
||||
{
|
||||
return $this->prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed[]|StaticPrefixCollection[]
|
||||
* @return array[]|self[]
|
||||
*/
|
||||
public function getItems()
|
||||
public function getRoutes(): array
|
||||
{
|
||||
return $this->items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a route to a group.
|
||||
*
|
||||
* @param string $prefix
|
||||
* @param mixed $route
|
||||
*/
|
||||
public function addRoute($prefix, $route)
|
||||
public function addRoute(string $prefix, array|StaticPrefixCollection $route)
|
||||
{
|
||||
$prefix = '/' === $prefix ? $prefix : rtrim($prefix, '/');
|
||||
$this->guardAgainstAddingNotAcceptedRoutes($prefix);
|
||||
[$prefix, $staticPrefix] = $this->getCommonPrefix($prefix, $prefix);
|
||||
|
||||
if ($this->prefix === $prefix) {
|
||||
// When a prefix is exactly the same as the base we move up the match start position.
|
||||
// This is needed because otherwise routes that come afterwards have higher precedence
|
||||
// than a possible regular expression, which goes against the input order sorting.
|
||||
$this->items[] = array($prefix, $route);
|
||||
$this->matchStart = count($this->items);
|
||||
for ($i = \count($this->items) - 1; 0 <= $i; --$i) {
|
||||
$item = $this->items[$i];
|
||||
|
||||
return;
|
||||
}
|
||||
[$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
|
||||
|
||||
if ($this->prefix !== $staticPrefix && $this->prefix !== $this->staticPrefixes[$i]) {
|
||||
// the new route and the previous one have exclusive static prefixes
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->prefix === $staticPrefix && $this->prefix === $this->staticPrefixes[$i]) {
|
||||
// the new route and the previous one have no static prefix
|
||||
break;
|
||||
}
|
||||
|
||||
if ($this->prefixes[$i] !== $this->staticPrefixes[$i] && $this->prefix === $this->staticPrefixes[$i]) {
|
||||
// the previous route is non-static and has no static prefix
|
||||
break;
|
||||
}
|
||||
|
||||
if ($prefix !== $staticPrefix && $this->prefix === $staticPrefix) {
|
||||
// the new route is non-static and has no static prefix
|
||||
break;
|
||||
}
|
||||
|
||||
foreach ($this->items as $i => $item) {
|
||||
if ($i < $this->matchStart) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($item instanceof self && $item->accepts($prefix)) {
|
||||
if ($item instanceof self && $this->prefixes[$i] === $commonPrefix) {
|
||||
// the new route is a child of a previous one, let's nest it
|
||||
$item->addRoute($prefix, $route);
|
||||
} else {
|
||||
// the new route and a previous one have a common prefix, let's merge them
|
||||
$child = new self($commonPrefix);
|
||||
[$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];
|
||||
|
||||
return;
|
||||
$this->staticPrefixes[$i] = $commonStaticPrefix;
|
||||
$this->prefixes[$i] = $commonPrefix;
|
||||
$this->items[$i] = $child;
|
||||
}
|
||||
|
||||
$group = $this->groupWithItem($item, $prefix, $route);
|
||||
|
||||
if ($group instanceof self) {
|
||||
$this->items[$i] = $group;
|
||||
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// No optimised case was found, in this case we simple add the route for possible
|
||||
// grouping when new routes are added.
|
||||
$this->items[] = array($prefix, $route);
|
||||
$this->staticPrefixes[] = $staticPrefix;
|
||||
$this->prefixes[] = $prefix;
|
||||
$this->items[] = $route;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to combine a route with another route or group.
|
||||
*
|
||||
* @param StaticPrefixCollection|array $item
|
||||
* @param string $prefix
|
||||
* @param mixed $route
|
||||
*
|
||||
* @return null|StaticPrefixCollection
|
||||
* Linearizes back a set of nested routes into a collection.
|
||||
*/
|
||||
private function groupWithItem($item, $prefix, $route)
|
||||
public function populateCollection(RouteCollection $routes): RouteCollection
|
||||
{
|
||||
$itemPrefix = $item instanceof self ? $item->prefix : $item[0];
|
||||
$commonPrefix = $this->detectCommonPrefix($prefix, $itemPrefix);
|
||||
|
||||
if (!$commonPrefix) {
|
||||
return;
|
||||
}
|
||||
|
||||
$child = new self($commonPrefix);
|
||||
|
||||
if ($item instanceof self) {
|
||||
$child->items = array($item);
|
||||
} else {
|
||||
$child->addRoute($item[0], $item[1]);
|
||||
}
|
||||
|
||||
$child->addRoute($prefix, $route);
|
||||
|
||||
return $child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a prefix can be contained within the group.
|
||||
*
|
||||
* @param string $prefix
|
||||
*
|
||||
* @return bool Whether a prefix could belong in a given group
|
||||
*/
|
||||
private function accepts($prefix)
|
||||
{
|
||||
return '' === $this->prefix || strpos($prefix, $this->prefix) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects whether there's a common prefix relative to the group prefix and returns it.
|
||||
*
|
||||
* @param string $prefix
|
||||
* @param string $anotherPrefix
|
||||
*
|
||||
* @return false|string A common prefix, longer than the base/group prefix, or false when none available
|
||||
*/
|
||||
private function detectCommonPrefix($prefix, $anotherPrefix)
|
||||
{
|
||||
$baseLength = strlen($this->prefix);
|
||||
$commonLength = $baseLength;
|
||||
$end = min(strlen($prefix), strlen($anotherPrefix));
|
||||
|
||||
for ($i = $baseLength; $i <= $end; ++$i) {
|
||||
if (substr($prefix, 0, $i) !== substr($anotherPrefix, 0, $i)) {
|
||||
break;
|
||||
foreach ($this->items as $route) {
|
||||
if ($route instanceof self) {
|
||||
$route->populateCollection($routes);
|
||||
} else {
|
||||
$routes->add(...$route);
|
||||
}
|
||||
|
||||
$commonLength = $i;
|
||||
}
|
||||
|
||||
$commonPrefix = rtrim(substr($prefix, 0, $commonLength), '/');
|
||||
|
||||
if (strlen($commonPrefix) > $baseLength) {
|
||||
return $commonPrefix;
|
||||
}
|
||||
|
||||
return false;
|
||||
return $routes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes the tree by inlining items from groups with less than 3 items.
|
||||
* Gets the full and static common prefixes between two route patterns.
|
||||
*
|
||||
* The static prefix stops at last at the first opening bracket.
|
||||
*/
|
||||
public function optimizeGroups()
|
||||
private function getCommonPrefix(string $prefix, string $anotherPrefix): array
|
||||
{
|
||||
$index = -1;
|
||||
$baseLength = \strlen($this->prefix);
|
||||
$end = min(\strlen($prefix), \strlen($anotherPrefix));
|
||||
$staticLength = null;
|
||||
set_error_handler([__CLASS__, 'handleError']);
|
||||
|
||||
while (isset($this->items[++$index])) {
|
||||
$item = $this->items[$index];
|
||||
|
||||
if ($item instanceof self) {
|
||||
$item->optimizeGroups();
|
||||
|
||||
// When a group contains only two items there's no reason to optimize because at minimum
|
||||
// the amount of prefix check is 2. In this case inline the group.
|
||||
if ($item->shouldBeInlined()) {
|
||||
array_splice($this->items, $index, 1, $item->items);
|
||||
|
||||
// Lower index to pass through the same index again after optimizing.
|
||||
// The first item of the replacements might be a group needing optimization.
|
||||
--$index;
|
||||
try {
|
||||
for ($i = $baseLength; $i < $end && $prefix[$i] === $anotherPrefix[$i]; ++$i) {
|
||||
if ('(' === $prefix[$i]) {
|
||||
$staticLength = $staticLength ?? $i;
|
||||
for ($j = 1 + $i, $n = 1; $j < $end && 0 < $n; ++$j) {
|
||||
if ($prefix[$j] !== $anotherPrefix[$j]) {
|
||||
break 2;
|
||||
}
|
||||
if ('(' === $prefix[$j]) {
|
||||
++$n;
|
||||
} elseif (')' === $prefix[$j]) {
|
||||
--$n;
|
||||
} elseif ('\\' === $prefix[$j] && (++$j === $end || $prefix[$j] !== $anotherPrefix[$j])) {
|
||||
--$j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (0 < $n) {
|
||||
break;
|
||||
}
|
||||
if (('?' === ($prefix[$j] ?? '') || '?' === ($anotherPrefix[$j] ?? '')) && ($prefix[$j] ?? '') !== ($anotherPrefix[$j] ?? '')) {
|
||||
break;
|
||||
}
|
||||
$subPattern = substr($prefix, $i, $j - $i);
|
||||
if ($prefix !== $anotherPrefix && !preg_match('/^\(\[[^\]]++\]\+\+\)$/', $subPattern) && !preg_match('{(?<!'.$subPattern.')}', '')) {
|
||||
// sub-patterns of variable length are not considered as common prefixes because their greediness would break in-order matching
|
||||
break;
|
||||
}
|
||||
$i = $j - 1;
|
||||
} elseif ('\\' === $prefix[$i] && (++$i === $end || $prefix[$i] !== $anotherPrefix[$i])) {
|
||||
--$i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
if ($i < $end && 0b10 === (\ord($prefix[$i]) >> 6) && preg_match('//u', $prefix.' '.$anotherPrefix)) {
|
||||
do {
|
||||
// Prevent cutting in the middle of an UTF-8 characters
|
||||
--$i;
|
||||
} while (0b10 === (\ord($prefix[$i]) >> 6));
|
||||
}
|
||||
|
||||
return [substr($prefix, 0, $i), substr($prefix, 0, $staticLength ?? $i)];
|
||||
}
|
||||
|
||||
private function shouldBeInlined()
|
||||
public static function handleError(int $type, string $msg)
|
||||
{
|
||||
if (count($this->items) >= 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
if ($item instanceof self) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->items as $item) {
|
||||
if (is_array($item) && $item[0] === $this->prefix) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guards against adding incompatible prefixes in a group.
|
||||
*
|
||||
* @param string $prefix
|
||||
*
|
||||
* @throws \LogicException When a prefix does not belong in a group.
|
||||
*/
|
||||
private function guardAgainstAddingNotAcceptedRoutes($prefix)
|
||||
{
|
||||
if (!$this->accepts($prefix)) {
|
||||
$message = sprintf('Could not add route with prefix %s to collection with prefix %s', $prefix, $this->prefix);
|
||||
|
||||
throw new \LogicException($message);
|
||||
}
|
||||
return str_contains($msg, 'Compilation failed: lookbehind assertion is not fixed length');
|
||||
}
|
||||
}
|
||||
|
||||
58
vendor/symfony/routing/Matcher/ExpressionLanguageProvider.php
vendored
Normal file
58
vendor/symfony/routing/Matcher/ExpressionLanguageProvider.php
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
<?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;
|
||||
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
use Symfony\Contracts\Service\ServiceProviderInterface;
|
||||
|
||||
/**
|
||||
* Exposes functions defined in the request context to route conditions.
|
||||
*
|
||||
* @author Ahmed TAILOULOUTE <ahmed.tailouloute@gmail.com>
|
||||
*/
|
||||
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
|
||||
{
|
||||
private $functions;
|
||||
|
||||
public function __construct(ServiceProviderInterface $functions)
|
||||
{
|
||||
$this->functions = $functions;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFunctions(): array
|
||||
{
|
||||
$functions = [];
|
||||
|
||||
foreach ($this->functions->getProvidedServices() as $function => $type) {
|
||||
$functions[] = new ExpressionFunction(
|
||||
$function,
|
||||
static function (...$args) use ($function) {
|
||||
return sprintf('($context->getParameter(\'_functions\')->get(%s)(%s))', var_export($function, true), implode(', ', $args));
|
||||
},
|
||||
function ($values, ...$args) use ($function) {
|
||||
return $values['context']->getParameter('_functions')->get($function)(...$args);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return $functions;
|
||||
}
|
||||
|
||||
public function get(string $function): callable
|
||||
{
|
||||
return $this->functions->get($function);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher;
|
||||
|
||||
use Symfony\Component\Routing\Exception\ExceptionInterface;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\Route;
|
||||
|
||||
/**
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
@@ -22,44 +22,43 @@ abstract class RedirectableUrlMatcher extends UrlMatcher implements Redirectable
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function match($pathinfo)
|
||||
public function match(string $pathinfo): array
|
||||
{
|
||||
try {
|
||||
$parameters = parent::match($pathinfo);
|
||||
return parent::match($pathinfo);
|
||||
} catch (ResourceNotFoundException $e) {
|
||||
if ('/' === substr($pathinfo, -1) || !in_array($this->context->getMethod(), array('HEAD', 'GET'))) {
|
||||
if (!\in_array($this->context->getMethod(), ['HEAD', 'GET'], true)) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
try {
|
||||
parent::match($pathinfo.'/');
|
||||
if ($this->allowSchemes) {
|
||||
redirect_scheme:
|
||||
$scheme = $this->context->getScheme();
|
||||
$this->context->setScheme(current($this->allowSchemes));
|
||||
try {
|
||||
$ret = parent::match($pathinfo);
|
||||
|
||||
return $this->redirect($pathinfo.'/', null);
|
||||
} catch (ResourceNotFoundException $e2) {
|
||||
return $this->redirect($pathinfo, $ret['_route'] ?? null, $this->context->getScheme()) + $ret;
|
||||
} catch (ExceptionInterface $e2) {
|
||||
throw $e;
|
||||
} finally {
|
||||
$this->context->setScheme($scheme);
|
||||
}
|
||||
} elseif ('/' === $trimmedPathinfo = rtrim($pathinfo, '/') ?: '/') {
|
||||
throw $e;
|
||||
} else {
|
||||
try {
|
||||
$pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo;
|
||||
$ret = parent::match($pathinfo);
|
||||
|
||||
return $this->redirect($pathinfo, $ret['_route'] ?? null) + $ret;
|
||||
} catch (ExceptionInterface $e2) {
|
||||
if ($this->allowSchemes) {
|
||||
goto redirect_scheme;
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function handleRouteRequirements($pathinfo, $name, Route $route)
|
||||
{
|
||||
// expression condition
|
||||
if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
|
||||
return array(self::REQUIREMENT_MISMATCH, null);
|
||||
}
|
||||
|
||||
// check HTTP scheme requirement
|
||||
$scheme = $this->context->getScheme();
|
||||
$schemes = $route->getSchemes();
|
||||
if ($schemes && !$route->hasScheme($scheme)) {
|
||||
return array(self::ROUTE_MATCH, $this->redirect($pathinfo, $name, current($schemes)));
|
||||
}
|
||||
|
||||
return array(self::REQUIREMENT_MATCH, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,13 +19,11 @@ namespace Symfony\Component\Routing\Matcher;
|
||||
interface RedirectableUrlMatcherInterface
|
||||
{
|
||||
/**
|
||||
* Redirects the user to another URL.
|
||||
* Redirects the user to another URL and returns the parameters for the redirection.
|
||||
*
|
||||
* @param string $path The path info to redirect to
|
||||
* @param string $route The route name that matched
|
||||
* @param string|null $scheme The URL scheme (null to keep the current one)
|
||||
*
|
||||
* @return array An array of parameters
|
||||
*/
|
||||
public function redirect($path, $route, $scheme = null);
|
||||
public function redirect(string $path, string $route, string $scheme = null): array;
|
||||
}
|
||||
|
||||
@@ -12,8 +12,9 @@
|
||||
namespace Symfony\Component\Routing\Matcher;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
|
||||
use Symfony\Component\Routing\Exception\NoConfigurationException;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
|
||||
/**
|
||||
* RequestMatcherInterface is the interface that all request matcher classes must implement.
|
||||
@@ -25,15 +26,12 @@ interface RequestMatcherInterface
|
||||
/**
|
||||
* Tries to match a request with a set of routes.
|
||||
*
|
||||
* If the matcher can not find information, it must throw one of the exceptions documented
|
||||
* If the matcher cannot find information, it must throw one of the exceptions documented
|
||||
* below.
|
||||
*
|
||||
* @param Request $request The request to match
|
||||
*
|
||||
* @return array An array of parameters
|
||||
*
|
||||
* @throws NoConfigurationException If no routing configuration could be found
|
||||
* @throws ResourceNotFoundException If no matching resource could be found
|
||||
* @throws MethodNotAllowedException If a matching resource was found but the request method is not allowed
|
||||
*/
|
||||
public function matchRequest(Request $request);
|
||||
public function matchRequest(Request $request): array;
|
||||
}
|
||||
|
||||
@@ -23,15 +23,15 @@ use Symfony\Component\Routing\RouteCollection;
|
||||
*/
|
||||
class TraceableUrlMatcher extends UrlMatcher
|
||||
{
|
||||
const ROUTE_DOES_NOT_MATCH = 0;
|
||||
const ROUTE_ALMOST_MATCHES = 1;
|
||||
const ROUTE_MATCHES = 2;
|
||||
public const ROUTE_DOES_NOT_MATCH = 0;
|
||||
public const ROUTE_ALMOST_MATCHES = 1;
|
||||
public const ROUTE_MATCHES = 2;
|
||||
|
||||
protected $traces;
|
||||
|
||||
public function getTraces($pathinfo)
|
||||
public function getTraces(string $pathinfo)
|
||||
{
|
||||
$this->traces = array();
|
||||
$this->traces = [];
|
||||
|
||||
try {
|
||||
$this->match($pathinfo);
|
||||
@@ -50,14 +50,34 @@ class TraceableUrlMatcher extends UrlMatcher
|
||||
return $traces;
|
||||
}
|
||||
|
||||
protected function matchCollection($pathinfo, RouteCollection $routes)
|
||||
protected function matchCollection(string $pathinfo, RouteCollection $routes): array
|
||||
{
|
||||
// HEAD and GET are equivalent as per RFC
|
||||
if ('HEAD' === $method = $this->context->getMethod()) {
|
||||
$method = 'GET';
|
||||
}
|
||||
$supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
|
||||
$trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
|
||||
|
||||
foreach ($routes as $name => $route) {
|
||||
$compiledRoute = $route->compile();
|
||||
$staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
|
||||
$requiredMethods = $route->getMethods();
|
||||
|
||||
if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
|
||||
// check the static prefix of the URL first. Only use the more expensive preg_match when it matches
|
||||
if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
|
||||
$this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route);
|
||||
continue;
|
||||
}
|
||||
$regex = $compiledRoute->getRegex();
|
||||
|
||||
$pos = strrpos($regex, '$');
|
||||
$hasTrailingSlash = '/' === $regex[$pos - 1];
|
||||
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
|
||||
|
||||
if (!preg_match($regex, $pathinfo, $matches)) {
|
||||
// does it match without any requirements?
|
||||
$r = new Route($route->getPath(), $route->getDefaults(), array(), $route->getOptions());
|
||||
$r = new Route($route->getPath(), $route->getDefaults(), [], $route->getOptions());
|
||||
$cr = $r->compile();
|
||||
if (!preg_match($cr->getRegex(), $pathinfo)) {
|
||||
$this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route);
|
||||
@@ -66,10 +86,10 @@ class TraceableUrlMatcher extends UrlMatcher
|
||||
}
|
||||
|
||||
foreach ($route->getRequirements() as $n => $regex) {
|
||||
$r = new Route($route->getPath(), $route->getDefaults(), array($n => $regex), $route->getOptions());
|
||||
$r = new Route($route->getPath(), $route->getDefaults(), [$n => $regex], $route->getOptions());
|
||||
$cr = $r->compile();
|
||||
|
||||
if (in_array($n, $cr->getVariables()) && !preg_match($cr->getRegex(), $pathinfo)) {
|
||||
if (\in_array($n, $cr->getVariables()) && !preg_match($cr->getRegex(), $pathinfo)) {
|
||||
$this->addTrace(sprintf('Requirement for "%s" does not match (%s)', $n, $regex), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
|
||||
continue 2;
|
||||
@@ -79,63 +99,66 @@ class TraceableUrlMatcher extends UrlMatcher
|
||||
continue;
|
||||
}
|
||||
|
||||
// check host requirement
|
||||
$hostMatches = array();
|
||||
$hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath());
|
||||
|
||||
if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
|
||||
if ($hasTrailingSlash) {
|
||||
$matches = $m;
|
||||
} else {
|
||||
$hasTrailingVar = false;
|
||||
}
|
||||
}
|
||||
|
||||
$hostMatches = [];
|
||||
if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
|
||||
$this->addTrace(sprintf('Host "%s" does not match the requirement ("%s")', $this->context->getHost(), $route->getHost()), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// check HTTP method requirement
|
||||
if ($requiredMethods = $route->getMethods()) {
|
||||
// HEAD and GET are equivalent as per RFC
|
||||
if ('HEAD' === $method = $this->context->getMethod()) {
|
||||
$method = 'GET';
|
||||
}
|
||||
$status = $this->handleRouteRequirements($pathinfo, $name, $route);
|
||||
|
||||
if (!in_array($method, $requiredMethods)) {
|
||||
$this->allow = array_merge($this->allow, $requiredMethods);
|
||||
|
||||
$this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
|
||||
continue;
|
||||
}
|
||||
if (self::REQUIREMENT_MISMATCH === $status[0]) {
|
||||
$this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $route->getCondition()), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
continue;
|
||||
}
|
||||
|
||||
// check condition
|
||||
if ($condition = $route->getCondition()) {
|
||||
if (!$this->getExpressionLanguage()->evaluate($condition, array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
|
||||
$this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $condition), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
|
||||
if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
|
||||
$this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route);
|
||||
|
||||
continue;
|
||||
return $this->allow = $this->allowSchemes = [];
|
||||
}
|
||||
$this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route);
|
||||
continue;
|
||||
}
|
||||
|
||||
// check HTTP scheme requirement
|
||||
if ($requiredSchemes = $route->getSchemes()) {
|
||||
$scheme = $this->context->getScheme();
|
||||
if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
|
||||
$this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
|
||||
$this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s)', $this->context->getScheme(), implode(', ', $route->getSchemes())), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$route->hasScheme($scheme)) {
|
||||
$this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s); the user will be redirected to first required scheme', $scheme, implode(', ', $requiredSchemes)), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
|
||||
return true;
|
||||
}
|
||||
if ($requiredMethods && !\in_array($method, $requiredMethods)) {
|
||||
$this->allow = array_merge($this->allow, $requiredMethods);
|
||||
$this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route);
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route);
|
||||
|
||||
return true;
|
||||
return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? []));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private function addTrace($log, $level = self::ROUTE_DOES_NOT_MATCH, $name = null, $route = null)
|
||||
private function addTrace(string $log, int $level = self::ROUTE_DOES_NOT_MATCH, string $name = null, Route $route = null)
|
||||
{
|
||||
$this->traces[] = array(
|
||||
$this->traces[] = [
|
||||
'log' => $log,
|
||||
'name' => $name,
|
||||
'level' => $level,
|
||||
'path' => null !== $route ? $route->getPath() : null,
|
||||
);
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
187
vendor/symfony/routing/Matcher/UrlMatcher.php
vendored
187
vendor/symfony/routing/Matcher/UrlMatcher.php
vendored
@@ -11,14 +11,15 @@
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher;
|
||||
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
|
||||
use Symfony\Component\Routing\Exception\NoConfigurationException;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
use Symfony\Component\Routing\RequestContext;
|
||||
use Symfony\Component\Routing\Route;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
|
||||
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
|
||||
/**
|
||||
* UrlMatcher matches URL based on a set of routes.
|
||||
@@ -27,39 +28,34 @@ use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
|
||||
*/
|
||||
class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
{
|
||||
const REQUIREMENT_MATCH = 0;
|
||||
const REQUIREMENT_MISMATCH = 1;
|
||||
const ROUTE_MATCH = 2;
|
||||
public const REQUIREMENT_MATCH = 0;
|
||||
public const REQUIREMENT_MISMATCH = 1;
|
||||
public const ROUTE_MATCH = 2;
|
||||
|
||||
/**
|
||||
* @var RequestContext
|
||||
*/
|
||||
/** @var RequestContext */
|
||||
protected $context;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
* Collects HTTP methods that would be allowed for the request.
|
||||
*/
|
||||
protected $allow = array();
|
||||
protected $allow = [];
|
||||
|
||||
/**
|
||||
* @var RouteCollection
|
||||
* Collects URI schemes that would be allowed for the request.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
protected $routes;
|
||||
protected array $allowSchemes = [];
|
||||
|
||||
protected $routes;
|
||||
protected $request;
|
||||
protected $expressionLanguage;
|
||||
|
||||
/**
|
||||
* @var ExpressionFunctionProviderInterface[]
|
||||
*/
|
||||
protected $expressionLanguageProviders = array();
|
||||
protected $expressionLanguageProviders = [];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param RouteCollection $routes A RouteCollection instance
|
||||
* @param RequestContext $context The context
|
||||
*/
|
||||
public function __construct(RouteCollection $routes, RequestContext $context)
|
||||
{
|
||||
$this->routes = $routes;
|
||||
@@ -77,7 +73,7 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getContext()
|
||||
public function getContext(): RequestContext
|
||||
{
|
||||
return $this->context;
|
||||
}
|
||||
@@ -85,23 +81,25 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function match($pathinfo)
|
||||
public function match(string $pathinfo): array
|
||||
{
|
||||
$this->allow = array();
|
||||
$this->allow = $this->allowSchemes = [];
|
||||
|
||||
if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
|
||||
if ($ret = $this->matchCollection(rawurldecode($pathinfo) ?: '/', $this->routes)) {
|
||||
return $ret;
|
||||
}
|
||||
|
||||
throw 0 < count($this->allow)
|
||||
? new MethodNotAllowedException(array_unique($this->allow))
|
||||
: new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
if ('/' === $pathinfo && !$this->allow && !$this->allowSchemes) {
|
||||
throw new NoConfigurationException();
|
||||
}
|
||||
|
||||
throw 0 < \count($this->allow) ? new MethodNotAllowedException(array_unique($this->allow)) : new ResourceNotFoundException(sprintf('No routes found for "%s".', $pathinfo));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function matchRequest(Request $request)
|
||||
public function matchRequest(Request $request): array
|
||||
{
|
||||
$this->request = $request;
|
||||
|
||||
@@ -120,59 +118,82 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
/**
|
||||
* Tries to match a URL with a set of routes.
|
||||
*
|
||||
* @param string $pathinfo The path info to be parsed
|
||||
* @param RouteCollection $routes The set of routes
|
||||
*
|
||||
* @return array An array of parameters
|
||||
* @param string $pathinfo The path info to be parsed
|
||||
*
|
||||
* @throws NoConfigurationException If no routing configuration could be found
|
||||
* @throws ResourceNotFoundException If the resource could not be found
|
||||
* @throws MethodNotAllowedException If the resource was found but the request method is not allowed
|
||||
*/
|
||||
protected function matchCollection($pathinfo, RouteCollection $routes)
|
||||
protected function matchCollection(string $pathinfo, RouteCollection $routes): array
|
||||
{
|
||||
// HEAD and GET are equivalent as per RFC
|
||||
if ('HEAD' === $method = $this->context->getMethod()) {
|
||||
$method = 'GET';
|
||||
}
|
||||
$supportsTrailingSlash = 'GET' === $method && $this instanceof RedirectableUrlMatcherInterface;
|
||||
$trimmedPathinfo = rtrim($pathinfo, '/') ?: '/';
|
||||
|
||||
foreach ($routes as $name => $route) {
|
||||
$compiledRoute = $route->compile();
|
||||
$staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
|
||||
$requiredMethods = $route->getMethods();
|
||||
|
||||
// check the static prefix of the URL first. Only use the more expensive preg_match when it matches
|
||||
if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
|
||||
if ('' !== $staticPrefix && !str_starts_with($trimmedPathinfo, $staticPrefix)) {
|
||||
continue;
|
||||
}
|
||||
$regex = $compiledRoute->getRegex();
|
||||
|
||||
$pos = strrpos($regex, '$');
|
||||
$hasTrailingSlash = '/' === $regex[$pos - 1];
|
||||
$regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
|
||||
|
||||
if (!preg_match($regex, $pathinfo, $matches)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
|
||||
continue;
|
||||
$hasTrailingVar = $trimmedPathinfo !== $pathinfo && preg_match('#\{\w+\}/?$#', $route->getPath());
|
||||
|
||||
if ($hasTrailingVar && ($hasTrailingSlash || (null === $m = $matches[\count($compiledRoute->getPathVariables())] ?? null) || '/' !== ($m[-1] ?? '/')) && preg_match($regex, $trimmedPathinfo, $m)) {
|
||||
if ($hasTrailingSlash) {
|
||||
$matches = $m;
|
||||
} else {
|
||||
$hasTrailingVar = false;
|
||||
}
|
||||
}
|
||||
|
||||
$hostMatches = array();
|
||||
$hostMatches = [];
|
||||
if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// check HTTP method requirement
|
||||
if ($requiredMethods = $route->getMethods()) {
|
||||
// HEAD and GET are equivalent as per RFC
|
||||
if ('HEAD' === $method = $this->context->getMethod()) {
|
||||
$method = 'GET';
|
||||
}
|
||||
|
||||
if (!in_array($method, $requiredMethods)) {
|
||||
$this->allow = array_merge($this->allow, $requiredMethods);
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$status = $this->handleRouteRequirements($pathinfo, $name, $route);
|
||||
|
||||
if (self::ROUTE_MATCH === $status[0]) {
|
||||
return $status[1];
|
||||
}
|
||||
|
||||
if (self::REQUIREMENT_MISMATCH === $status[0]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return $this->getAttributes($route, $name, array_replace($matches, $hostMatches));
|
||||
if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) {
|
||||
if ($supportsTrailingSlash && (!$requiredMethods || \in_array('GET', $requiredMethods))) {
|
||||
return $this->allow = $this->allowSchemes = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($route->getSchemes() && !$route->hasScheme($this->context->getScheme())) {
|
||||
$this->allowSchemes = array_merge($this->allowSchemes, $route->getSchemes());
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($requiredMethods && !\in_array($method, $requiredMethods)) {
|
||||
$this->allow = array_merge($this->allow, $requiredMethods);
|
||||
continue;
|
||||
}
|
||||
|
||||
return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, $status[1] ?? []));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,55 +202,41 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
* As this method requires the Route object, it is not available
|
||||
* in matchers that do not have access to the matched Route instance
|
||||
* (like the PHP and Apache matcher dumpers).
|
||||
*
|
||||
* @param Route $route The route we are matching against
|
||||
* @param string $name The name of the route
|
||||
* @param array $attributes An array of attributes from the matcher
|
||||
*
|
||||
* @return array An array of parameters
|
||||
*/
|
||||
protected function getAttributes(Route $route, $name, array $attributes)
|
||||
protected function getAttributes(Route $route, string $name, array $attributes): array
|
||||
{
|
||||
$defaults = $route->getDefaults();
|
||||
if (isset($defaults['_canonical_route'])) {
|
||||
$name = $defaults['_canonical_route'];
|
||||
unset($defaults['_canonical_route']);
|
||||
}
|
||||
$attributes['_route'] = $name;
|
||||
|
||||
return $this->mergeDefaults($attributes, $route->getDefaults());
|
||||
return $this->mergeDefaults($attributes, $defaults);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles specific route requirements.
|
||||
*
|
||||
* @param string $pathinfo The path
|
||||
* @param string $name The route name
|
||||
* @param Route $route The route
|
||||
*
|
||||
* @return array The first element represents the status, the second contains additional information
|
||||
*/
|
||||
protected function handleRouteRequirements($pathinfo, $name, Route $route)
|
||||
protected function handleRouteRequirements(string $pathinfo, string $name, Route $route): array
|
||||
{
|
||||
// expression condition
|
||||
if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), array('context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)))) {
|
||||
return array(self::REQUIREMENT_MISMATCH, null);
|
||||
if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition(), ['context' => $this->context, 'request' => $this->request ?: $this->createRequest($pathinfo)])) {
|
||||
return [self::REQUIREMENT_MISMATCH, null];
|
||||
}
|
||||
|
||||
// check HTTP scheme requirement
|
||||
$scheme = $this->context->getScheme();
|
||||
$status = $route->getSchemes() && !$route->hasScheme($scheme) ? self::REQUIREMENT_MISMATCH : self::REQUIREMENT_MATCH;
|
||||
|
||||
return array($status, null);
|
||||
return [self::REQUIREMENT_MATCH, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get merged default parameters.
|
||||
*
|
||||
* @param array $params The parameters
|
||||
* @param array $defaults The defaults
|
||||
*
|
||||
* @return array Merged default parameters
|
||||
*/
|
||||
protected function mergeDefaults($params, $defaults)
|
||||
protected function mergeDefaults(array $params, array $defaults): array
|
||||
{
|
||||
foreach ($params as $key => $value) {
|
||||
if (!is_int($key)) {
|
||||
if (!\is_int($key) && null !== $value) {
|
||||
$defaults[$key] = $value;
|
||||
}
|
||||
}
|
||||
@@ -240,8 +247,8 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
protected function getExpressionLanguage()
|
||||
{
|
||||
if (null === $this->expressionLanguage) {
|
||||
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
|
||||
throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
|
||||
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);
|
||||
}
|
||||
@@ -252,15 +259,15 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
protected function createRequest($pathinfo)
|
||||
protected function createRequest(string $pathinfo): ?Request
|
||||
{
|
||||
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
|
||||
if (!class_exists(Request::class)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), array(), array(), array(
|
||||
return Request::create($this->context->getScheme().'://'.$this->context->getHost().$this->context->getBaseUrl().$pathinfo, $this->context->getMethod(), $this->context->getParameters(), [], [], [
|
||||
'SCRIPT_FILENAME' => $this->context->getBaseUrl(),
|
||||
'SCRIPT_NAME' => $this->context->getBaseUrl(),
|
||||
));
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
|
||||
namespace Symfony\Component\Routing\Matcher;
|
||||
|
||||
use Symfony\Component\Routing\RequestContextAwareInterface;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
|
||||
use Symfony\Component\Routing\Exception\NoConfigurationException;
|
||||
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
|
||||
use Symfony\Component\Routing\RequestContextAwareInterface;
|
||||
|
||||
/**
|
||||
* UrlMatcherInterface is the interface that all URL matcher classes must implement.
|
||||
@@ -25,15 +26,14 @@ interface UrlMatcherInterface extends RequestContextAwareInterface
|
||||
/**
|
||||
* Tries to match a URL path with a set of routes.
|
||||
*
|
||||
* If the matcher can not find information, it must throw one of the exceptions documented
|
||||
* If the matcher cannot find information, it must throw one of the exceptions documented
|
||||
* below.
|
||||
*
|
||||
* @param string $pathinfo The path info to be parsed (raw format, i.e. not urldecoded)
|
||||
*
|
||||
* @return array An array of parameters
|
||||
*
|
||||
* @throws NoConfigurationException If no routing configuration could be found
|
||||
* @throws ResourceNotFoundException If the resource could not be found
|
||||
* @throws MethodNotAllowedException If the resource was found but the request method is not allowed
|
||||
*/
|
||||
public function match($pathinfo);
|
||||
public function match(string $pathinfo): array;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user