Passed
Push — 6.x ( 08953e...092dd0 )
by Phil
13:02
created

Router::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 7
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 4
crap 1
1
<?php
2
3
/**
4
 * The cached router is currently in BETA and not recommended for production code.
5
 *
6
 * Please feel free to heavily test and report any issues as an issue on the GitHub repository.
7
 */
8
9
declare(strict_types=1);
10
11
namespace League\Route\Cache;
12
13
use InvalidArgumentException;
14
use League\Route\Router as MainRouter;
15
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
16
use Psr\SimpleCache\CacheInterface;
17
18
use function Opis\Closure\{serialize as s, unserialize as u};
19
20
class Router
21
{
22
    /**
23
     * @var callable
24
     */
25
    protected $builder;
26
27
    /**
28
     * @var integer
29
     */
30
    protected $ttl;
31
32 3
    public function __construct(
33
        callable $builder,
34
        protected CacheInterface $cache,
35
        protected bool $cacheEnabled = true,
36
        protected string $cacheKey = 'league/route/cache'
37
    ) {
38 3
        $this->builder = $builder;
39
    }
40
41 3
    public function dispatch(ServerRequestInterface $request): ResponseInterface
42
    {
43 3
        $router = $this->buildRouter($request);
44 3
        return $router->dispatch($request);
45
    }
46
47 3
    protected function buildRouter(ServerRequestInterface $request): MainRouter
48
    {
49 3
        if (true === $this->cacheEnabled && $cache = $this->cache->get($this->cacheKey)) {
50 3
            $router = u($cache, ['allowed_classes' => true]);
51
52 3
            if ($router instanceof MainRouter) {
53 3
                return $router;
54
            }
55
        }
56
57 3
        $builder = $this->builder;
58 3
        $router = $builder(new MainRouter());
59
60 3
        if (false === $this->cacheEnabled) {
61
            return $router;
62
        }
63
64 3
        if ($router instanceof MainRouter) {
65 3
            $router->prepareRoutes($request);
66 3
            $this->cache->set($this->cacheKey, s($router));
67 3
            return $router;
68
        }
69
70
        throw new InvalidArgumentException('Invalid Router builder provided to cached router');
71
    }
72
}
73