Router   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 91.3%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 23
c 1
b 0
f 0
dl 0
loc 63
ccs 21
cts 23
cp 0.913
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A dispatch() 0 4 1
B buildRouter() 0 29 7
A __construct() 0 11 3
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 Laravel\SerializableClosure\SerializableClosure;
15
use League\Route\Router as MainRouter;
16
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
17
use Psr\SimpleCache\CacheInterface;
18
19
class Router
20
{
21
    /**
22
     * @var callable
23
     */
24
    protected $builder;
25
26
    protected int $ttl;
27
28 3
    public function __construct(
29
        callable $builder,
30
        protected CacheInterface $cache,
31
        protected bool $cacheEnabled = true,
32
        protected string $cacheKey = 'league/route/cache'
33
    ) {
34 3
        if (true === $this->cacheEnabled && $builder instanceof \Closure) {
35 3
            $builder = new SerializableClosure($builder);
36
        }
37
38 3
        $this->builder = $builder;
39
    }
40
41
    /**
42
     * @throws \Psr\SimpleCache\InvalidArgumentException
43
     */
44 3
    public function dispatch(ServerRequestInterface $request): ResponseInterface
45
    {
46 3
        $router = $this->buildRouter($request);
47 3
        return $router->dispatch($request);
48
    }
49
50
    /**
51
     * @throws \Psr\SimpleCache\InvalidArgumentException
52
     */
53 3
    protected function buildRouter(ServerRequestInterface $request): MainRouter
54
    {
55 3
        if (true === $this->cacheEnabled && $cache = $this->cache->get($this->cacheKey)) {
56 3
            $router = unserialize($cache, ['allowed_classes' => true]);
57
58 3
            if ($router instanceof MainRouter) {
59 3
                return $router;
60
            }
61
        }
62
63 3
        $builder = $this->builder;
64
65 3
        if ($builder instanceof SerializableClosure) {
66 3
            $builder = $builder->getClosure();
67
        }
68
69 3
        $router = $builder(new MainRouter());
70
71 3
        if (false === $this->cacheEnabled) {
72
            return $router;
73
        }
74
75 3
        if ($router instanceof MainRouter) {
76 3
            $router->prepareRoutes($request);
77 3
            $this->cache->set($this->cacheKey, serialize($router));
78 3
            return $router;
79
        }
80
81
        throw new InvalidArgumentException('Invalid Router builder provided to cached router');
82
    }
83
}
84