Passed
Push — master ( 87e9f7...24047f )
by Alexander
01:12
created

FastRoute::injectItem()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 16
ccs 7
cts 8
cp 0.875
crap 3.0175
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
     * Constructor
125
     *
126
     * Accepts optionally a FastRoute RouteCollector and a callable factory
127
     * that can return a FastRoute dispatcher.
128
     *
129
     * If either is not provided defaults will be used:
130
     *
131
     * - A RouteCollector instance will be created composing a RouteParser and
132
     *   RouteGenerator.
133
     * - A callable that returns a GroupCountBased dispatcher will be created.
134
     *
135
     * @param null|RouteCollector $router If not provided, a default
136
     *     implementation will be used.
137
     * @param RouteParser $routeParser
138
     * @param null|callable $dispatcherFactory Callable that will return a
139
     *     FastRoute dispatcher.
140
     * @param array $config Array of custom configuration options.
141
     */
142 10
    public function __construct(
143
        RouteCollector $router,
144
        RouteParser $routeParser,
145
        callable $dispatcherFactory = null,
146
        array $config = null
147
    ) {
148 10
        $this->router = $router;
149 10
        $this->dispatcherCallback = $dispatcherFactory;
150 10
        $this->routeParser = $routeParser;
151
152 10
        $this->loadConfig($config);
153
    }
154
155
    /**
156
     * Load configuration parameters
157
     *
158
     * @param null|array $config Array of custom configuration options.
159
     */
160 10
    private function loadConfig(array $config = null): void
161
    {
162 10
        if (null === $config) {
163 10
            return;
164
        }
165
166
        if (isset($config[self::CONFIG_CACHE_ENABLED])) {
167
            $this->cacheEnabled = (bool)$config[self::CONFIG_CACHE_ENABLED];
168
        }
169
170
        if (isset($config[self::CONFIG_CACHE_FILE])) {
171
            $this->cacheFile = (string)$config[self::CONFIG_CACHE_FILE];
172
        }
173
174
        if ($this->cacheEnabled) {
175
            $this->loadDispatchData();
176
        }
177
    }
178
179 1
    public function match(ServerRequestInterface $request): MatchingResult
180
    {
181
        // Inject any pending route items
182 1
        $this->injectItems();
183
184 1
        $dispatchData = $this->getDispatchData();
185 1
        $path = rawurldecode($request->getUri()->getPath());
186 1
        $method = $request->getMethod();
187 1
        $result = $this->getDispatcher($dispatchData)->dispatch($method, $path);
188
189 1
        return $result[0] !== Dispatcher::FOUND
190
            ? $this->marshalFailedRoute($result)
191 1
            : $this->marshalMatchedRoute($result, $method);
192
    }
193
194 6
    public function getUriPrefix(): string
195
    {
196 6
        return $this->uriPrefix;
197
    }
198
199
    public function setUriPrefix(string $prefix): void
200
    {
201
        $this->uriPrefix = $prefix;
202
    }
203
204
    /**
205
     * Generate a URI based on a given route.
206
     *
207
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
208
     * this method uses `FastRoute\RouteParser\Std` to search for the best route
209
     * match based on the available substitutions and generates a uri.
210
     *
211
     * @param string $name Route name.
212
     * @param array $parameters Key/value option pairs to pass to the router for
213
     * purposes of generating a URI; takes precedence over options present
214
     * in route used to generate URI.
215
     *
216
     * @return string URI path generated.
217
     * @throws \RuntimeException if the route name is not known or a parameter value does not match its regex.
218
     */
219 9
    public function generate(string $name, array $parameters = []): string
220
    {
221
        // Inject any pending route items
222 9
        $this->injectItems();
223
224 9
        $route = $this->getRoute($name);
225
226 8
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getPattern()));
227 8
        if ($parsedRoutes === []) {
228
            throw new RouteNotFoundException($name);
229
        }
230
231 8
        $missingParameters = [];
232
233
        // One route pattern can correspond to multiple routes if it has optional parts
