Completed
Pull Request — master (#283)
by Phil
22:36
created

CachedRouter::dispatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Route;
6
7
use InvalidArgumentException;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
11
use function Opis\Closure\{serialize as s, unserialize as u};
12
13
class CachedRouter
14
{
15
    /**
16
     * @var callable
17
     */
18
    protected $builder;
19
20
    /**
21
     * @var string
22
     */
23
    protected $cacheFile;
24
25
    /**
26
     * @var bool
27
     */
28
    protected $cacheEnabled;
29
30
    public function __construct(callable $builder, string $cacheFile, bool $cacheEnabled = true)
31
    {
32
        $this->builder = $builder;
33
        $this->cacheFile = $cacheFile;
34
        $this->cacheEnabled = $cacheEnabled;
35
    }
36
37
    public function dispatch(ServerRequestInterface $request): ResponseInterface
38
    {
39
        $router = $this->buildRouter($request);
40
        return $router->dispatch($request);
41
    }
42
43
    protected function buildRouter(ServerRequestInterface $request): Router
44
    {
45
        if (true === $this->cacheEnabled && file_exists($this->cacheFile)) {
46
            $cache  = file_get_contents($this->cacheFile);
47
            $router = u($cache, ['allowed_classes' => true]);
0 ignored issues
show
Unused Code introduced by
The call to Opis\Closure\unserialize() has too many arguments starting with array('allowed_classes' => true).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
48
49
            if ($router instanceof Router) {
50
                return $router;
51
            }
52
        }
53
54
        $builder = $this->builder;
55
        $router  = $builder(new Router());
56
57
        if (false === $this->cacheEnabled) {
58
            return $router;
59
        }
60
61
        if ($router instanceof Router) {
62
            $router->prepareRoutes($request);
63
            file_put_contents($this->cacheFile, s($router));
64
            return $router;
65
        }
66
67
        throw new InvalidArgumentException('Invalid Router builder provided to cached router');
68
    }
69
}
70