Passed
Push — master ( e3faac...545dab )
by Divine Niiquaye
04:53 queued 02:08
created

Router::setMatcher()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Flight Routing.
7
 *
8
 * PHP version 7.4 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Flight\Routing;
19
20
use Fig\Http\Message\RequestMethodInterface;
21
use Flight\Routing\Generator\GeneratedUri;
22
use Flight\Routing\Interfaces\{RouteCompilerInterface, RouteMatcherInterface};
23
use Laminas\Stratigility\Next;
24
use Psr\Cache\CacheItemPoolInterface;
25
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface, UriInterface};
26
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
27
28
/**
29
 * Aggregate routes for matching and Dispatching.
30
 *
31
 * @author Divine Niiquaye Ibok <[email protected]>
32
 */
33
class Router implements RouteMatcherInterface, RequestMethodInterface, MiddlewareInterface
34
{
35
    /**
36
     * Standard HTTP methods for browser requests.
37
     */
38
    public const HTTP_METHODS_STANDARD = [
39
        self::METHOD_HEAD,
40
        self::METHOD_GET,
41
        self::METHOD_POST,
42
        self::METHOD_PUT,
43
        self::METHOD_PATCH,
44
        self::METHOD_DELETE,
45
        self::METHOD_PURGE,
46
        self::METHOD_OPTIONS,
47
        self::METHOD_TRACE,
48
        self::METHOD_CONNECT,
49
    ];
50
51
    private \SplQueue $pipeline;
52
    private ?RouteCompilerInterface $compiler;
53
    private ?RouteMatcherInterface $matcher = null;
54
    private string $matcherClass = RouteMatcher::class;
55
56
    /** @var array<string,array<int,MiddlewareInterface>> */
57
    private array $middlewares = [];
58
59
    /** @var RouteCollection|(callable(RouteCollection): void)|null */
0 ignored issues
show
Documentation Bug introduced by
The doc comment RouteCollection|(callabl...Collection): void)|null at position 3 could not be parsed: Expected ')' at position 3, but found 'callable'.
Loading history...
60
    private $collection;
61
62
63
    /** @var CacheItemPoolInterface|string|null */
64
    private $cacheData;
65
66
    /**
67
     * @param CacheItemPoolInterface|string|null $cache use file path or PSR-6 cache
68
     */
69 92
    public function __construct(RouteCompilerInterface $compiler = null, $cache = null)
70
    {
71 92
        $this->compiler = $compiler;
72 92
        $this->pipeline = new \SplQueue();
73 92
        $this->cacheData = $cache;
74
    }
75
76
    /**
77
     * Set a route collection instance into Router in order to use addRoute method.
78
     *
79
     * @param CacheItemPoolInterface|string|null $cache use file path or PSR-6 cache
80
     *
81
     * @return static
82
     */
83 87
    public static function withCollection(RouteCollection $collection = null, RouteCompilerInterface $compiler = null, $cache = null)
84
    {
85 87
        $new = new static($compiler, $cache);
86 87
        $new->collection = $collection ?? new RouteCollection();
87
88 87
        return $new;
89
    }
90
91
    /**
92
     * This method works only if withCollection method is used.
93
     */
94 78
    public function addRoute(Route ...$routes): void
