Passed
Push — master ( 67a6c5...5b4678 )
by Divine Niiquaye
24:01 queued 08:03
created

Router::getCachedData()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.0208

Importance

Changes 9
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
nc 9
nop 1
dl 0
loc 21
ccs 11
cts 12
cp 0.9167
crap 6.0208
rs 9.2222
c 9
b 0
f 0
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\Exceptions\UrlGenerationException;
22
use Flight\Routing\Generator\GeneratedUri;
23
use Flight\Routing\Interfaces\{RouteCompilerInterface, RouteMatcherInterface, UrlGeneratorInterface};
24
use Laminas\Stratigility\Next;
25
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface, UriInterface};
26
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
27
use Symfony\Component\VarExporter\VarExporter;
28
29
/**
30
 * Aggregate routes for matching and Dispatching.
31
 *
32
 * @author Divine Niiquaye Ibok <[email protected]>
33
 */
34
class Router implements RouteMatcherInterface, RequestMethodInterface, MiddlewareInterface
35
{
36
    /**
37
     * Standard HTTP methods for browser requests.
38
     */
39
    public const HTTP_METHODS_STANDARD = [
40
        self::METHOD_HEAD,
41
        self::METHOD_GET,
42
        self::METHOD_POST,
43
        self::METHOD_PUT,
44
        self::METHOD_PATCH,
45
        self::METHOD_DELETE,
46
        self::METHOD_PURGE,
47
        self::METHOD_OPTIONS,
48
        self::METHOD_TRACE,
49
        self::METHOD_CONNECT,
50
    ];
51
52
    private ?RouteCompilerInterface $compiler;
53
    private ?RouteMatcherInterface $matcher = null;
54
    private ?\SplQueue $pipeline = null;
55
    private string $matcherClass = RouteMatcher::class;
56
    private ?string $cacheData;
57
58
    /** @var array<string,array<int,MiddlewareInterface>> */
59
    private array $middlewares = [];
60
61
    /** @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...
62
    private $collection;
63
64
    /**
65
     * @param string|null $cache file path to store compiled routes
66
     */
67 92
    public function __construct(RouteCompilerInterface $compiler = null, string $cache = null)
68
    {
69 92
        $this->compiler = $compiler;
70 92
        $this->cacheData = $cache;
71
    }
72
73
    /**
74
     * Set a route collection instance into Router in order to use addRoute method.
75
     *
76
     * @param string|null $cache file path to store compiled routes
77
     *
78
     * @return static
79
     */
80 87
    public static function withCollection(RouteCollection $collection = null, RouteCompilerInterface $compiler = null, string $cache = null)
81
    {
82 87
        $new = new static($compiler, $cache);
83 87
        $new->collection = $collection ?? new RouteCollection();
84
85 87
        return $new;
86
    }
87
88
    /**
89
     * This method works only if withCollection method is used.
90
     */
91 78
    public function addRoute(Route ...$routes): void
92
    {
93 78
        if ($this->collection instanceof RouteCollection) {
94 78
            $this->collection->routes($routes);
95
        }
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101 2
    public function match(string $method, UriInterface $uri): ?Route
102
    {
103 2
        return $this->getMatcher()->match($method, $uri);
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 7
    public function matchRequest(ServerRequestInterface $request): ?Route
110
    {
111 7
        return $this->getMatcher()->matchRequest($request);
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117 7
    public function generateUri(string $routeName, array $parameters = [], int $referenceType = GeneratedUri::ABSOLUTE_PATH): GeneratedUri
118
    {
119 7
        $matcher = $this->getMatcher();
120
121
        //@codeCoverageIgnoreStart
122
        if (!$matcher instanceof UrlGeneratorInterface) {
123
            throw new UrlGenerationException(\sprintf('The route matcher does not support using the %s implementation', UrlGeneratorInterface::class));
124
        }
125
        //@codeCoverageIgnoreEnd
126
127 7
        return $matcher->generateUri($routeName, $parameters, $referenceType);
128
    }
129
130
    /**
131
     * Attach middleware to the pipeline.
132
     */
133 56
    public function pipe(MiddlewareInterface ...$middlewares): void
134
    {
135 56
        if (null === $this->pipeline) {
136 56
            $this->pipeline = new \SplQueue();
137
        }
138
139 56
        foreach ($middlewares as $middleware) {
140 56
            $this->pipeline->enqueue($middleware);
141
        }
142
    }
143
144
    /**
145
     * Attach a name to a group of middlewares.
146
     */
147 4
    public function pipes(string $name, MiddlewareInterface ...$middlewares): void
148
    {
149 4
        $this->middlewares[$name] = $middlewares;
150
    }
151
152
    /**
153
     * Sets the RouteCollection instance associated with this Router.
154
     *
155
     * @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...
156
     */
157 4
    public function setCollection(callable $routeDefinitionCallback): void
158
    {
159 4
        $this->collection = $routeDefinitionCallback;
160
    }
161
162
    /**
163
     *  Get the RouteCollection instance associated with this Router.
164
     */
165 91
    public function getCollection(): RouteCollection
166
    {
167 91
        if (\is_callable($collection = $this->collection)) {
168 3
            $collection($collection = new RouteCollection());
169 88
        } elseif (null === $collection) {
170 1
            throw new \RuntimeException(\sprintf('Did you forget to set add the route collection with the "%s".', __CLASS__ . '::setCollection'));
171
        }
172
173 90
        return $this->collection = $collection;
174
    }
175
176
    /**
177
     * Set where cached data will be stored.
178
     *
179
     * @param string $cache file path to store compiled routes
180
     */
181
    public function setCache(string $cache): void
182
    {
183
        $this->cacheData = $cache;
184
    }
185
186
    /**
187
     * If RouteCollection's data has been cached.
188
     */
189 3
    public function isCached(): bool
190
    {
191 3
        return ($cache = $this->cacheData) && \file_exists($cache);
192
    }
193
194
    /**
195
     * Set a matcher class associated with this Router.
196
     */
197
    public function setMatcher(string $matcherClass): void
198
    {
199
        if (!\is_subclass_of($matcherClass, RouteMatcherInterface::class)) {
200
            throw new \InvalidArgumentException(\sprintf('"%s" must be a subclass of "%s".', $matcherClass, RouteMatcherInterface::class));
201
        }
202
        $this->matcherClass = $matcherClass;
203
    }
204
205
    /**
206
     * Gets the Route matcher instance associated with this Router.
207
     */
208 92
    public function getMatcher(): RouteMatcherInterface
209
    {
210 92
        return $this->matcher ??= $this->cacheData ? $this->getCachedData($this->cacheData) : new $this->matcherClass($this->getCollection(), $this->compiler);
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216 77
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
217
    {
218 77
        $route = $this->getMatcher()->matchRequest($request);
219
220 73
        if (null !== $route) {
221 50
            foreach ($route->getPiped() as $middleware) {
222 2
                if (isset($this->middlewares[$middleware])) {
223 2
                    $this->pipe(...$this->middlewares[$middleware]);
224
                }
225
            }
226
        }
227
228 73
        if (null !== $this->pipeline) {
229 56
            $handler = new Next($this->pipeline, $handler);
230
        }
231
232 73
        return $handler->handle($request->withAttribute(Route::class, $route));
233
    }
234
235 2
    protected function getCachedData(string $cache): RouteMatcherInterface
236
    {
237 2
        $cachedData = @include $cache;
238
239 2
        if (!$cachedData instanceof RouteMatcherInterface) {
240 1
            $cachedData = new $this->matcherClass($this->getCollection(), $this->compiler);
241 1
            $dumpData = \class_exists(VarExporter::class) ? VarExporter::export($cachedData) : "\unserialize(<<<'SERIALIZED'\n" . \serialize($cachedData) . "\nSERIALIZED)";
242
243 1
            if (!\is_dir($directory = \dirname($cache))) {
244
                @\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

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

250
                /** @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...
251
            }
252 1
            $cachedData = require $cache;
253
        }
254
255 2
        return $cachedData;
256
    }
257
}
258