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\Matcher\Dumper;
13
 
14
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
15
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
16
use Symfony\Component\Routing\Route;
17
use Symfony\Component\Routing\RouteCollection;
18
 
19
/**
20
 * CompiledUrlMatcherDumper creates PHP arrays to be used with CompiledUrlMatcher.
21
 *
22
 * @author Fabien Potencier <fabien@symfony.com>
23
 * @author Tobias Schultze <http://tobion.de>
24
 * @author Arnaud Le Blanc <arnaud.lb@gmail.com>
25
 * @author Nicolas Grekas <p@tchwork.com>
26
 */
27
class CompiledUrlMatcherDumper extends MatcherDumper
28
{
29
    private ExpressionLanguage $expressionLanguage;
30
    private ?\Exception $signalingException = null;
31
 
32
    /**
33
     * @var ExpressionFunctionProviderInterface[]
34
     */
35
    private array $expressionLanguageProviders = [];
36
 
37
    public function dump(array $options = []): string
38
    {
39
        return <<<EOF
40
<?php
41
 
42
/**
43
 * This file has been auto-generated
44
 * by the Symfony Routing Component.
45
 */
46
 
47
return [
48
{$this->generateCompiledRoutes()}];
49
 
50
EOF;
51
    }
52
 
53
    public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider)
54
    {
55
        $this->expressionLanguageProviders[] = $provider;
56
    }
57
 
58
    /**
59
     * Generates the arrays for CompiledUrlMatcher's constructor.
60
     */
61
    public function getCompiledRoutes(bool $forDump = false): array
62
    {
63
        // Group hosts by same-suffix, re-order when possible
64
        $matchHost = false;
65
        $routes = new StaticPrefixCollection();
66
        foreach ($this->getRoutes()->all() as $name => $route) {
67
            if ($host = $route->getHost()) {
68
                $matchHost = true;
69
                $host = '/'.strtr(strrev($host), '}.{', '(/)');
70
            }
71
 
72
            $routes->addRoute($host ?: '/(.*)', [$name, $route]);
73
        }
74
 
75
        if ($matchHost) {
76
            $compiledRoutes = [true];
77
            $routes = $routes->populateCollection(new RouteCollection());
78
        } else {
79
            $compiledRoutes = [false];
80
            $routes = $this->getRoutes();
81
        }
82
 
83
        [$staticRoutes, $dynamicRoutes] = $this->groupStaticRoutes($routes);
84
 
85
        $conditions = [null];
86
        $compiledRoutes[] = $this->compileStaticRoutes($staticRoutes, $conditions);
87
        $chunkLimit = \count($dynamicRoutes);
88
 
89
        while (true) {
90
            try {
91
                $this->signalingException = new \RuntimeException('Compilation failed: regular expression is too large');
92
                $compiledRoutes = array_merge($compiledRoutes, $this->compileDynamicRoutes($dynamicRoutes, $matchHost, $chunkLimit, $conditions));
93
 
94
                break;
95
            } catch (\Exception $e) {
96
                if (1 < $chunkLimit && $this->signalingException === $e) {
97
                    $chunkLimit = 1 + ($chunkLimit >> 1);
98
                    continue;
99
                }
100
                throw $e;
101
            }
102
        }
103
 
104
        if ($forDump) {
105
            $compiledRoutes[2] = $compiledRoutes[4];
106
        }
107
        unset($conditions[0]);
108
 
109
        if ($conditions) {
110
            foreach ($conditions as $expression => $condition) {
111
                $conditions[$expression] = "case {$condition}: return {$expression};";
112
            }
113
 
114
            $checkConditionCode = <<<EOF
115
    static function (\$condition, \$context, \$request, \$params) { // \$checkCondition
116
        switch (\$condition) {
117
{$this->indent(implode("\n", $conditions), 3)}
118
        }
119
    }
120
EOF;
121
            $compiledRoutes[4] = $forDump ? $checkConditionCode.",\n" : eval('return '.$checkConditionCode.';');
122
        } else {
123
            $compiledRoutes[4] = $forDump ? "    null, // \$checkCondition\n" : null;
124
        }
125
 
126
        return $compiledRoutes;
127
    }
