vendor/symfony/routing/RouteCompiler.php line 87

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