Passed
Push — master ( f87b2f...1d5b5f )
by Alexander
300:47 queued 197:13
created

UrlMatcher::getRouteCollection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
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 Yiisoft\Http\Method;
15
use Yiisoft\Router\MatchingResult;
16
use Yiisoft\Router\Route;
17
use Yiisoft\Router\RouteCollectionInterface;
18
use Yiisoft\Router\UrlMatcherInterface;
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 27
    public function __construct(
88
        RouteCollectionInterface $routeCollection,
89
        CacheInterface $cache = null,
90
        array $config = null,
91
        RouteCollector $fastRouteCollector = null,
92
        callable $dispatcherFactory = null
93
    ) {
94 27
        if (null === $fastRouteCollector) {
95 27
            $fastRouteCollector = $this->createRouteCollector();
96
        }
97 27
        $this->routeCollection = $routeCollection;
98 27
        $this->fastRouteCollector = $fastRouteCollector;
99 27
        $this->dispatcherCallback = $dispatcherFactory;
100 27
        $this->loadConfig($config);
101 27
        $this->cache = $cache;
102
103 27
        $this->loadDispatchData();
104 27
    }
105
106 26
    public function match(ServerRequestInterface $request): MatchingResult
107
    {
108 26
        $this->request = $request;
109
110 26
        if (!$this->hasCache && !$this->hasInjectedRoutes) {
111 25
            $this->injectRoutes();
112
        }
113
114 26
        $dispatchData = $this->getDispatchData();
115 26
        $path = rawurldecode($request->getUri()->getPath());
116 26
        $method = $request->getMethod();
117 26
        $result = $this->getDispatcher($dispatchData)->dispatch($method, $request->getUri()->getHost() . $path);
118
119 26
        return $result[0] !== Dispatcher::FOUND
120 7
            ? $this->marshalFailedRoute($result)
121 26
            : $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 10
    public function getLastMatchedRequest(): ?ServerRequestInterface
138
    {
139 10
        return $this->request;
140
    }
141
142
    /**
143
     * Load configuration parameters
144
     *
145
     * @param null|array $config Array of custom configuration options.
146
     */
147 27
    private function loadConfig(array $config = null): void
148
    {
149 27
        if (null === $config) {
150 9
            return;
151
        }
152
153 18
        if (isset($config[self::CONFIG_CACHE_KEY])) {
154 18
            $this->cacheKey = (string)$config[self::CONFIG_CACHE_KEY];
155
        }
156 18
    }
157
158
    /**
159
     * Retrieve the dispatcher instance.
160
     *
161
     * Uses the callable factory in $dispatcherCallback, passing it $data
162
     * (which should be derived from the router's getData() method); this
163
     * approach is done to allow testing against the dispatcher.
164
     *
165
     * @param array|object $data Data from RouteCollector::getData()
166
     * @return Dispatcher
167
     */
168 26
    private function getDispatcher($data): Dispatcher
169
    {
170 26
        if (!$this->dispatcherCallback) {
171 26
            $this->dispatcherCallback = $this->createDispatcherCallback();
172
        }
173
174 26
        $factory = $this->dispatcherCallback;
175
176 26
        return $factory($data);
177
    }
178
179
    /**
180
     * Create a default FastRoute Collector instance
181
     */
182 27
    private function createRouteCollector(): RouteCollector
183
    {
184 27
        return new RouteCollector(new RouteParser(), new RouteGenerator());
185
    }
186
187
    /**
188
     * Return a default implementation of a callback that can return a Dispatcher.
189
     */
190 26
    private function createDispatcherCallback(): callable
191
    {
192 26
        return static function ($data) {
193 26
            return new GroupCountBased($data);
194 26
        };
195
    }
196
197
    /**
198
     * Marshal a routing failure result.
199
     *
200
     * If the failure was due to the HTTP method, passes the allowed HTTP
201
     * methods to the factory.
202
     * @param array $result
203
     * @return MatchingResult
204
     */
205 7
    private function marshalFailedRoute(array $result): MatchingResult
206
    {
207 7
        $resultCode = $result[0];
208 7
        if ($resultCode === Dispatcher::METHOD_NOT_ALLOWED) {
209 1
            return MatchingResult::fromFailure($result[1]);
210
        }
211
212 6
        return MatchingResult::fromFailure(Method::ANY);
213
    }
214
215
    /**
216
     * Marshals a route result based on the results of matching, the current host and the current HTTP method.
217
     * @param array $result
218
     * @param string $method
219
     * @return MatchingResult
220
     */
221 19
    private function marshalMatchedRoute(array $result, string $method): MatchingResult
222
    {
223 19
        [, $name, $parameters] = $result;
224
225 19
        $route = $this->routeCollection->getRoute($name);
226
227 19
        if (!in_array($method, $route->getMethods(), true)) {
228 1
            $result[1] = $route->getPattern();
229 1
            return $this->marshalMethodNotAllowedResult($result);
230
        }
231
232 18
        $parameters = array_merge($route->getDefaults(), $parameters);
233 18
        $this->currentRoute = $route;
234
235 18
        return MatchingResult::fromSuccess($route, $parameters);
236
    }
237
238 1
    private function marshalMethodNotAllowedResult(array $result): MatchingResult
239
    {
240 1
        $path = $result[1];
241
242 1
        $allowedMethods = array_unique(
243 1
            array_reduce(
244 1
                $this->routeCollection->getRoutes(),
245 1
                static function ($allowedMethods, Route $route) use ($path) {
246 1
                    if ($path !== $route->getPattern()) {
247 1
                        return $allowedMethods;
248
                    }
249
250 1
                    return array_merge($allowedMethods, $route->getMethods());
251
                },
252 1
                []
253
            )
254
        );
255
256 1
        return MatchingResult::fromFailure($allowedMethods);
257
    }
258
259
    /**
260
     * Inject routes into the underlying router
261
     */
262 25
    private function injectRoutes(): void
263
    {
264 25
        foreach ($this->routeCollection->getRoutes() as $index => $route) {
265
            /** @var Route $route */
266 25
            $hostPattern = $route->getHost() ?? '{_host:[a-zA-Z0-9\.\-]*}';
267 25
            $this->fastRouteCollector->addRoute($route->getMethods(), $hostPattern . $route->getPattern(), $route->getName());
268
        }
269 25
        $this->hasInjectedRoutes = true;
270 25
    }
271
272
    /**
273
     * Get the dispatch data either from cache or freshly generated by the
274
     * FastRoute data generator.
275
     *
276
     * If caching is enabled, store the freshly generated data to file.
277
     */
278 26
    private function getDispatchData(): array
279
    {
280 26
        if ($this->hasCache) {
281 1
            return $this->dispatchData;
282
        }
283
284 25
        $dispatchData = (array)$this->fastRouteCollector->getData();
285
286 25
        if ($this->cache !== null) {
287 2
            $this->cacheDispatchData($dispatchData);
288
        }
289
290 25
        return $dispatchData;
291
    }
292
293
    /**
294
     * Load dispatch data from cache
295
     * @throws \RuntimeException If the cache file contains invalid data
296
     */
297 27
    private function loadDispatchData(): void
298
    {
299 27
        if ($this->cache !== null && $this->cache->has($this->cacheKey)) {
300 1
            $dispatchData = $this->cache->get($this->cacheKey);
301
302 1
            $this->hasCache = true;
303 1
            $this->dispatchData = $dispatchData;
304 1
            return;
305
        }
306
307 26
        $this->hasCache = false;
308 26
    }
309
310
    /**
311
     * Save dispatch data to cache
312
     * @param array $dispatchData
313
     * @throws \RuntimeException If the cache directory does not exist.
314
     * @throws \RuntimeException If the cache directory is not writable.
315
     * @throws \RuntimeException If the cache file exists but is not writable
316
     */
317 2
    private function cacheDispatchData(array $dispatchData): void
318
    {
319 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

319
        $this->cache->/** @scrutinizer ignore-call */ 
320
                      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...
320 2
    }
321
}
322