128
 
129
    private function generateCompiledRoutes(): string
130
    {
131
        [$matchHost, $staticRoutes, $regexpCode, $dynamicRoutes, $checkConditionCode] = $this->getCompiledRoutes(true);
132
 
133
        $code = self::export($matchHost).', // $matchHost'."\n";
134
 
135
        $code .= '[ // $staticRoutes'."\n";
136
        foreach ($staticRoutes as $path => $routes) {
137
            $code .= sprintf("    %s => [\n", self::export($path));
138
            foreach ($routes as $route) {
139
                $code .= sprintf("        [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
140
            }
141
            $code .= "    ],\n";
142
        }
143
        $code .= "],\n";
144
 
145
        $code .= sprintf("[ // \$regexpList%s\n],\n", $regexpCode);
146
 
147
        $code .= '[ // $dynamicRoutes'."\n";
148
        foreach ($dynamicRoutes as $path => $routes) {
149
            $code .= sprintf("    %s => [\n", self::export($path));
150
            foreach ($routes as $route) {
151
                $code .= sprintf("        [%s, %s, %s, %s, %s, %s, %s],\n", ...array_map([__CLASS__, 'export'], $route));
152
            }
153
            $code .= "    ],\n";
154
        }
155
        $code .= "],\n";
156
        $code = preg_replace('/ => \[\n        (\[.+?),\n    \],/', ' => [$1],', $code);
157
 
158
        return $this->indent($code, 1).$checkConditionCode;
159
    }
160
 
161
    /**
162
     * Splits static routes from dynamic routes, so that they can be matched first, using a simple switch.
163
     */
164
    private function groupStaticRoutes(RouteCollection $collection): array
165
    {
166
        $staticRoutes = $dynamicRegex = [];
167
        $dynamicRoutes = new RouteCollection();
168
 
169
        foreach ($collection->all() as $name => $route) {
170
            $compiledRoute = $route->compile();
171
            $staticPrefix = rtrim($compiledRoute->getStaticPrefix(), '/');
172
            $hostRegex = $compiledRoute->getHostRegex();
173
            $regex = $compiledRoute->getRegex();
174
            if ($hasTrailingSlash = '/' !== $route->getPath()) {
175
                $pos = strrpos($regex, '$');
176
                $hasTrailingSlash = '/' === $regex[$pos - 1];
177
                $regex = substr_replace($regex, '/?$', $pos - $hasTrailingSlash, 1 + $hasTrailingSlash);
178
            }
179
 
180
            if (!$compiledRoute->getPathVariables()) {
181
                $host = !$compiledRoute->getHostVariables() ? $route->getHost() : '';
182
                $url = $route->getPath();
183
                if ($hasTrailingSlash) {
184
                    $url = substr($url, 0, -1);
185
                }
186
                foreach ($dynamicRegex as [$hostRx, $rx, $prefix]) {
187
                    if (('' === $prefix || str_starts_with($url, $prefix)) && (preg_match($rx, $url) || preg_match($rx, $url.'/')) && (!$host || !$hostRx || preg_match($hostRx, $host))) {
188
                        $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
189
                        $dynamicRoutes->add($name, $route);
190
                        continue 2;
191
                    }
192
                }
193
 
194
                $staticRoutes[$url][$name] = [$route, $hasTrailingSlash];
195
            } else {
196
                $dynamicRegex[] = [$hostRegex, $regex, $staticPrefix];
197
                $dynamicRoutes->add($name, $route);
198
            }
199
        }
200
 
201
        return [$staticRoutes, $dynamicRoutes];
202
    }
203
 
204
    /**
205
     * Compiles static routes in a switch statement.
206
     *
207
     * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
208
     * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
209
     *
210
     * @throws \LogicException
211
     */
212
    private function compileStaticRoutes(array $staticRoutes, array &$conditions): array
213
    {
214
        if (!$staticRoutes) {
215
            return [];
216
        }
217
        $compiledRoutes = [];
218
 
219
        foreach ($staticRoutes as $url => $routes) {
220
            $compiledRoutes[$url] = [];
221
            foreach ($routes as $name => [$route, $hasTrailingSlash]) {
222
                $compiledRoutes[$url][] = $this->compileRoute($route, $name, (!$route->compile()->getHostVariables() ? $route->getHost() : $route->compile()->getHostRegex()) ?: null, $hasTrailingSlash, false, $conditions);
223
            }
224
        }
225
 
226
        return $compiledRoutes;
227
    }
228
 
229
    /**
230
     * Compiles a regular expression followed by a switch statement to match dynamic routes.
231
     *
232
     * The regular expression matches both the host and the pathinfo at the same time. For stellar performance,
233
     * it is built as a tree of patterns, with re-ordering logic to group same-prefix routes together when possible.
234
     *
235
     * Patterns are named so that we know which one matched (https://pcre.org/current/doc/html/pcre2syntax.html#SEC23).
236
     * This name is used to "switch" to the additional logic required to match the final route.
237
     *
238
     * Condition-less paths are put in a static array in the switch's default, with generic matching logic.
239
     * Paths that can match two or more routes, or have user-specified conditions are put in separate switch's cases.
240
     *
241
     * Last but not least:
242
     *  - Because it is not possible to mix unicode/non-unicode patterns in a single regexp, several of them can be generated.
243
     *  - The same regexp can be used several times when the logic in the switch rejects the match. When this happens, the
244
     *    matching-but-failing subpattern is excluded by replacing its name by "(*F)", which forces a failure-to-match.
245
     *    To ease this backlisting operation, the name of subpatterns is also the string offset where the replacement should occur.
246
     */
247
    private function compileDynamicRoutes(RouteCollection $collection, bool $matchHost, int $chunkLimit, array &$conditions): array
248
    {
249
        if (!$collection->all()) {
250
            return [[], [], ''];
251
        }
252
        $regexpList = [];
253
        $code = '';
254
        $state = (object) [
255
            'regexMark' => 0,
256
            'regex' => [],
257
            'routes' => [],
258
            'mark' => 0,
259
            'markTail' => 0,
260
            'hostVars' => [],
261
            'vars' => [],
262
        ];
263
        $state->getVars = static function ($m) use ($state) {
264
            if ('_route' === $m[1]) {
265
                return '?:';
266
            }
267
 
268
            $state->vars[] = $m[1];
269
 
270
            return '';
271
        };
272
 
273
        $chunkSize = 0;
274
        $prev = null;
275
        $perModifiers = [];
276
        foreach ($collection->all() as $name => $route) {
277
            preg_match('#[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
278
            if ($chunkLimit < ++$chunkSize || $prev !== $rx[0] && $route->compile()->getPathVariables()) {
279
                $chunkSize = 1;
280
                $routes = new RouteCollection();
281
                $perModifiers[] = [$rx[0], $routes];
282
                $prev = $rx[0];
283
            }
284
            $routes->add($name, $route);
285
        }
286
 
287
        foreach ($perModifiers as [$modifiers, $routes]) {
288
            $prev = false;
289
            $perHost = [];
290
            foreach ($routes->all() as $name => $route) {
291
                $regex = $route->compile()->getHostRegex();
292
                if ($prev !== $regex) {
293
                    $routes = new RouteCollection();
294
                    $perHost[] = [$regex, $routes];
295
                    $prev = $regex;
296
                }
297
                $routes->add($name, $route);
298
            }
299
            $prev = false;
300
            $rx = '{^(?';
301
            $code .= "\n    {$state->mark} => ".self::export($rx);
302
            $startingMark = $state->mark;
303
            $state->mark += \strlen($rx);
304
            $state->regex = $rx;
305
 
306
            foreach ($perHost as [$hostRegex, $routes]) {
307
                if ($matchHost) {
308
                    if ($hostRegex) {
309
                        preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $hostRegex, $rx);
310
                        $state->vars = [];
311
                        $hostRegex = '(?i:'.preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]).')\.';
312
                        $state->hostVars = $state->vars;
313
                    } else {
314
                        $hostRegex = '(?:(?:[^./]*+\.)++)';
315
                        $state->hostVars = [];
316
                    }
317
                    $state->mark += \strlen($rx = ($prev ? ')' : '')."|{$hostRegex}(?");
318
                    $code .= "\n        .".self::export($rx);
319
                    $state->regex .= $rx;
320
                    $prev = true;
321
                }
322
 
323
                $tree = new StaticPrefixCollection();
324
                foreach ($routes->all() as $name => $route) {
325
                    preg_match('#^.\^(.*)\$.[a-zA-Z]*$#', $route->compile()->getRegex(), $rx);
326
 
327
                    $state->vars = [];
328
                    $regex = preg_replace_callback('#\?P<([^>]++)>#', $state->getVars, $rx[1]);
329
                    if ($hasTrailingSlash = '/' !== $regex && '/' === $regex[-1]) {
330
                        $regex = substr($regex, 0, -1);
331
                    }
332
                    $hasTrailingVar = (bool) preg_match('#\{[\w\x80-\xFF]+\}/?$#', $route->getPath());
333
 
334
                    $tree->addRoute($regex, [$name, $regex, $state->vars, $route, $hasTrailingSlash, $hasTrailingVar]);
335
                }
336
 
337
                $code .= $this->compileStaticPrefixCollection($tree, $state, 0, $conditions);
338
            }
339
            if ($matchHost) {
340
                $code .= "\n        .')'";
341
                $state->regex .= ')';
342
            }
343
            $rx = ")/?$}{$modifiers}";
344
            $code .= "\n        .'{$rx}',";
345
            $state->regex .= $rx;
346
            $state->markTail = 0;
347
 
348
            // if the regex is too large, throw a signaling exception to recompute with smaller chunk size
349
            set_error_handler(function ($type, $message) { throw str_contains($message, $this->signalingException->getMessage()) ? $this->signalingException : new \ErrorException($message); });
350
            try {
351
                preg_match($state->regex, '');
352
            } finally {
353
                restore_error_handler();
354
            }
355
 
356
            $regexpList[$startingMark] = $state->regex;
357
        }