95
    {
96 78
        if ($this->collection instanceof RouteCollection) {
97 78
            $this->collection->routes($routes);
98
        }
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104 2
    public function match(string $method, UriInterface $uri): ?Route
105
    {
106 2
        return $this->getMatcher()->match($method, $uri);
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112 7
    public function matchRequest(ServerRequestInterface $request): ?Route
113
    {
114 7
        return $this->getMatcher()->matchRequest($request);
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 7
    public function generateUri(string $routeName, array $parameters = []): GeneratedUri
121
    {
122 7
        return $this->getMatcher()->generateUri($routeName, $parameters);
123
    }
124
125
    /**
126
     * Attach middleware to the pipeline.
127
     */
128 55
    public function pipe(MiddlewareInterface ...$middlewares): void
129
    {
130 55
        foreach ($middlewares as $middleware) {
131 55
            $this->pipeline->enqueue($middleware);
132
        }
133
    }
134
135
    /**
136
     * Attach a name to a group of middlewares.
137
     */
138 4
    public function pipes(string $name, MiddlewareInterface ...$middlewares): void
139
    {
140 4
        $this->middlewares[$name] = $middlewares;
141
    }
142
143
    /**
144
     * Sets the RouteCollection instance associated with this Router.
145
     *
146
     * @param (callable(RouteCollection): void) $routeDefinitionCallback takes only one parameter of route collection
0 ignored issues
show
Documentation Bug introduced by
The doc comment (callable(RouteCollection): void) at position 1 could not be parsed: Expected ')' at position 1, but found 'callable'.
Loading history...
147
     */
148 4
    public function setCollection(callable $routeDefinitionCallback): void
149
    {
150 4
        $this->collection = $routeDefinitionCallback;
151
    }
152
153
    /**
154
     *  Get the RouteCollection instance associated with this Router.
155
     */
156 91
    public function getCollection(): RouteCollection
157
    {
158 91
        if (\is_callable($collection = $this->collection)) {
159 3
            $collection($collection = new RouteCollection());
160 88
        } elseif (null === $collection) {
161 1
            throw new \RuntimeException(\sprintf('Did you forget to set add the route collection with the "%s".', __CLASS__ . '::setCollection'));
162
        }
163
164 90
        return $this->collection = $collection;
165
    }
166
167
    /**
168
     * Set where cached data will be stored.
169
     *
170
     * @param CacheItemPoolInterface|string $cache use file path or PSR-6 cache
171
     *
172
     * @return void
173
     */
174
    public function setCache($cache): void
175
    {
176
        $this->cacheData = $cache;
177
    }
178
179
    /**
180
     * If RouteCollection's data has been cached.
181
     */
182 3
    public function isCached(): bool
183
    {
184 3
        if (null === $cache = $this->cacheData) {
185 1
            return false;
186
        }
187
188 2
        return ($cache instanceof CacheItemPoolInterface && $cache->hasItem(__FILE__)) || \file_exists($cache);
0 ignored issues
show
Bug introduced by
It seems like $cache can also be of type Psr\Cache\CacheItemPoolInterface; however, parameter $filename of file_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

188
        return ($cache instanceof CacheItemPoolInterface && $cache->hasItem(__FILE__)) || \file_exists(/** @scrutinizer ignore-type */ $cache);
Loading history...
189
    }
190
191
    /**
192
     * Set a matcher class associated with this Router.
193
     */
194
    public function setMatcher(string $matcherClass): void
195
    {
196
        if (!\is_subclass_of($matcherClass, RouteMatcherInterface::class)) {
197
            throw new \InvalidArgumentException(\sprintf('"%s" must be a subclass of "%s".', $matcherClass, RouteMatcherInterface::class));
198
        }
199
        $this->matcherClass = $matcherClass;
200
    }
201
202
    /**
203
     * Gets the Route matcher instance associated with this Router.
204
     */
205 92
    public function getMatcher(): RouteMatcherInterface
206
    {
207 92
        return $this->matcher ??= $this->cacheData ? $this->getCachedData($this->cacheData) : new $this->matcherClass($this->getCollection(), $this->compiler);
208
    }
209
210
    /**
211
     * {@inheritdoc}
212
     */
213 77
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
214
    {
215 77
        $route = $this->getMatcher()->matchRequest($request);
216
217 73
        if (null !== $route) {
218 50
            foreach ($route->getPiped() as $middleware) {
219 2
                foreach ($this->middlewares[$middleware] ?? [] as $pipedMiddleware) {
220 2
                    $this->pipeline->enqueue($pipedMiddleware);
221
                }
222
            }
223
        }
224
225 73
        return (new Next($this->pipeline, $handler))->handle($request->withAttribute(Route::class, $route));
226
    }
227
228
    /**
229
     * @param CacheItemPoolInterface|string $cache
230
     */
231 2
    protected function getCachedData($cache): RouteMatcherInterface
232
    {
233 2
        if ($cache instanceof CacheItemPoolInterface) {
234
            $cachedData = ($cacheItem = $cache->getItem(__FILE__))->get();
235
236
            if (!$cachedData instanceof RouteMatcherInterface) {
237
                $cache->deleteItem(__FILE__);
238
                $cache->save($cacheItem->set($cachedData = new $this->matcherClass($this->getCollection(), $this->compiler)));
239
            }
240
241
            return $cacheItem->get();
242
        }
243
244 2
        $cachedData = @include $cache;
245
246 2
        if (!$cachedData instanceof RouteMatcherInterface) {
247 1
            $dumpData = "<<<'SERIALIZED'\n" . \serialize(new $this->matcherClass($this->getCollection(), $this->compiler)) . "\nSERIALIZED";
248
249 1
            if (!\is_dir($directory = \dirname($cache))) {
250
                @\mkdir($directory, 0775, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

250
                /** @scrutinizer ignore-unhandled */ @\mkdir($directory, 0775, true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
251
            }
252
253 1
            \file_put_contents($cache, "<?php // auto generated: AVOID MODIFYING\n\nreturn \unserialize(" . $dumpData . ");\n");
254
255 1
            if (\function_exists('opcache_invalidate') && \filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
256 1
                @\opcache_invalidate($cache, true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for opcache_invalidate(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

256
                /** @scrutinizer ignore-unhandled */ @\opcache_invalidate($cache, true);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
257
            }
258 1
            $cachedData = require $cache;
259
        }
260
261 2
        return $cachedData;
262
    }
263
}
264