Passed
Push — master ( f578af...67718f )
by Alexander
02:21 queued 59s
created

UrlMatcher   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 304
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 80
c 2
b 0
f 0
dl 0
loc 304
ccs 86
cts 86
cp 1
rs 9.92
wmc 31

16 Methods

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

327
        $this->cache->/** @scrutinizer ignore-call */ 
328
                      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...
328
    }
329
}
330