358
 
359
        $state->routes[$state->mark][] = [null, null, null, null, false, false, 0];
360
        unset($state->getVars);
361
 
362
        return [$regexpList, $state->routes, $code];
363
    }
364
 
365
    /**
366
     * Compiles a regexp tree of subpatterns that matches nested same-prefix routes.
367
     *
368
     * @param \stdClass $state A simple state object that keeps track of the progress of the compilation,
369
     *                         and gathers the generated switch's "case" and "default" statements
370
     */
371
    private function compileStaticPrefixCollection(StaticPrefixCollection $tree, \stdClass $state, int $prefixLen, array &$conditions): string
372
    {
373
        $code = '';
374
        $prevRegex = null;
375
        $routes = $tree->getRoutes();
376
 
377
        foreach ($routes as $i => $route) {
378
            if ($route instanceof StaticPrefixCollection) {
379
                $prevRegex = null;
380
                $prefix = substr($route->getPrefix(), $prefixLen);
381
                $state->mark += \strlen($rx = "|{$prefix}(?");
382
                $code .= "\n            .".self::export($rx);
383
                $state->regex .= $rx;
384
                $code .= $this->indent($this->compileStaticPrefixCollection($route, $state, $prefixLen + \strlen($prefix), $conditions));
385
                $code .= "\n            .')'";
386
                $state->regex .= ')';
387
                ++$state->markTail;
388
                continue;
389
            }
390
 
391
            [$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route;
392
            $compiledRoute = $route->compile();
393
            $vars = array_merge($state->hostVars, $vars);
394
 
395
            if ($compiledRoute->getRegex() === $prevRegex) {
396
                $state->routes[$state->mark][] = $this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions);
397
                continue;
398
            }
399
 
400
            $state->mark += 3 + $state->markTail + \strlen($regex) - $prefixLen;
401
            $state->markTail = 2 + \strlen($state->mark);
402
            $rx = sprintf('|%s(*:%s)', substr($regex, $prefixLen), $state->mark);
403
            $code .= "\n            .".self::export($rx);
404
            $state->regex .= $rx;
405
 
406
            $prevRegex = $compiledRoute->getRegex();
407
            $state->routes[$state->mark] = [$this->compileRoute($route, $name, $vars, $hasTrailingSlash, $hasTrailingVar, $conditions)];
408
        }
409
 
410
        return $code;
411
    }
