vendor/symfony/routing/RouteCompiler.php line 89

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Routing;
  11. /**
  12.  * RouteCompiler compiles Route instances to CompiledRoute instances.
  13.  *
  14.  * @author Fabien Potencier <fabien@symfony.com>
  15.  * @author Tobias Schultze <http://tobion.de>
  16.  */
  17. class RouteCompiler implements RouteCompilerInterface
  18. {
  19.     /**
  20.      * This string defines the characters that are automatically considered separators in front of
  21.      * optional placeholders (with default and no static text following). Such a single separator
  22.      * can be left out together with the optional placeholder from matching and generating URLs.
  23.      */
  24.     public const SEPARATORS '/,;.:-_~+*=@|';
  25.     /**
  26.      * The maximum supported length of a PCRE subpattern name
  27.      * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.
  28.      *
  29.      * @internal
  30.      */
  31.     public const VARIABLE_MAXIMUM_LENGTH 32;
  32.     /**
  33.      * {@inheritdoc}
  34.      *
  35.      * @throws \InvalidArgumentException if a path variable is named _fragment
  36.      * @throws \LogicException           if a variable is referenced more than once
  37.      * @throws \DomainException          if a variable name starts with a digit or if it is too long to be successfully used as
  38.      *                                   a PCRE subpattern
  39.      */
  40.     public static function compile(Route $route): CompiledRoute
  41.     {
  42.         $hostVariables = [];
  43.         $variables = [];
  44.         $hostRegex null;
  45.         $hostTokens = [];
  46.         if ('' !== $host $route->getHost()) {
  47.             $result self::compilePattern($route$hosttrue);
  48.             $hostVariables $result['variables'];
  49.             $variables $hostVariables;
  50.             $hostTokens $result['tokens'];
  51.             $hostRegex $result['regex'];
  52.         }
  53.         $locale $route->getDefault('_locale');
  54.         if (null !== $locale && null !== $route->getDefault('_canonical_route') && preg_quote($locale) === $route->getRequirement('_locale')) {
  55.             $requirements $route->getRequirements();
  56.             unset($requirements['_locale']);
  57.             $route->setRequirements($requirements);
  58.             $route->setPath(str_replace('{_locale}'$locale$route->getPath()));
  59.         }
  60.         $path $route->getPath();
  61.         $result self::compilePattern($route$pathfalse);
  62.         $staticPrefix $result['staticPrefix'];
  63.         $pathVariables $result['variables'];
  64.         foreach ($pathVariables as $pathParam) {
  65.             if ('_fragment' === $pathParam) {
  66.                 throw new \InvalidArgumentException(sprintf('Route pattern "%s" cannot contain "_fragment" as a path parameter.'$route->getPath()));
  67.             }
  68.         }
  69.         $variables array_merge($variables$pathVariables);
  70.         $tokens $result['tokens'];
  71.         $regex $result['regex'];
  72.         return new CompiledRoute(
  73.             $staticPrefix,
  74.             $regex,
  75.             $tokens,
  76.             $pathVariables,
  77.             $hostRegex,
  78.             $hostTokens,
  79.             $hostVariables,
  80.             array_unique($variables)
  81.         );
  82.     }
  83.     private static function compilePattern(Route $routestring $patternbool $isHost): array
  84.     {
  85.         $tokens = [];
  86.         $variables = [];
  87.         $matches = [];
  88.         $pos 0;
  89.         $defaultSeparator $isHost '.' '/';
  90.         $useUtf8 preg_match('//u'$pattern);
  91.         $needsUtf8 $route->getOption('utf8');
  92.         if (!$needsUtf8 && $useUtf8 && preg_match('/[\x80-\xFF]/'$pattern)) {
  93.             throw new \LogicException(sprintf('Cannot use UTF-8 route patterns without setting the "utf8" option for route "%s".'$route->getPath()));
  94.         }
  95.         if (!$useUtf8 && $needsUtf8) {
  96.             throw new \LogicException(sprintf('Cannot mix UTF-8 requirements with non-UTF-8 pattern "%s".'$pattern));
  97.         }
  98.         // Match all variables enclosed in "{}" and iterate over them. But we only want to match the innermost variable
  99.         // in case of nested "{}", e.g. {foo{bar}}. This in ensured because \w does not match "{" or "}" itself.
  100.         preg_match_all('#\{(!)?([\w\x80-\xFF]+)\}#'$pattern$matches\PREG_OFFSET_CAPTURE \PREG_SET_ORDER);
  101.         foreach ($matches as $match) {
  102.             $important $match[1][1] >= 0;
  103.             $varName $match[2][0];
  104.             // get all static text preceding the current variable
  105.             $precedingText substr($pattern$pos$match[0][1] - $pos);
  106.             $pos $match[0][1] + \strlen($match[0][0]);
  107.             if (!\strlen($precedingText)) {
  108.                 $precedingChar '';
  109.             } elseif ($useUtf8) {
  110.                 preg_match('/.$/u'$precedingText$precedingChar);
  111.                 $precedingChar $precedingChar[0];
  112.             } else {
  113.                 $precedingChar substr($precedingText, -1);
  114.             }
  115.             $isSeparator '' !== $precedingChar && str_contains(static::SEPARATORS$precedingChar);
  116.             // A PCRE subpattern name must start with a non-digit. Also a PHP variable cannot start with a digit so the
  117.             // variable would not be usable as a Controller action argument.
  118.             if (preg_match('/^\d/'$varName)) {
  119.                 throw new \DomainException(sprintf('Variable name "%s" cannot start with a digit in route pattern "%s". Please use a different name.'$varName$pattern));
  120.             }
  121.             if (\in_array($varName$variables)) {
  122.                 throw new \LogicException(sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.'$pattern$varName));
  123.             }
  124.             if (\strlen($varName) > self::VARIABLE_MAXIMUM_LENGTH) {
  125.                 throw new \DomainException(sprintf('Variable name "%s" cannot be longer than %d characters in route pattern "%s". Please use a shorter name.'$varNameself::VARIABLE_MAXIMUM_LENGTH$pattern));
  126.             }
  127.             if ($isSeparator && $precedingText !== $precedingChar) {
  128.                 $tokens[] = ['text'substr($precedingText0, -\strlen($precedingChar))];
  129.             } elseif (!$isSeparator && '' !== $precedingText) {
  130.                 $tokens[] = ['text'$precedingText];
  131.             }
  132.             $regexp $route->getRequirement($varName);
  133.             if (null === $regexp) {
  134.                 $followingPattern = (string) substr($pattern$pos);
  135.                 // Find the next static character after the variable that functions as a separator. By default, this separator and '/'
  136.                 // are disallowed for the variable. This default requirement makes sure that optional variables can be matched at all
  137.                 // and that the generating-matching-combination of URLs unambiguous, i.e. the params used for generating the URL are
  138.                 // the same that will be matched. Example: new Route('/{page}.{_format}', ['_format' => 'html'])
  139.                 // If {page} would also match the separating dot, {_format} would never match as {page} will eagerly consume everything.
  140.                 // Also even if {_format} was not optional the requirement prevents that {page} matches something that was originally
  141.                 // part of {_format} when generating the URL, e.g. _format = 'mobile.html'.
  142.                 $nextSeparator self::findNextSeparator($followingPattern$useUtf8);
  143.                 $regexp sprintf(
  144.                     '[^%s%s]+',
  145.                     preg_quote($defaultSeparator),
  146.                     $defaultSeparator !== $nextSeparator && '' !== $nextSeparator preg_quote($nextSeparator) : ''
  147.                 );
  148.                 if (('' !== $nextSeparator && !preg_match('#^\{[\w\x80-\xFF]+\}#'$followingPattern)) || '' === $followingPattern) {
  149.                     // When we have a separator, which is disallowed for the variable, we can optimize the regex with a possessive
  150.                     // quantifier. This prevents useless backtracking of PCRE and improves performance by 20% for matching those patterns.
  151.                     // Given the above example, there is no point in backtracking into {page} (that forbids the dot) when a dot must follow
  152.                     // after it. This optimization cannot be applied when the next char is no real separator or when the next variable is
  153.                     // directly adjacent, e.g. '/{x}{y}'.
  154.                     $regexp .= '+';
  155.                 }
  156.             } else {
  157.                 if (!preg_match('//u'$regexp)) {
  158.                     $useUtf8 false;
  159.                 } elseif (!$needsUtf8 && preg_match('/[\x80-\xFF]|(?<!\\\\)\\\\(?:\\\\\\\\)*+(?-i:X|[pP][\{CLMNPSZ]|x\{[A-Fa-f0-9]{3})/'$regexp)) {
  160.                     throw new \LogicException(sprintf('Cannot use UTF-8 route requirements without setting the "utf8" option for variable "%s" in pattern "%s".'$varName$pattern));
  161.                 }
  162.                 if (!$useUtf8 && $needsUtf8) {
  163.                     throw new \LogicException(sprintf('Cannot mix UTF-8 requirement with non-UTF-8 charset for variable "%s" in pattern "%s".'$varName$pattern));
  164.                 }
  165.                 $regexp self::transformCapturingGroupsToNonCapturings($regexp);
  166.             }
  167.             if ($important) {
  168.                 $token = ['variable'$isSeparator $precedingChar ''$regexp$varNamefalsetrue];
  169.             } else {
  170.                 $token = ['variable'$isSeparator $precedingChar ''$regexp$varName];
  171.             }
  172.             $tokens[] = $token;
  173.             $variables[] = $varName;
  174.         }
  175.         if ($pos \strlen($pattern)) {
  176.             $tokens[] = ['text'substr($pattern$pos)];
  177.         }
  178.         // find the first optional token
  179.         $firstOptional \PHP_INT_MAX;
  180.         if (!$isHost) {
  181.             for ($i \count($tokens) - 1$i >= 0; --$i) {
  182.                 $token $tokens[$i];
  183.                 // variable is optional when it is not important and has a default value
  184.                 if ('variable' === $token[0] && !($token[5] ?? false) && $route->hasDefault($token[3])) {
  185.                     $firstOptional $i;
  186.                 } else {
  187.                     break;
  188.                 }
  189.             }
  190.         }
  191.         // compute the matching regexp
  192.         $regexp '';
  193.         for ($i 0$nbToken \count($tokens); $i $nbToken; ++$i) {
  194.             $regexp .= self::computeRegexp($tokens$i$firstOptional);
  195.         }
  196.         $regexp '{^'.$regexp.'$}sD'.($isHost 'i' '');
  197.         // enable Utf8 matching if really required
  198.         if ($needsUtf8) {
  199.             $regexp .= 'u';
  200.             for ($i 0$nbToken \count($tokens); $i $nbToken; ++$i) {
  201.                 if ('variable' === $tokens[$i][0]) {
  202.                     $tokens[$i][4] = true;
  203.                 }
  204.             }
  205.         }
  206.         return [
  207.             'staticPrefix' => self::determineStaticPrefix($route$tokens),
  208.             'regex' => $regexp,
  209.             'tokens' => array_reverse($tokens),
  210.             'variables' => $variables,
  211.         ];
  212.     }
  213.     /**
  214.      * Determines the longest static prefix possible for a route.
  215.      */
  216.     private static function determineStaticPrefix(Route $route, array $tokens): string
  217.     {
  218.         if ('text' !== $tokens[0][0]) {
  219.             return ($route->hasDefault($tokens[0][3]) || '/' === $tokens[0][1]) ? '' $tokens[0][1];
  220.         }
  221.         $prefix $tokens[0][1];
  222.         if (isset($tokens[1][1]) && '/' !== $tokens[1][1] && false === $route->hasDefault($tokens[1][3])) {
  223.             $prefix .= $tokens[1][1];
  224.         }
  225.         return $prefix;
  226.     }
  227.     /**
  228.      * Returns the next static character in the Route pattern that will serve as a separator (or the empty string when none available).
  229.      */
  230.     private static function findNextSeparator(string $patternbool $useUtf8): string
  231.     {
  232.         if ('' == $pattern) {
  233.             // return empty string if pattern is empty or false (false which can be returned by substr)
  234.             return '';
  235.         }
  236.         // first remove all placeholders from the pattern so we can find the next real static character
  237.         if ('' === $pattern preg_replace('#\{[\w\x80-\xFF]+\}#'''$pattern)) {
  238.             return '';
  239.         }
  240.         if ($useUtf8) {
  241.             preg_match('/^./u'$pattern$pattern);
  242.         }
  243.         return str_contains(static::SEPARATORS$pattern[0]) ? $pattern[0] : '';
  244.     }
  245.     /**
  246.      * Computes the regexp used to match a specific token. It can be static text or a subpattern.
  247.      *
  248.      * @param array $tokens        The route tokens
  249.      * @param int   $index         The index of the current token
  250.      * @param int   $firstOptional The index of the first optional token
  251.      */
  252.     private static function computeRegexp(array $tokensint $indexint $firstOptional): string
  253.     {
  254.         $token $tokens[$index];
  255.         if ('text' === $token[0]) {
  256.             // Text tokens
  257.             return preg_quote($token[1]);
  258.         } else {
  259.             // Variable tokens
  260.             if (=== $index && === $firstOptional) {
  261.                 // When the only token is an optional variable token, the separator is required
  262.                 return sprintf('%s(?P<%s>%s)?'preg_quote($token[1]), $token[3], $token[2]);
  263.             } else {
  264.                 $regexp sprintf('%s(?P<%s>%s)'preg_quote($token[1]), $token[3], $token[2]);
  265.                 if ($index >= $firstOptional) {
  266.                     // Enclose each optional token in a subpattern to make it optional.
  267.                     // "?:" means it is non-capturing, i.e. the portion of the subject string that
  268.                     // matched the optional subpattern is not passed back.
  269.                     $regexp "(?:$regexp";
  270.                     $nbTokens \count($tokens);
  271.                     if ($nbTokens == $index) {
  272.                         // Close the optional subpatterns
  273.                         $regexp .= str_repeat(')?'$nbTokens $firstOptional - (=== $firstOptional 0));
  274.                     }
  275.                 }
  276.                 return $regexp;
  277.             }
  278.         }
  279.     }
  280.     private static function transformCapturingGroupsToNonCapturings(string $regexp): string
  281.     {
  282.         for ($i 0$i \strlen($regexp); ++$i) {
  283.             if ('\\' === $regexp[$i]) {
  284.                 ++$i;
  285.                 continue;
  286.             }
  287.             if ('(' !== $regexp[$i] || !isset($regexp[$i 2])) {
  288.                 continue;
  289.             }
  290.             if ('*' === $regexp[++$i] || '?' === $regexp[$i]) {
  291.                 ++$i;
  292.                 continue;
  293.             }
  294.             $regexp substr_replace($regexp'?:'$i0);
  295.             ++$i;
  296.         }
  297.         return $regexp;
  298.     }
  299. }