Passed
Pull Request — master (#23)
by Alexander
01:28
created

FastRoute::getRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router\FastRoute;
6
7
use FastRoute\Dispatcher;
8
use FastRoute\Dispatcher\GroupCountBased;
9
use FastRoute\RouteCollector;
10
use FastRoute\RouteParser;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Yiisoft\Router\Group;
13
use Yiisoft\Router\MatchingResult;
14
use Yiisoft\Http\Method;
15
use Yiisoft\Router\Route;
16
use Yiisoft\Router\RouteNotFoundException;
17
use Yiisoft\Router\RouterInterface;
18
19
use function array_key_exists;
20
use function array_keys;
21
use function array_merge;
22
use function array_reduce;
23
use function array_unique;
24
use function dirname;
25
use function file_exists;
26
use function file_put_contents;
27
use function implode;
28
use function is_array;
29
use function is_dir;
30
use function is_string;
31
use function is_writable;
32
use function preg_match;
33
use function restore_error_handler;
34
use function set_error_handler;
35
use function sprintf;
36
use function var_export;
37
38
use const E_WARNING;
39
40
/**
41
 * Router implementation bridging nikic/fast-route.
42
 * Adapted from https://github.com/zendframework/zend-expressive-fastroute/
43
 */
44
class FastRoute extends Group implements RouterInterface
45
{
46
    /**
47
     * Template used when generating the cache file.
48
     */
49
    public const CACHE_TEMPLATE = <<< 'EOT'
50
<?php
51
return %s;
52
EOT;
53
54
    /**
55
     * @const string Configuration key used to enable/disable fastroute caching
56
     */
57
    public const CONFIG_CACHE_ENABLED = 'cache_enabled';
58
59
    /**
60
     * @const string Configuration key used to set the cache file path
61
     */
62
    public const CONFIG_CACHE_FILE = 'cache_file';
63
64
    /**
65
     * Cache generated route data?
66
     *
67
     * @var bool
68
     */
69
    private $cacheEnabled = false;
70
71
    /**
72
     * Cache file path relative to the project directory.
73
     *
74
     * @var string
75
     */
76
    private $cacheFile = 'data/cache/fastroute.php.cache';
77
78
    /**
79
     * @var callable A factory callback that can return a dispatcher.
80
     */
81
    private $dispatcherCallback;
82
83
    /**
84
     * Cached data used by the dispatcher.
85
     *
86
     * @var array
87
     */
88
    private $dispatchData = [];
89
90
    /**
91
     * True if cache is enabled and valid dispatch data has been loaded from
92
     * cache.
93
     *
94
     * @var bool
95
     */
96
    private $hasCache = false;
97
98
    /**
99
     * FastRoute router
100
     *
101
     * @var RouteCollector
102
     */
103
    private $router;
104
105
    /**
106
     * All attached routes as Route instances
107
     *
108
     * @var Route[]
109
     */
110
    private $routes = [];
111
112
    /**
113
     * @var RouteParser
114
     */
115
    private $routeParser;
116
117
    /** @var string */
118
    private $uriPrefix = '';
119
120
    /** @var Route|null */
121
    private ?Route $currentRoute = null;
122
123
    /**
124
     * Last matched request
125
     *
126
     * @var ServerRequestInterface|null
127
     */
128
    private ?ServerRequestInterface $request = null;
129
130
    /**
131
     * Constructor
132
     *
133
     * Accepts optionally a FastRoute RouteCollector and a callable factory
134
     * that can return a FastRoute dispatcher.
135
     *
136
     * If either is not provided defaults will be used:
137
     *
138
     * - A RouteCollector instance will be created composing a RouteParser and
139
     *   RouteGenerator.
140
     * - A callable that returns a GroupCountBased dispatcher will be created.
141
     *
142
     * @param null|RouteCollector $router If not provided, a default
143
     *     implementation will be used.
144
     * @param RouteParser $routeParser
145
     * @param null|callable $dispatcherFactory Callable that will return a
146
     *     FastRoute dispatcher.
147
     * @param array $config Array of custom configuration options.
148
     */
149 21
    public function __construct(
150
        RouteCollector $router,
151
        RouteParser $routeParser,
152
        callable $dispatcherFactory = null,
153
        array $config = null
154
    ) {
155 21
        $this->router = $router;
156 21
        $this->dispatcherCallback = $dispatcherFactory;
157 21
        $this->routeParser = $routeParser;
158
159 21
        $this->loadConfig($config);
160
    }
161
162
    /**
163
     * Load configuration parameters
164
     *
165
     * @param null|array $config Array of custom configuration options.
166
     */
167 21
    private function loadConfig(array $config = null): void
168
    {
169 21
        if (null === $config) {
170 21
            return;
171
        }
172
173
        if (isset($config[self::CONFIG_CACHE_ENABLED])) {
174
            $this->cacheEnabled = (bool)$config[self::CONFIG_CACHE_ENABLED];
175
        }
176
177
        if (isset($config[self::CONFIG_CACHE_FILE])) {
178
            $this->cacheFile = (string)$config[self::CONFIG_CACHE_FILE];
179
        }
180
181
        if ($this->cacheEnabled) {
182
            $this->loadDispatchData();
183
        }
184
    }
185
186 5
    public function match(ServerRequestInterface $request): MatchingResult
187
    {
188 5
        $this->request = $request;
189
        // Inject any pending route items
190 5
        $this->injectItems();
191
192 5
        $dispatchData = $this->getDispatchData();
193 5
        $path = rawurldecode($request->getUri()->getPath());
194 5
        $method = $request->getMethod();
195 5
        $result = $this->getDispatcher($dispatchData)->dispatch($method, $path);
196
197 5
        return $result[0] !== Dispatcher::FOUND
198
            ? $this->marshalFailedRoute($result)
199 5
            : $this->marshalMatchedRoute($result, $method);
200
    }
201
202 17
    public function getUriPrefix(): string
203
    {
204 17
        return $this->uriPrefix;
205
    }
206
207
    public function setUriPrefix(string $prefix): void
208
    {
209
        $this->uriPrefix = $prefix;
210
    }
211
212
    /**
213
     * Generate a URI based on a given route.
214
     *
215
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
216
     * this method uses `FastRoute\RouteParser\Std` to search for the best route
217
     * match based on the available substitutions and generates a uri.
218
     *
219
     * @param string $name Route name.
220
     * @param array $parameters Key/value option pairs to pass to the router for
221
     * purposes of generating a URI; takes precedence over options present
222
     * in route used to generate URI.
223
     *
224
     * @return string URI path generated.
225
     * @throws \RuntimeException if the route name is not known or a parameter value does not match its regex.
226
     */
227 20
    public function generate(string $name, array $parameters = []): string
228
    {
229
        // Inject any pending route items
230 20
        $this->injectItems();
231
232 20
        $route = $this->getRoute($name);
233
234 19
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getPattern()));
235 19
        if ($parsedRoutes === []) {
236
            throw new RouteNotFoundException($name);
237
        }
238
239 19
        $missingParameters = [];
240
241
        // One route pattern can correspond to multiple routes if it has optional parts
242 19
        foreach ($parsedRoutes as $parsedRouteParts) {
243
            // Check if all parameters can be substituted
244 19
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
245
246
            // If not all parameters can be substituted, try the next route
247 19
            if (!empty($missingParameters)) {
248 3
                continue;
249
            }
250
251 17
            return $this->generatePath($parameters, $parsedRouteParts);
252
        }
253
254
        // No valid route was found: list minimal required parameters
255 2
        throw new \RuntimeException(sprintf(
256 2
            'Route `%s` expects at least parameter values for [%s], but received [%s]',
257 2
            $name,
258 2
            implode(',', $missingParameters),
259 2
            implode(',', array_keys($parameters))
260
        ));
261
    }