412
 
413
    /**
414
     * Compiles a single Route to PHP code used to match it against the path info.
415
     */
416
    private function compileRoute(Route $route, string $name, string|array|null $vars, bool $hasTrailingSlash, bool $hasTrailingVar, array &$conditions): array
417
    {
418
        $defaults = $route->getDefaults();
419
 
420
        if (isset($defaults['_canonical_route'])) {
421
            $name = $defaults['_canonical_route'];
422
            unset($defaults['_canonical_route']);
423
        }
424
 
425
        if ($condition = $route->getCondition()) {
426
            $condition = $this->getExpressionLanguage()->compile($condition, ['context', 'request', 'params']);
427
            $condition = $conditions[$condition] ??= (str_contains($condition, '$request') ? 1 : -1) * \count($conditions);
428
        } else {
429
            $condition = null;
430
        }
431
 
432
        return [
433
            ['_route' => $name] + $defaults,
434
            $vars,
435
            array_flip($route->getMethods()) ?: null,
436
            array_flip($route->getSchemes()) ?: null,
437
            $hasTrailingSlash,
438
            $hasTrailingVar,
439
            $condition,
440
        ];
441
    }
442
 
443
    private function getExpressionLanguage(): ExpressionLanguage
444
    {
445
        if (!isset($this->expressionLanguage)) {
446
            if (!class_exists(ExpressionLanguage::class)) {
447
                throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
448
            }
449
            $this->expressionLanguage = new ExpressionLanguage(null, $this->expressionLanguageProviders);
450
        }
451
 
452
        return $this->expressionLanguage;
453
    }
454
 
455
    private function indent(string $code, int $level = 1): string
456
    {
457
        return preg_replace('/^./m', str_repeat('    ', $level).'$0', $code);
458
    }
459
 
460
    /**
461
     * @internal
462
     */
463
    public static function export(mixed $value): string
464
    {
465
        if (null === $value) {
466
            return 'null';
467
        }
468
        if (!\is_array($value)) {
469
            if (\is_object($value)) {
470
                throw new \InvalidArgumentException('Symfony\Component\Routing\Route cannot contain objects.');
471
            }
472
 
473
            return str_replace("\n", '\'."\n".\'', var_export($value, true));
474
        }
475
        if (!$value) {
476
            return '[]';
477
        }
478
 
479
        $i = 0;
480
        $export = '[';
481
 
482
        foreach ($value as $k => $v) {
483
            if ($i === $k) {
484
                ++$i;
485
            } else {
486
                $export .= self::export($k).' => ';
487
 
488
                if (\is_int($k) && $i < $k) {
489
                    $i = 1 + $k;
490
                }
491
            }
492
 
493
            $export .= self::export($v).', ';
494
        }
495
 
496
        return substr_replace($export, ']', -2);
497
    }
498
}