234 8
        foreach ($parsedRoutes as $parsedRouteParts) {
235
            // Check if all parameters can be substituted
236 8
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
237
238
            // If not all parameters can be substituted, try the next route
239 8
            if (!empty($missingParameters)) {
240 3
                continue;
241
            }
242
243 6
            return $this->generatePath($parameters, $parsedRouteParts);
244
        }
245
246
        // No valid route was found: list minimal required parameters
247 2
        throw new \RuntimeException(sprintf(
248 2
            'Route `%s` expects at least parameter values for [%s], but received [%s]',
249 2
            $name,
250 2
            implode(',', $missingParameters),
251 2
            implode(',', array_keys($parameters))
252
        ));
253
    }
254
255
    /**
256
     * Returns the current Route object
257
     * @return Route|null current route
258
     */
259
    public function getCurrentRoute(): ?Route
260
    {
261
        return $this->currentRoute;
262
    }
263
264
    /**
265
     * Checks for any missing route parameters
266
     * @param array $parts
267
     * @param array $substitutions
268
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
269
     */
270 8
    private function missingParameters(array $parts, array $substitutions): array
271
    {
272 8
        $missingParameters = [];
273
274
        // Gather required parameters
275 8
        foreach ($parts as $part) {
276 8
            if (is_string($part)) {
277 8
                continue;
278
            }
279
280 7
            $missingParameters[] = $part[0];
281
        }
282
283
        // Check if all parameters exist
284 8
        foreach ($missingParameters as $parameter) {
285 7
            if (!array_key_exists($parameter, $substitutions)) {
286
                // Return the parameters so they can be used in an
287
                // exception if needed
288 3
                return $missingParameters;
289
            }
290
        }
291
292
        // All required parameters are available
293 6
        return [];
294
    }
295
296
    /**
297
     * Retrieve the dispatcher instance.
298
     *
299
     * Uses the callable factory in $dispatcherCallback, passing it $data
300
     * (which should be derived from the router's getData() method); this
301
     * approach is done to allow testing against the dispatcher.
302
     *
303
     * @param array|object $data Data from RouteCollection::getData()
304
     * @return Dispatcher
305
     */
306 1
    private function getDispatcher($data): Dispatcher
307
    {
308 1
        if (!$this->dispatcherCallback) {
309
            $this->dispatcherCallback = $this->createDispatcherCallback();
310
        }
311
312 1
        $factory = $this->dispatcherCallback;
313
314 1
        return $factory($data);
315
    }
316
317
    /**
318
     * Return a default implementation of a callback that can return a Dispatcher.
319
     */
320
    private function createDispatcherCallback(): callable
321
    {
322
        return static function ($data) {
323
            return new GroupCountBased($data);
324
        };
325
    }
326
327
    /**
328
     * Marshal a routing failure result.
329
     *
330
     * If the failure was due to the HTTP method, passes the allowed HTTP
331
     * methods to the factory.
332
     * @param array $result
333
     * @return MatchingResult
334
     */
335
    private function marshalFailedRoute(array $result): MatchingResult
336
    {
337
        $resultCode = $result[0];
338
        if ($resultCode === Dispatcher::METHOD_NOT_ALLOWED) {
339
            return MatchingResult::fromFailure($result[1]);
340
        }
341
342
        return MatchingResult::fromFailure(Method::ANY);
343
    }
344
345
    /**
346
     * Marshals a route result based on the results of matching and the current HTTP method.
347
     * @param array $result
348
     * @param string $method
349
     * @return MatchingResult
350
     */
351 1
    private function marshalMatchedRoute(array $result, string $method): MatchingResult