262
263
    /**
264
     * Generates absolute URL from named route and parameters
265
     *
266
     * @param string $name name of the route
267
     * @param array $parameters parameter-value set
268
     * @param string|null $scheme host scheme
269
     * @param string|null $host host for manual setup
270
     * @return string URL generated
271
     * @throws RouteNotFoundException in case there is no route with the name specified
272
     */
273 9
    public function generateAbsolute(string $name, array $parameters = [], string $scheme = null, string $host = null): string
274
    {
275 9
        $url = $this->generate($name, $parameters);
276 9
        $route = $this->getRoute($name);
277 9
        $uri = $this->request !== null ? $this->request->getUri() : null;
278 9
        $scheme = $scheme ?? ($uri !== null ? $uri->getScheme() : null);
279
280 9
        if ($host !== null) {
281 3
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme);
282
        }
283
284 6
        if (($host = $route->getHost()) !== null) {
285 4
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme);
286
        }
287
288 2
        if ($uri !== null) {
289 2
            $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
290 2
            return $scheme . '://' . $uri->getHost() . $port . $url;
291
        }
292
293
        return $url;
294
    }
295
296
    /**
297
     * Normalize URL by ensuring that it use specified scheme.
298
     *
299
     * If URL is relative or scheme is null, normalization is skipped.
300
     *
301
     * @param string $url the URL to process
302
     * @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
303
     * create protocol-relative URL (e.g. `//example.com/path`)
304
     * @return string the processed URL
305
     */
