Passed
Push — master ( 8d099e...79397a )
by Divine Niiquaye
02:48
created

Router::getCachedData()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 30
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 9.5839

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 7
eloc 15
c 6
b 0
f 0
nc 7
nop 1
dl 0
loc 30
ccs 10
cts 16
cp 0.625
crap 9.5839
rs 8.8333
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
    /** @var array<string,array<int,MiddlewareInterface>> */
52
    private array $middlewares = [];
53
54
    /** @var array<string,Route|null> Match once, use later */
55
    private array $optimized = [];
56
57
    private \SplQueue $pipeline;
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
    private ?RouteCompilerInterface $compiler;
63
64
    private ?RouteMatcherInterface $matcher = null;
65
66
    /** @var CacheItemPoolInterface|string|null */
67
    private $cacheData;
68
69
    /**
70
     * @param CacheItemPoolInterface|string|null $cache use file path or PSR-6 cache
71
     */
72 92
    public function __construct(RouteCompilerInterface $compiler = null, $cache = null)
73
    {
74 92
        $this->compiler = $compiler;
75 92
        $this->pipeline = new \SplQueue();
76 92
        $this->cacheData = $cache;
77
    }
78
79
    /**
80
     * Set a route collection instance into Router in order to use addRoute method.
81
     *
82
     * @param CacheItemPoolInterface|string|null $cache use file path or PSR-6 cache
83
     *
84
     * @return static
85
     */
86 87
    public static function withCollection(RouteCollection $collection = null, RouteCompilerInterface $compiler = null, $cache = null)
87
    {
88 87
        $new = new static($compiler, $cache);
89 87
        $new->collection = $collection ?? new RouteCollection();
90
91 87
        return $new;
92
    }
93
94
    /**
95
     * This method works only if withCollection method is used.
96
     */
97 78
    public function addRoute(Route ...$routes): void
98
    {
99 78
        if ($this->collection instanceof RouteCollection) {
100 78
            $this->collection->routes($routes);
101
        }
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107 2
    public function match(string $method, UriInterface $uri): ?Route
108
    {
109 2
        return $this->optimized[$method . (string) $uri] ??= $this->getMatcher()->match($method, $uri);
110
    }
111
112
    /**
113
     * {@inheritdoc}
114
     */
115 7
    public function matchRequest(ServerRequestInterface $request): ?Route
116
    {
117 7
        return $this->optimized[$request->getMethod() . (string) $request->getUri()] ??= $this->getMatcher()->matchRequest($request);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123 7
    public function generateUri(string $routeName, array $parameters = []): GeneratedUri
124
    {
125 7
        return $this->getMatcher()->generateUri($routeName, $parameters);
126
    }
127
128
    /**
129
     * Attach middleware to the pipeline.
130
     */
131 55
    public function pipe(MiddlewareInterface ...$middlewares): void
132
    {
133 55
        foreach ($middlewares as $middleware) {
134 55
            $this->pipeline->enqueue($middleware);
135
        }
136
    }
137
138
    /**
139
     * Attach a name to a group of middlewares.
140
     */
141 4
    public function pipes(string $name, MiddlewareInterface ...$middlewares): void
142
    {
143 4
        $this->middlewares[$name] = $middlewares;
144
    }
145
146
    /**
147
     * Sets the RouteCollection instance associated with this Router.
148
     *
149
     * @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...
150
     */
151 4
    public function setCollection(callable $routeDefinitionCallback): void
152
    {
153 4
        $this->collection = $routeDefinitionCallback;
154
    }
155
156
    /**
157
     *  Get the RouteCollection instance associated with this Router.
158
     */
159 91
    public function getCollection(): RouteCollection
160
    {
161 91
        if (\is_callable($collection = $this->collection)) {
162 3
            $collection($collection = new RouteCollection());
163 88
        } elseif (null === $collection) {
164 1
            throw new \RuntimeException(\sprintf('Did you forget to set add the route collection with the "%s".', __CLASS__ . '::setCollection'));
165
        }
166
167 90
        return $this->collection = $collection;
168
    }
169
170
    /**
171
     * Set where cached data will be stored.
172
     *
173
     * @param CacheItemPoolInterface|string $cache use file path or PSR-6 cache
174
     *
175
     * @return void
176
     */
177
    public function setCache($cache): void
178
    {
179
        $this->cacheData = $cache;
180
    }
181
182
    /**
183
     * If RouteCollection's data has been cached.
184
     */
185 3
    public function isCached(): bool
186
    {
187 3
        if (null === $cache = $this->cacheData) {
188 1
            return false;
189
        }
190
191 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

191
        return ($cache instanceof CacheItemPoolInterface && $cache->hasItem(__FILE__)) || \file_exists(/** @scrutinizer ignore-type */ $cache);
Loading history...
192
    }
193
194
    /**
195
     * Gets the Route matcher instance associated with this Router.
196
     */
197 92
    public function getMatcher(): RouteMatcherInterface
198
    {
199 92
        return $this->matcher
200 91
            ?? $this->matcher = (
201 92
                $this->cacheData
202 2
                    ? $this->getCachedData($this->cacheData)
203 92
                    : new RouteMatcher($this->getCollection(), $this->compiler)
204
            );
205
    }
206
207
    /**
208
     * {@inheritdoc}
209
     */
210 77
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
211
    {
212 77
        $route = $this->getMatcher()->matchRequest($request);
213
214 73
        if (null !== $route) {
215 50
            foreach ($route->getPiped() as $middleware) {
216 2
                foreach ($this->middlewares[$middleware] ?? [] as $pipedMiddleware) {
217 2
                    $this->pipeline->enqueue($pipedMiddleware);
218
                }
219
            }
220
        }
221
222 73
        return (new Next($this->pipeline, $handler))->handle($request->withAttribute(Route::class, $route));
223
    }
224
225
    /**
226
     * @param CacheItemPoolInterface|string $cache
227
     */
228 2
    protected function getCachedData($cache): RouteMatcherInterface
229
    {
230 2
        if ($cache instanceof CacheItemPoolInterface) {
231
            $cachedData = $cache->getItem(__FILE__)->get();
232
233
            if (!$cachedData instanceof RouteMatcherInterface) {
234
                $cache->deleteItem(__FILE__);
235
                $cache->save($cache->getItem(__FILE__)->set($cachedData = new RouteMatcher($this->getCollection(), $this->compiler)));
236
            }
237
238
            return $cachedData;
239
        }
240
241 2
        $cachedData = @include $cache;
242
243 2
        if (!$cachedData instanceof RouteMatcherInterface) {
244 1
            $dumpData = "<<<'SERIALIZED'\n" . \serialize($cachedData = new RouteMatcher($this->getCollection(), $this->compiler)) . "\nSERIALIZED";
245
246 1
            if (!\is_dir($directory = \dirname($cache))) {
247
                @\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

247
                /** @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...
248
            }
249
250 1
            \file_put_contents($cache, "<?php // auto generated: AVOID MODIFYING\n\nreturn \unserialize(" . $dumpData . ");\n");
251
252 1
            if (\function_exists('opcache_invalidate') && \filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
253 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

253
                /** @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...
254
            }
255
        }
256
257 2
        return $cachedData;
258
    }
259
}
260