352
    {
353 1
        [, $path, $parameters] = $result;
354
355
        /* @var Route $route */
356 1
        $route = array_reduce(
357 1
            $this->routes,
358
            static function ($matched, Route $route) use ($path, $method) {
359 1
                if ($matched) {
360
                    return $matched;
361
                }
362
363 1
                if ($path !== $route->getPattern()) {
364
                    return $matched;
365
                }
366
367 1
                if (!in_array($method, $route->getMethods(), true)) {
368
                    return $matched;
369
                }
370
371 1
                return $route;
372 1
            },
373 1
            false
374
        );
375
376 1
        if (false === $route) {
0 ignored issues
show
introduced by
The condition false === $route is always false.
Loading history...
377
            return $this->marshalMethodNotAllowedResult($result);
378
        }
379
380 1
        $parameters = array_merge($route->getDefaults(), $parameters);
381 1
        $this->currentRoute = $route;
382
383 1
        return MatchingResult::fromSuccess($route, $parameters);
384
    }
385
386
    /**
387
     * Inject queued items into the underlying router
388
     */
389 10
    private function injectItems(): void
390
    {
391 10
        foreach ($this->items as $index => $item) {
392 10
            $this->injectItem($item);
393 10
            unset($this->items[$index]);
394
        }
395
    }
396
397
    /**
398
     * Inject an item into the underlying router
399
     * @param Route|Group $route
400
     */
401 10
    private function injectItem($route): void
402
    {
403 10
        if ($route instanceof Group) {
404 1
            $this->injectGroup($route);
405 1
            return;
406
        }
407
408
        // Filling the routes' hash-map is required by the `generateUri` method
409 9
        $this->routes[$route->getName()] = $route;
410
411
        // Skip feeding FastRoute collector if valid cached data was already loaded
412 9
        if ($this->hasCache) {
413
            return;
414
        }
415
416 9
        $this->router->addRoute($route->getMethods(), $route->getPattern(), $route->getPattern());
417
    }
418
419
    /**
420
     * Inject a Group instance into the underlying router.
421
     */
422 1
    private function injectGroup(Group $group, RouteCollector $collector = null): void
423
    {
424 1
        if ($collector === null) {
425 1
            $collector = $this->router;
426
        }
427 1
        $collector->addGroup(
428 1
            $group->getPrefix(),
429
            function (RouteCollector $r) use ($group) {
430 1
                foreach ($group->items as $index => $item) {
431 1
                    if ($item instanceof Group) {
432
                        $this->injectGroup($item, $r);
433
                        continue;
434
                    }
435
436
                    /** @var Route $modifiedItem */
437 1
                    $modifiedItem = $item->pattern($group->getPrefix() . $item->getPattern());
438 1
                    $groupMiddlewares = $group->getMiddlewares();
439
440 1
                    for (end($groupMiddlewares); key($groupMiddlewares) !== null; prev($groupMiddlewares)) {
441
                        $modifiedItem = $modifiedItem->addMiddleware(current($groupMiddlewares));
442
                    }
443
444
                    // Filling the routes' hash-map is required by the `generateUri` method
445 1
                    $this->routes[$modifiedItem->getName()] = $modifiedItem;
446
447
                    // Skip feeding FastRoute collector if valid cached data was already loaded
448 1
                    if ($this->hasCache) {
449
                        continue;
450
                    }
451
452 1
                    $r->addRoute($item->getMethods(), $item->getPattern(), $modifiedItem->getPattern());
453
                }
454 1
            }
455
        );
456
    }
457
458
    /**
459
     * Get the dispatch data either from cache or freshly generated by the
460
     * FastRoute data generator.
461
     *
462
     * If caching is enabled, store the freshly generated data to file.
463
     */
464 1
    private function getDispatchData(): array
465
    {
466 1
        if ($this->hasCache) {
467
            return $this->dispatchData;
468
        }
469
470 1
        $dispatchData = (array)$this->router->getData();
471
472 1
        if ($this->cacheEnabled) {
473
            $this->cacheDispatchData($dispatchData);
474
        }
475
476 1
        return $dispatchData;
477
    }
478
479
    /**
480
     * Load dispatch data from cache
481
     * @throws \RuntimeException If the cache file contains invalid data
482
     */
483
    private function loadDispatchData(): void