306 7
    private function ensureScheme(string $url, ?string $scheme): string
307
    {
308 7
        if ($scheme === null || $this->isRelative($url)) {
309 4
            return $url;
310
        }
311
312 3
        if (strpos($url, '//') === 0) {
313
            // e.g. //example.com/path/to/resource
314 2
            return $scheme === '' ? $url : "$scheme:$url";
315
        }
316
317 1
        if (($pos = strpos($url, '://')) !== false) {
318 1
            if ($scheme === '') {
319
                $url = substr($url, $pos + 1);
320
            } else {
321 1
                $url = $scheme . substr($url, $pos);
322
            }
323
        }
324
325 1
        return $url;
326
    }
327
328
    /**
329
     * Returns a value indicating whether a URL is relative.
330
     * A relative URL does not have host info part.
331
     * @param string $url the URL to be checked
332
     * @return bool whether the URL is relative
333
     */
334 3
    private function isRelative(string $url): bool
335
    {
336 3
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
337
    }
338
339
    /**
340
     * Returns the current Route object
341
     * @return Route|null current route
342
     */
343
    public function getCurrentRoute(): ?Route
344
    {
345
        return $this->currentRoute;
346
    }
347
348
    /**
349
     * Checks for any missing route parameters
350
     * @param array $parts
351
     * @param array $substitutions
352
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
353
     */
354 19
    private function missingParameters(array $parts, array $substitutions): array
355
    {
356 19
        $missingParameters = [];
357
358
        // Gather required parameters
359 19
        foreach ($parts as $part) {
360 19
            if (is_string($part)) {
361 19
                continue;
362
            }
363
364 9
            $missingParameters[] = $part[0];
365
        }
366
367
        // Check if all parameters exist
368 19
        foreach ($missingParameters as $parameter) {
369 9
            if (!array_key_exists($parameter, $substitutions)) {
370
                // Return the parameters so they can be used in an
371
                // exception if needed
372 3
                return $missingParameters;
373
            }
374
        }
375
376
        // All required parameters are available
377 17
        return [];
378
    }
379
380
    /**
381
     * Retrieve the dispatcher instance.
382
     *
383
     * Uses the callable factory in $dispatcherCallback, passing it $data
384
     * (which should be derived from the router's getData() method); this
385
     * approach is done to allow testing against the dispatcher.
386
     *
387
     * @param array|object $data Data from RouteCollection::getData()
388
     * @return Dispatcher
389
     */
390 5
    private function getDispatcher($data): Dispatcher
391
    {
392 5
        if (!$this->dispatcherCallback) {
393
            $this->dispatcherCallback = $this->createDispatcherCallback();
394
        }
395
396 5
        $factory = $this->dispatcherCallback;
397
398 5
        return $factory($data);
399
    }
400
401
    /**
402
     * Return a default implementation of a callback that can return a Dispatcher.
403
     */
404
    private function createDispatcherCallback(): callable
405
    {
406
        return static function ($data) {
407
            return new GroupCountBased($data);
408
        };
409
    }
410
411
    /**
412
     * Marshal a routing failure result.
413
     *
414
     * If the failure was due to the HTTP method, passes the allowed HTTP
415
     * methods to the factory.
416
     * @param array $result
417
     * @return MatchingResult
418
     */
419
    private function marshalFailedRoute(array $result): MatchingResult
420
    {
421
        $resultCode = $result[0];
422
        if ($resultCode === Dispatcher::METHOD_NOT_ALLOWED) {
423
            return MatchingResult::fromFailure($result[1]);
424
        }
425
426
        return MatchingResult::fromFailure(Method::ANY);
427
    }
