Passed
Push — master ( 251776...0d70ac )
by Alexander
12:13 queued 10:43
created

FastRoute::generateAbsolute()   C

Complexity

Conditions 15
Paths 32

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 15

Importance

Changes 0
Metric Value
cc 15
eloc 14
c 0
b 0
f 0
nc 32
nop 4
dl 0
loc 24
rs 5.9166
ccs 15
cts 15
cp 1
crap 15

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 27
    public function __construct(
150
        RouteCollector $router,
151
        RouteParser $routeParser,
152
        callable $dispatcherFactory = null,
153
        array $config = null
154
    ) {
155 27
        $this->router = $router;
156 27
        $this->dispatcherCallback = $dispatcherFactory;
157 27
        $this->routeParser = $routeParser;
158
159 27
        $this->loadConfig($config);
160
    }
161
162
    /**
163
     * Load configuration parameters
164
     *
165
     * @param null|array $config Array of custom configuration options.
166
     */
167 27
    private function loadConfig(array $config = null): void
168
    {
169 27
        if (null === $config) {
170 27
            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 9
    public function match(ServerRequestInterface $request): MatchingResult
187
    {
188 9
        $this->request = $request;
189
        // Inject any pending route items
190 9
        $this->injectItems();
191
192 9
        $dispatchData = $this->getDispatchData();
193 9
        $path = rawurldecode($request->getUri()->getPath());
194 9
        $method = $request->getMethod();
195 9
        $result = $this->getDispatcher($dispatchData)->dispatch($method, $path);
196
197 9
        return $result[0] !== Dispatcher::FOUND
198
            ? $this->marshalFailedRoute($result)
199 9
            : $this->marshalMatchedRoute($result, $method);
200
    }
201
202 23
    public function getUriPrefix(): string
203
    {
204 23
        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 26
    public function generate(string $name, array $parameters = []): string
228
    {
229
        // Inject any pending route items
230 26
        $this->injectItems();
231
232 26
        $route = $this->getRoute($name);
233
234 25
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getPattern()));
235 25
        if ($parsedRoutes === []) {
236
            throw new RouteNotFoundException($name);
237
        }
238
239 25
        $missingParameters = [];
240
241
        // One route pattern can correspond to multiple routes if it has optional parts
242 25
        foreach ($parsedRoutes as $parsedRouteParts) {
243
            // Check if all parameters can be substituted
244 25
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
245
246
            // If not all parameters can be substituted, try the next route
247 25
            if (!empty($missingParameters)) {
248 3
                continue;
249
            }
250
251 23
            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 15
    public function generateAbsolute(string $name, array $parameters = [], string $scheme = null, string $host = null): string
274
    {
275 15
        $url = $this->generate($name, $parameters);
276 15
        $route = $this->getRoute($name);
277 15
        $uri = $this->request !== null ? $this->request->getUri() : null;
278 15
        $lastRequestScheme = $uri !== null ? $uri->getScheme() : null;
279
280 15
        if ($host !== null || ($host = $route->getHost()) !== null) {
281 10
            if ($scheme === null && (strpos($host, '://') !== false || strpos($host, '//') === 0)) {
282 6
                return rtrim($host, '/') . $url;
283
            }
284
285 4
            if ($scheme === '' && $host !== '' && !(strpos($host, '://') !== false || strpos($host, '//') === 0)) {
286 2
                $host = '//' . $host;
287
            }
288 4
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
289
        }
290
291 5
        if ($uri !== null) {
292 4
            $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
293 4
            return  $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $lastRequestScheme);
294
        }
295
296 1
        return $url;
297
    }
298
299
    /**
300
     * Normalize URL by ensuring that it use specified scheme.
301
     *
302
     * If URL is relative or scheme is null, normalization is skipped.
303
     *
304
     * @param string $url the URL to process
305
     * @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
306
     * create protocol-relative URL (e.g. `//example.com/path`)
307
     * @return string the processed URL
308
     */
309 8
    private function ensureScheme(string $url, ?string $scheme): string
310
    {
311 8
        if ($scheme === null || $this->isRelative($url)) {
312
            return $url;
313
        }
314
315 8
        if (strpos($url, '//') === 0) {
316
            // e.g. //example.com/path/to/resource
317 2
            return $scheme === '' ? $url : "$scheme:$url";
318
        }
319
320 8
        if (($pos = strpos($url, '://')) !== false) {
321 8
            if ($scheme === '') {
322 3
                $url = substr($url, $pos + 1);
323
            } else {
324 5
                $url = $scheme . substr($url, $pos);
325
            }
326
        }
327
328 8
        return $url;
329
    }
330
331
    /**
332
     * Returns a value indicating whether a URL is relative.
333
     * A relative URL does not have host info part.
334
     * @param string $url the URL to be checked
335
     * @return bool whether the URL is relative
336
     */
337 8
    private function isRelative(string $url): bool
338
    {
339 8
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
340
    }
341
342
    /**
343
     * Returns the current Route object
344
     * @return Route|null current route
345
     */
346
    public function getCurrentRoute(): ?Route
347
    {
348
        return $this->currentRoute;
349
    }
350
351
    /**
352
     * Checks for any missing route parameters
353
     * @param array $parts
354
     * @param array $substitutions
355
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
356
     */
357 25
    private function missingParameters(array $parts, array $substitutions): array
358
    {
359 25
        $missingParameters = [];
360
361
        // Gather required parameters
362 25
        foreach ($parts as $part) {
363 25
            if (is_string($part)) {
364 25
                continue;
365
            }
366
367 9
            $missingParameters[] = $part[0];
368
        }
369
370
        // Check if all parameters exist
371 25
        foreach ($missingParameters as $parameter) {
372 9
            if (!array_key_exists($parameter, $substitutions)) {
373
                // Return the parameters so they can be used in an
374
                // exception if needed
375 3
                return $missingParameters;
376
            }
377
        }
378
379
        // All required parameters are available
380 23
        return [];
381
    }
382
383
    /**
384
     * Retrieve the dispatcher instance.
385
     *
386
     * Uses the callable factory in $dispatcherCallback, passing it $data
387
     * (which should be derived from the router's getData() method); this
388
     * approach is done to allow testing against the dispatcher.
389
     *
390
     * @param array|object $data Data from RouteCollection::getData()
391
     * @return Dispatcher
392
     */
393 9
    private function getDispatcher($data): Dispatcher
394
    {
395 9
        if (!$this->dispatcherCallback) {
396
            $this->dispatcherCallback = $this->createDispatcherCallback();
397
        }
398
399 9
        $factory = $this->dispatcherCallback;
400
401 9
        return $factory($data);
402
    }
403
404
    /**
405
     * Return a default implementation of a callback that can return a Dispatcher.
406
     */
407
    private function createDispatcherCallback(): callable
408
    {
409
        return static function ($data) {
410
            return new GroupCountBased($data);
411
        };
412
    }
413
414
    /**
415
     * Marshal a routing failure result.
416
     *
417
     * If the failure was due to the HTTP method, passes the allowed HTTP
418
     * methods to the factory.
419
     * @param array $result
420
     * @return MatchingResult
421
     */
422
    private function marshalFailedRoute(array $result): MatchingResult
423
    {
424
        $resultCode = $result[0];
425
        if ($resultCode === Dispatcher::METHOD_NOT_ALLOWED) {
426
            return MatchingResult::fromFailure($result[1]);
427
        }
428
429
        return MatchingResult::fromFailure(Method::ANY);
430
    }
431
432
    /**
433
     * Marshals a route result based on the results of matching and the current HTTP method.
434
     * @param array $result
435
     * @param string $method
436
     * @return MatchingResult
437
     */
438 9
    private function marshalMatchedRoute(array $result, string $method): MatchingResult
439
    {
440 9
        [, $path, $parameters] = $result;
441
442
        /* @var Route $route */
443 9
        $route = array_reduce(
444 9
            $this->routes,
445 9
            static function ($matched, Route $route) use ($path, $method) {
446 9
                if ($matched) {
447 1
                    return $matched;
448
                }
449
450 9
                if ($path !== $route->getPattern()) {
451
                    return $matched;
452
                }
453
454 9
                if (!in_array($method, $route->getMethods(), true)) {
455
                    return $matched;
456
                }
457
458 9
                return $route;
459 9
            },
460 9
            false
461
        );
462
463 9
        if (false === $route) {
0 ignored issues
show
introduced by
The condition false === $route is always false.
Loading history...
464
            return $this->marshalMethodNotAllowedResult($result);
465
        }
466
467 9
        $parameters = array_merge($route->getDefaults(), $parameters);
468 9
        $this->currentRoute = $route;
469
470 9
        return MatchingResult::fromSuccess($route, $parameters);
471
    }
472
473
    /**
474
     * Inject queued items into the underlying router
475
     */
476 27
    private function injectItems(): void
477
    {
478 27
        foreach ($this->items as $index => $item) {
479 27
            $this->injectItem($item);
480 27
            unset($this->items[$index]);
481
        }
482
    }
483
484
    /**
485
     * Inject an item into the underlying router
486
     * @param Route|Group $route
487
     */
488 27
    private function injectItem($route): void
489
    {
490 27
        if ($route instanceof Group) {
491 2
            $this->injectGroup($route);
492 2
            return;
493
        }
494
495
        // Filling the routes' hash-map is required by the `generateUri` method
496 25
        $this->routes[$route->getName()] = $route;
497
498
        // Skip feeding FastRoute collector if valid cached data was already loaded
499 25
        if ($this->hasCache) {
500
            return;
501
        }
502
503 25
        $this->router->addRoute($route->getMethods(), $route->getPattern(), $route->getPattern());
504
    }
505
506
    /**
507
     * Inject a Group instance into the underlying router.
508
     */
509 2
    private function injectGroup(Group $group, RouteCollector $collector = null, string $prefix = ''): void
510
    {
511 2
        if ($collector === null) {
512 2
            $collector = $this->router;
513
        }
514
515 2
        $collector->addGroup(
516 2
            $group->getPrefix(),
517 2
            function (RouteCollector $r) use ($group, $prefix) {
518 2
                $prefix .= $group->getPrefix();
519 2
                foreach ($group->items as $index => $item) {
520 2
                    if ($item instanceof Group) {
521 1
                        $this->injectGroup($item, $r, $prefix);
522 1
                        continue;
523
                    }
524
525
                    /** @var Route $modifiedItem */
526 2
                    $modifiedItem = $item->pattern($prefix . $item->getPattern());
527
528 2
                    $groupMiddlewares = $group->getMiddlewares();
529
530 2
                    for (end($groupMiddlewares); key($groupMiddlewares) !== null; prev($groupMiddlewares)) {
531
                        $modifiedItem = $modifiedItem->addMiddleware(current($groupMiddlewares));
532
                    }
533
534
                    // Filling the routes' hash-map is required by the `generateUri` method
535 2
                    $this->routes[$modifiedItem->getName()] = $modifiedItem;
536
537
                    // Skip feeding FastRoute collector if valid cached data was already loaded
538 2
                    if ($this->hasCache) {
539
                        continue;
540
                    }
541
542 2
                    $r->addRoute($item->getMethods(), $item->getPattern(), $modifiedItem->getPattern());
543
                }
544 2
            }
545
        );
546
    }
547
548
    /**
549
     * Get the dispatch data either from cache or freshly generated by the
550
     * FastRoute data generator.
551
     *
552
     * If caching is enabled, store the freshly generated data to file.
553
     */
554 9
    private function getDispatchData(): array
555
    {
556 9
        if ($this->hasCache) {
557
            return $this->dispatchData;
558
        }
559
560 9
        $dispatchData = (array)$this->router->getData();
561
562 9
        if ($this->cacheEnabled) {
563
            $this->cacheDispatchData($dispatchData);
564
        }
565
566 9
        return $dispatchData;
567
    }
568
569
    /**
570
     * Load dispatch data from cache
571
     * @throws \RuntimeException If the cache file contains invalid data
572
     */
573
    private function loadDispatchData(): void
574
    {
575
        set_error_handler(
576
            static function () {
577
            },
578
            E_WARNING
579
        ); // suppress php warnings
580
        $dispatchData = include $this->cacheFile;
581
        restore_error_handler();
582
583
        // Cache file does not exist
584
        if (false === $dispatchData) {
585
            return;
586
        }
587
588
        if (!is_array($dispatchData)) {
589
            throw new \RuntimeException(
590
                sprintf(
591
                    'Invalid cache file "%s"; cache file MUST return an array',
592
                    $this->cacheFile
593
                )
594
            );
595
        }
596
597
        $this->hasCache = true;
598
        $this->dispatchData = $dispatchData;
599
    }
600
601
    /**
602
     * Save dispatch data to cache
603
     * @param array $dispatchData
604
     * @return int|false bytes written to file or false if error
605
     * @throws \RuntimeException If the cache directory does not exist.
606
     * @throws \RuntimeException If the cache directory is not writable.
607
     * @throws \RuntimeException If the cache file exists but is not writable
608
     */
609
    private function cacheDispatchData(array $dispatchData)
610
    {
611
        $cacheDir = dirname($this->cacheFile);
612
613
        if (!is_dir($cacheDir)) {
614
            throw new \RuntimeException(
615
                sprintf(
616
                    'The cache directory "%s" does not exist',
617
                    $cacheDir
618
                )
619
            );
620
        }
621
622
        if (!is_writable($cacheDir)) {
623
            throw new \RuntimeException(
624
                sprintf(
625
                    'The cache directory "%s" is not writable',
626
                    $cacheDir
627
                )
628
            );
629
        }
630
631
        if (file_exists($this->cacheFile) && !is_writable($this->cacheFile)) {
632
            throw new \RuntimeException(
633
                sprintf(
634
                    'The cache file %s is not writable',
635
                    $this->cacheFile
636
                )
637
            );
638
        }
639
640
        return file_put_contents(
641
            $this->cacheFile,
642
            sprintf(self::CACHE_TEMPLATE, var_export($dispatchData, true)),
643
            LOCK_EX
644
        );
645
    }
646
647
    private function marshalMethodNotAllowedResult(array $result): MatchingResult
648
    {
649
        $path = $result[1];
650
651
        $allowedMethods = array_unique(
652
            array_reduce(
653
                $this->routes,
654
                static function ($allowedMethods, Route $route) use ($path) {
655
                    if ($path !== $route->getPattern()) {
656
                        return $allowedMethods;
657
                    }
658
659
                    return array_merge($allowedMethods, $route->getMethods());
660
                },
661
                []
662
            )
663
        );
664
665
        return MatchingResult::fromFailure($allowedMethods);
666
    }
667
668
    /**
669
     * @param string $name
670
     * @return Route
671
     */
672 26
    private function getRoute(string $name): Route
673
    {
674 26
        if (!array_key_exists($name, $this->routes)) {
675 1
            throw new RouteNotFoundException($name);
676
        }
677
678 25
        return $this->routes[$name];
679
    }
680
681
    /**
682
     * @param array $parameters
683
     * @param array $parts
684
     * @return string
685
     */
686 23
    private function generatePath(array $parameters, array $parts): string
687
    {
688 23
        $notSubstitutedParams = $parameters;
689 23
        $path = $this->getUriPrefix();
690
691 23
        foreach ($parts as $part) {
692 23
            if (is_string($part)) {
693
                // Append the string
694 23
                $path .= $part;
695 23
                continue;
696
            }
697
698
            // Check substitute value with regex
699 6
            $pattern = str_replace('~', '\~', $part[1]);
700 6
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
701 1
                throw new \RuntimeException(
702 1
                    sprintf(
703 1
                        'Parameter value for [%s] did not match the regex `%s`',
704 1
                        $part[0],
705 1
                        $part[1]
706
                    )
707
                );
708
            }
709
710
            // Append the substituted value
711 5
            $path .= $parameters[$part[0]];
712 5
            unset($notSubstitutedParams[$part[0]]);
713
        }
714
715 22
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
716
    }
717
}
718