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