428
429
    /**
430
     * Marshals a route result based on the results of matching and the current HTTP method.
431
     * @param array $result
432
     * @param string $method
433
     * @return MatchingResult
434
     */
435 5
    private function marshalMatchedRoute(array $result, string $method): MatchingResult
436
    {
437 5
        [, $path, $parameters] = $result;
438
439
        /* @var Route $route */
440 5
        $route = array_reduce(
441 5
            $this->routes,
442 5
            static function ($matched, Route $route) use ($path, $method) {
443 5
                if ($matched) {
444
                    return $matched;
445
                }
446
447 5
                if ($path !== $route->getPattern()) {
448
                    return $matched;
449
                }
450
451 5
                if (!in_array($method, $route->getMethods(), true)) {
452
                    return $matched;
453
                }
454
455 5
                return $route;
456 5
            },
457 5
            false
458
        );
459
460 5
        if (false === $route) {
0 ignored issues
show
introduced by
The condition false === $route is always false.
Loading history...
461
            return $this->marshalMethodNotAllowedResult($result);
462
        }
463
464 5
        $parameters = array_merge($route->getDefaults(), $parameters);
465 5
        $this->currentRoute = $route;
466
467 5
        return MatchingResult::fromSuccess($route, $parameters);
468
    }
469
470
    /**
471
     * Inject queued items into the underlying router
472
     */
473 21
    private function injectItems(): void
474
    {
475 21
        foreach ($this->items as $index => $item) {
476 21
            $this->injectItem($item);
477 21
            unset($this->items[$index]);
478
        }
479
    }
480
481
    /**
482
     * Inject an item into the underlying router
483
     * @param Route|Group $route
484
     */
485 21
    private function injectItem($route): void
486
    {
487 21
        if ($route instanceof Group) {
488 2
            $this->injectGroup($route);
489 2
            return;
490
        }
491
492
        // Filling the routes' hash-map is required by the `generateUri` method
493 19
        $this->routes[$route->getName()] = $route;
494
495
        // Skip feeding FastRoute collector if valid cached data was already loaded
496 19
        if ($this->hasCache) {
497
            return;
498
        }
499
500 19
        $this->router->addRoute($route->getMethods(), $route->getPattern(), $route->getPattern());
501
    }
502
503
    /**
504
     * Inject a Group instance into the underlying router.
505
     */
506 2
    private function injectGroup(Group $group, RouteCollector $collector = null, string $prefix = ''): void
507
    {
508 2
        if ($collector === null) {
509 2
            $collector = $this->router;
510
        }
511
512 2
        $collector->addGroup(
513 2
            $group->getPrefix(),
514 2
            function (RouteCollector $r) use ($group, $prefix) {
515 2
                $prefix .= $group->getPrefix();
516 2
                foreach ($group->items as $index => $item) {
517 2
                    if ($item instanceof Group) {
518 1
                        $this->injectGroup($item, $r, $prefix);
519 1
                        continue;
520
                    }
521
522
                    /** @var Route $modifiedItem */
523 2
                    $modifiedItem = $item->pattern($prefix . $item->getPattern());
524
525 2
                    $groupMiddlewares = $group->getMiddlewares();
526
527 2
                    for (end($groupMiddlewares); key($groupMiddlewares) !== null; prev($groupMiddlewares)) {
528
                        $modifiedItem = $modifiedItem->addMiddleware(current($groupMiddlewares));
529
                    }
530
531
                    // Filling the routes' hash-map is required by the `generateUri` method
532 2
                    $this->routes[$modifiedItem->getName()] = $modifiedItem;
533
534
                    // Skip feeding FastRoute collector if valid cached data was already loaded
535 2
                    if ($this->hasCache) {
536
                        continue;
537
                    }
538
539 2
                    $r->addRoute($item->getMethods(), $item->getPattern(), $modifiedItem->getPattern());
540
                }
541 2
            }
542
        );
543
    }
544
545
    /**
546
     * Get the dispatch data either from cache or freshly generated by the
547
     * FastRoute data generator.
548
     *
549
     * If caching is enabled, store the freshly generated data to file.
550
     */
551 5
    private function getDispatchData(): array
552
    {
553 5
        if ($this->hasCache) {
554
            return $this->dispatchData;
555
        }
556
557 5
        $dispatchData = (array)$this->router->getData();
558
559 5
        if ($this->cacheEnabled) {
560
            $this->cacheDispatchData($dispatchData);
561
        }
562
563 5
        return $dispatchData;
564
    }
