Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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