484
    {
485
        set_error_handler(
486
            static function () {
487
            },
488
            E_WARNING
489
        ); // suppress php warnings
490
        $dispatchData = include $this->cacheFile;
491
        restore_error_handler();
492
493
        // Cache file does not exist
494
        if (false === $dispatchData) {
495
            return;
496
        }
497
498
        if (!is_array($dispatchData)) {
499
            throw new \RuntimeException(
500
                sprintf(
501
                    'Invalid cache file "%s"; cache file MUST return an array',
502
                    $this->cacheFile
503
                )
504
            );
505
        }
506
507
        $this->hasCache = true;
508
        $this->dispatchData = $dispatchData;
509
    }
510
511
    /**
512
     * Save dispatch data to cache
513
     * @param array $dispatchData
514
     * @return int|false bytes written to file or false if error
515
     * @throws \RuntimeException If the cache directory does not exist.
516
     * @throws \RuntimeException If the cache directory is not writable.
517
     * @throws \RuntimeException If the cache file exists but is not writable
518
     */
519
    private function cacheDispatchData(array $dispatchData)
520
    {
521
        $cacheDir = dirname($this->cacheFile);
522
523
        if (!is_dir($cacheDir)) {
524
            throw new \RuntimeException(
525
                sprintf(
526
                    'The cache directory "%s" does not exist',
527
                    $cacheDir
528
                )
529
            );
530
        }
531
532
        if (!is_writable($cacheDir)) {
533
            throw new \RuntimeException(
534
                sprintf(
535
                    'The cache directory "%s" is not writable',
536
                    $cacheDir
537
                )
538
            );
539
        }
540
541
        if (file_exists($this->cacheFile) && !is_writable($this->cacheFile)) {
542
            throw new \RuntimeException(
543
                sprintf(
544
                    'The cache file %s is not writable',
545
                    $this->cacheFile
546
                )
547
            );
548
        }
549
550
        return file_put_contents(
551
            $this->cacheFile,
552
            sprintf(self::CACHE_TEMPLATE, var_export($dispatchData, true)),
553
            LOCK_EX
554
        );
555
    }
556
557
    private function marshalMethodNotAllowedResult(array $result): MatchingResult
558
    {
559
        $path = $result[1];
560
561
        $allowedMethods = array_unique(
562
            array_reduce(
563
                $this->routes,
564
                static function ($allowedMethods, Route $route) use ($path) {
565
                    if ($path !== $route->getPattern()) {
566
                        return $allowedMethods;
567
                    }
568
569
                    return array_merge($allowedMethods, $route->getMethods());
570
                },
571
                []
572
            )
573
        );
574
575
        return MatchingResult::fromFailure($allowedMethods);
576
    }
577
578
    /**
579
     * @param string $name
580
     * @return Route
581
     */
582 9
    private function getRoute(string $name): Route
583
    {
584 9
        if (!array_key_exists($name, $this->routes)) {
585 1
            throw new RouteNotFoundException($name);
586
        }
587
588 8
        return $this->routes[$name];
589
    }
590
591
    /**
592
     * @param array $parameters
593
     * @param array $parts
594
     * @return string
595
     */
596 6
    private function generatePath(array $parameters, array $parts): string
597
    {
598 6
        $path = $this->getUriPrefix();
599 6
        foreach ($parts as $part) {
600 6
            if (is_string($part)) {
601
                // Append the string
602 6
                $path .= $part;
603 6
                continue;
604
            }
605
606
            // Check substitute value with regex
607 4
            $pattern = str_replace('~', '\~', $part[1]);
608 4
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
609 1
                throw new \RuntimeException(
610 1
                    sprintf(
611 1
                        'Parameter value for [%s] did not match the regex `%s`',
612 1
                        $part[0],
613 1
                        $part[1]
614
                    )
615
                );
616
            }
617
618
            // Append the substituted value
619 3
            $path .= $parameters[$part[0]];
620
        }
621
622 5
        return $path;
623
    }
624
}
625