565
566
    /**
567
     * Load dispatch data from cache
568
     * @throws \RuntimeException If the cache file contains invalid data
569
     */
570
    private function loadDispatchData(): void
571
    {
572
        set_error_handler(
573
            static function () {
574
            },
575
            E_WARNING
576
        ); // suppress php warnings
577
        $dispatchData = include $this->cacheFile;
578
        restore_error_handler();
579
580
        // Cache file does not exist
581
        if (false === $dispatchData) {
582
            return;
583
        }
584
585
        if (!is_array($dispatchData)) {
586
            throw new \RuntimeException(
587
                sprintf(
588
                    'Invalid cache file "%s"; cache file MUST return an array',
589
                    $this->cacheFile
590
                )
591
            );
592
        }
593
594
        $this->hasCache = true;
595
        $this->dispatchData = $dispatchData;
596
    }
597
598
    /**
599
     * Save dispatch data to cache
600
     * @param array $dispatchData
601
     * @return int|false bytes written to file or false if error
602
     * @throws \RuntimeException If the cache directory does not exist.
603
     * @throws \RuntimeException If the cache directory is not writable.
604
     * @throws \RuntimeException If the cache file exists but is not writable
605
     */
606
    private function cacheDispatchData(array $dispatchData)
607
    {
608
        $cacheDir = dirname($this->cacheFile);
609
610
        if (!is_dir($cacheDir)) {
611
            throw new \RuntimeException(
612
                sprintf(
613
                    'The cache directory "%s" does not exist',
614
                    $cacheDir
615
                )
616
            );
617
        }
618
619
        if (!is_writable($cacheDir)) {
620
            throw new \RuntimeException(
621
                sprintf(
622
                    'The cache directory "%s" is not writable',
623
                    $cacheDir
624
                )
625
            );
626
        }
627
628
        if (file_exists($this->cacheFile) && !is_writable($this->cacheFile)) {
629
            throw new \RuntimeException(
630
                sprintf(
631
                    'The cache file %s is not writable',
632
                    $this->cacheFile
633
                )
634
            );
635
        }
636
637
        return file_put_contents(
638
            $this->cacheFile,
639
            sprintf(self::CACHE_TEMPLATE, var_export($dispatchData, true)),
640
            LOCK_EX
641
        );
642
    }
643
644
    private function marshalMethodNotAllowedResult(array $result): MatchingResult
645
    {
646
        $path = $result[1];
647
648
        $allowedMethods = array_unique(
649
            array_reduce(
650
                $this->routes,
651
                static function ($allowedMethods, Route $route) use ($path) {
652
                    if ($path !== $route->getPattern()) {
653
                        return $allowedMethods;
654
                    }
655
656
                    return array_merge($allowedMethods, $route->getMethods());
657
                },
658
                []
659
            )
660
        );
661
662
        return MatchingResult::fromFailure($allowedMethods);
663
    }
664
665
    /**
666
     * @param string $name
667
     * @return Route
668
     */
669 20
    private function getRoute(string $name): Route
670
    {
671 20
        if (!array_key_exists($name, $this->routes)) {
672 1
            throw new RouteNotFoundException($name);
673
        }
674
675 19
        return $this->routes[$name];
676
    }
677
678
    /**
679
     * @param array $parameters
680
     * @param array $parts
681
     * @return string
682
     */
683 17
    private function generatePath(array $parameters, array $parts): string
684
    {
685 17
        $notSubstitutedParams = $parameters;
686 17
        $path = $this->getUriPrefix();
687
688 17
        foreach ($parts as $part) {
689 17
            if (is_string($part)) {
690
                // Append the string
691 17
                $path .= $part;
692 17
                continue;
693
            }
694
695
            // Check substitute value with regex
696 6
            $pattern = str_replace('~', '\~', $part[1]);
697 6
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
698 1
                throw new \RuntimeException(
699 1
                    sprintf(
700 1
                        'Parameter value for [%s] did not match the regex `%s`',
701 1
                        $part[0],
702 1
                        $part[1]
703
                    )
704
                );
705
            }
706
707
            // Append the substituted value
708 5
            $path .= $parameters[$part[0]];
709 5
            unset($notSubstitutedParams[$part[0]]);
710
        }
711
712 16
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
713
    }
714
}
715