Passed
Pull Request — master (#87)
by Sergei
02:06
created

UrlMatcher::getDispatchData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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

267
        $this->cache->/** @scrutinizer ignore-call */ 
268
                      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...
268 2
    }
269
}
270