Passed
Push — master ( 049287...68f58a )
by Divine Niiquaye
03:27
created

Router::pipe()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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

184
        return ($cache instanceof CacheItemPoolInterface && $cache->hasItem(__FILE__)) || \file_exists(/** @scrutinizer ignore-type */ $cache);
Loading history...
185
    }
186
187
    /**
188
     * Gets the Route matcher instance associated with this Router.
189
     */
190 92
    public function getMatcher(): RouteMatcherInterface
191
    {
192 92
        return $this->matcher ??= $this->cacheData ? $this->getCachedData($this->cacheData) : new RouteMatcher($this->getCollection(), $this->compiler);
193
    }
194
195
    /**
196
     * {@inheritdoc}
197
     */
198 77
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
199
    {
200 77
        $route = $this->getMatcher()->matchRequest($request);
201
202 73
        if (null !== $route) {
203 50
            foreach ($route->getPiped() as $middleware) {
204 2
                foreach ($this->middlewares[$middleware] ?? [] as $pipedMiddleware) {
205 2
                    $this->pipeline->enqueue($pipedMiddleware);
206
                }
207
            }
208
        }
209
210 73
        return (new Next($this->pipeline, $handler))->handle($request->withAttribute(Route::class, $route));
211
    }
212
213
    /**
214
     * @param CacheItemPoolInterface|string $cache
215
     */
216 2
    protected function getCachedData($cache): RouteMatcherInterface
217
    {
218 2
        if ($cache instanceof CacheItemPoolInterface) {
219
            $cachedData = ($cacheItem = $cache->getItem(__FILE__))->get();
220
221
            if (!$cachedData instanceof RouteMatcherInterface) {
222
                $cache->deleteItem(__FILE__);
223
                $cache->save($cacheItem->set(new RouteMatcher($this->getCollection(), $this->compiler)));
224
            }
225
226
            return $cacheItem->get();
227
        }
228
229 2
        $cachedData = @include $cache;
230
231 2
        if (!$cachedData instanceof RouteMatcherInterface) {
232 1
            $dumpData = "<?php // auto generated: AVOID MODIFYING\n\n \$data = ";
233 1
            $dumpData .= \var_export([
234 1
                'compiled' => $this->compiler->build($c = $this->getCollection()),
0 ignored issues
show
Bug introduced by
The method build() 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

234
                'compiled' => $this->compiler->/** @scrutinizer ignore-call */ build($c = $this->getCollection()),

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...
235 1
                'routes' => $c->getRoutes(),
236
            ], true);
237
238 1
            if (!\is_dir($directory = \dirname($cache))) {
239
                @\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

239
                /** @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...
240
            }
241 1
            \file_put_contents($cache, $dumpData . ";\nreturn \\Flight\Routing\RouteMatcher::__set_state(\$data);\n");
242
243 1
            if (\function_exists('opcache_invalidate') && \filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
244 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

244
                /** @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...
245
            }
246
247 1
            return require $cache;
248
        }
249
250 1
        return $cachedData;
251
    }
252
}
253