Passed
Push — master ( e19e02...dff518 )
by Alexander
22:52 queued 20:40
created

UrlMatcher::marshalMatchedRoute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 2
dl 0
loc 14
ccs 6
cts 8
cp 0.75
crap 3.1406
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router\FastRoute;
6
7
use FastRoute\DataGenerator\GroupCountBased as RouteGenerator;
8
use FastRoute\Dispatcher;
9
use FastRoute\Dispatcher\GroupCountBased;
10
use FastRoute\RouteCollector;
11
use FastRoute\RouteParser\Std as RouteParser;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\SimpleCache\CacheInterface;
14
use RuntimeException;
15
use Yiisoft\Http\Method;
16
use Yiisoft\Router\MatchingResult;
17
use Yiisoft\Router\Route;
18
use Yiisoft\Router\RouteCollectionInterface;
19
use Yiisoft\Router\RouteParametersInterface;
20
use Yiisoft\Router\UrlMatcherInterface;
21
22
use function array_merge;
23
use function array_reduce;
24
use function array_unique;
25
26
final class UrlMatcher implements UrlMatcherInterface
27
{
28
    /**
29
     * @const string Configuration key used to set the cache file path
30
     */
31
    public const CONFIG_CACHE_KEY = 'cache_key';
32
33
    /**
34
     * @const string Configuration key used to set the cache file path
35
     */
36
    private string $cacheKey = 'routes-cache';
37
38
    /**
39
     * @var callable A factory callback that can return a dispatcher.
40
     */
41
    private $dispatcherCallback;
42
43
    /**
44
     * Cached data used by the dispatcher.
45
     *
46
     * @var array
47
     */
48
    private array $dispatchData = [];
49
50
    /**
51
     * True if cache is enabled and valid dispatch data has been loaded from
52
     * cache.
53
     *
54
     * @var bool
55
     */
56
    private bool $hasCache = false;
57
    private ?CacheInterface $cache = null;
58
59
    private RouteCollector $fastRouteCollector;
60
    private RouteCollectionInterface $routeCollection;
61
    private bool $hasInjectedRoutes = false;
62
63
    /**
64
     * Constructor
65
     *
66
     * Accepts optionally a FastRoute RouteCollector and a callable factory
67
     * that can return a FastRoute dispatcher.
68
     *
69
     * If either is not provided defaults will be used:
70
     *
71
     * - A RouteCollector instance will be created composing a RouteParser and
72
     *   RouteGenerator.
73
     * - A callable that returns a GroupCountBased dispatcher will be created.
74
     *
75
     * @param RouteCollector|null $fastRouteCollector If not provided, a default
76
     *     implementation will be used.
77
     * @param callable|null $dispatcherFactory Callable that will return a
78
     *     FastRoute dispatcher.
79
     * @param array $config Array of custom configuration options.
80
     */
81 20
    public function __construct(
82
        RouteCollectionInterface $routeCollection,
83
        CacheInterface $cache = null,
84
        array $config = null,
85
        RouteCollector $fastRouteCollector = null,
86
        callable $dispatcherFactory = null
87
    ) {
88 20
        if (null === $fastRouteCollector) {
89 20
            $fastRouteCollector = $this->createRouteCollector();
90
        }
91 20
        $this->routeCollection = $routeCollection;
92 20
        $this->fastRouteCollector = $fastRouteCollector;
93 20
        $this->dispatcherCallback = $dispatcherFactory;
94 20
        $this->loadConfig($config);
95 20
        $this->cache = $cache;
96
97 20
        $this->loadDispatchData();
98 20
    }
99
100 20
    public function match(ServerRequestInterface $request): MatchingResult
101
    {
102 20
        if (!$this->hasCache && !$this->hasInjectedRoutes) {
103 19
            $this->injectRoutes();
104
        }
105
106 20
        $dispatchData = $this->getDispatchData();
107 20
        $path = urldecode($request->getUri()->getPath());
108 20
        $method = $request->getMethod();
109 20
        $result = $this->getDispatcher($dispatchData)->dispatch($method, $request->getUri()->getHost() . $path);
110
111 20
        return $result[0] !== Dispatcher::FOUND
112 6
            ? $this->marshalFailedRoute($result)
113 20
            : $this->marshalMatchedRoute($result, $method);
114
    }
115
116
    /**
117
     * Load configuration parameters
118
     *
119
     * @param array|null $config Array of custom configuration options.
120
     */
121 20
    private function loadConfig(array $config = null): void
122
    {
123 20
        if (null === $config) {
124
            return;
125
        }
126
127 20
        if (isset($config[self::CONFIG_CACHE_KEY])) {
128 20
            $this->cacheKey = (string)$config[self::CONFIG_CACHE_KEY];
129
        }
130 20
    }
131
132
    /**
133
     * Retrieve the dispatcher instance.
134
     *
135
     * Uses the callable factory in $dispatcherCallback, passing it $data
136
     * (which should be derived from the router's getData() method); this
137
     * approach is done to allow testing against the dispatcher.
138
     *
139
     * @param array|object $data Data from {@see RouteCollector::getData()}
140
     *
141
     * @return Dispatcher
142
     */
143 20
    private function getDispatcher($data): Dispatcher
144
    {
145 20
        if (!$this->dispatcherCallback) {
146 20
            $this->dispatcherCallback = $this->createDispatcherCallback();
147
        }
148
149 20
        $factory = $this->dispatcherCallback;
150
151 20
        return $factory($data);
152
    }
153
154
    /**
155
     * Create a default FastRoute Collector instance
156
     */
157 20
    private function createRouteCollector(): RouteCollector
158
    {
159 20
        return new RouteCollector(new RouteParser(), new RouteGenerator());
160
    }
161
162
    /**
163
     * Return a default implementation of a callback that can return a Dispatcher.
164
     */
165 20
    private function createDispatcherCallback(): callable
166
    {
167 20
        return static function ($data) {
168 20
            return new GroupCountBased($data);
169 20
        };
170
    }
171
172
    /**
173
     * Marshal a routing failure result.
174
     *
175
     * If the failure was due to the HTTP method, passes the allowed HTTP
176
     * methods to the factory.
177
     *
178
     * @param array $result
179
     *
180
     * @return MatchingResult
181
     */
182 6
    private function marshalFailedRoute(array $result): MatchingResult
183
    {
184 6
        $resultCode = $result[0];
185 6
        if ($resultCode === Dispatcher::METHOD_NOT_ALLOWED) {
186 3
            return MatchingResult::fromFailure($result[1]);
187
        }
188
189 3
        return MatchingResult::fromFailure(Method::ALL);
190
    }
191
192
    /**
193
     * Marshals a route result based on the results of matching, the current host and the current HTTP method.
194
     *
195
     * @param array $result
196
     * @param string $method
197
     *
198
     * @return MatchingResult
199
     */
200 14
    private function marshalMatchedRoute(array $result, string $method): MatchingResult
201
    {
202 14
        [, $name, $parameters] = $result;
203
204 14
        $route = $this->routeCollection->getRoute($name);
205
206 14
        if ($method !== 'HEAD' && !in_array($method, $route->getMethods(), true)) {
207
            $result[1] = $route->getPattern();
208
            return $this->marshalMethodNotAllowedResult($result);
209
        }
210
211 14
        $parameters = array_merge($route->getDefaults(), $parameters);
212
213 14
        return MatchingResult::fromSuccess($route, $parameters);
214
    }
215
216
    private function marshalMethodNotAllowedResult(array $result): MatchingResult
217
    {
218
        $path = $result[1];
219
220
        $allowedMethods = array_unique(
221
            array_reduce(
222
                $this->routeCollection->getRoutes(),
223
                static function ($allowedMethods, RouteParametersInterface $route) use ($path) {
224
                    if ($path !== $route->getPattern()) {
225
                        return $allowedMethods;
226
                    }
227
228
                    return array_merge($allowedMethods, $route->getMethods());
229
                },
230
                []
231
            )
232
        );
233
234
        return MatchingResult::fromFailure($allowedMethods);
235
    }
236
237
    /**
238
     * Inject routes into the underlying router
239
     */
240 19
    private function injectRoutes(): void
241
    {
242 19
        foreach ($this->routeCollection->getRoutes() as $index => $route) {
243
            /** @var Route $route */
244 19
            if (!$route->hasMiddlewares()) {
245
                continue;
246
            }
247 19
            $hostPattern = $route->getHost() ?? '{_host:[a-zA-Z0-9\.\-]*}';
248 19
            $methods = $route->getMethods();
249 19
            if (in_array(Method::GET, $methods, true) && !in_array(Method::HEAD, $methods, true)) {
250 16
                $methods = array_merge($methods, [Method::HEAD]);
251
            }
252 19
            $this->fastRouteCollector->addRoute(
253 19
                $methods,
254 19
                $hostPattern . $route->getPattern(),
255 19
                $route->getName()
256
            );
257
        }
258 19
        $this->hasInjectedRoutes = true;
259 19
    }
260
261
    /**
262
     * Get the dispatch data either from cache or freshly generated by the
263
     * FastRoute data generator.
264
     *
265
     * If caching is enabled, store the freshly generated data to file.
266
     */
267 20
    private function getDispatchData(): array
268
    {
269 20
        if ($this->hasCache) {
270 1
            return $this->dispatchData;
271
        }
272
273 19
        $dispatchData = (array)$this->fastRouteCollector->getData();
274
275 19
        if ($this->cache !== null) {
276 2
            $this->cacheDispatchData($dispatchData);
277
        }
278
279 19
        return $dispatchData;
280
    }
281
282
    /**
283
     * Load dispatch data from cache
284
     *
285
     * @throws RuntimeException If the cache file contains invalid data
286
     */
287 20
    private function loadDispatchData(): void
288
    {
289 20
        if ($this->cache !== null && $this->cache->has($this->cacheKey)) {
290 1
            $dispatchData = $this->cache->get($this->cacheKey);
291
292 1
            $this->hasCache = true;
293 1
            $this->dispatchData = $dispatchData;
294 1
            return;
295
        }
296
297 19
        $this->hasCache = false;
298 19
    }
299
300
    /**
301
     * Save dispatch data to cache
302
     *
303
     * @param array $dispatchData
304
     *
305
     * @throws RuntimeException If the cache directory does not exist.
306
     * @throws RuntimeException If the cache directory is not writable.
307
     * @throws RuntimeException If the cache file exists but is not writable
308
     */
309 2
    private function cacheDispatchData(array $dispatchData): void
310
    {
311 2
        $this->cache->set($this->cacheKey, $dispatchData);
0 ignored issues
show
Bug introduced by
The method set() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

311
        $this->cache->/** @scrutinizer ignore-call */ 
312
                      set($this->cacheKey, $dispatchData);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
312 2
    }
313
}
314