Passed
Branch 5.x (508359)
by Phil
24:20
created

Router   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 24
c 0
b 0
f 0
dl 0
loc 61
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A dispatch() 0 4 1
A buildRouter() 0 24 6
A __construct() 0 5 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
    protected const CACHE_KEY = 'league/route/cache';
23
24
    /**
25
     * @var callable
26
     */
27
    protected $builder;
28
29
    /**
30
     * @var CacheInterface
31
     */
32
    protected $cache;
33
34
    /**
35
     * @var integer
36
     */
37
    protected $ttl;
38
39
    /**
40
     * @var bool
41
     */
42
    protected $cacheEnabled;
43
44
    public function __construct(callable $builder, CacheInterface $cache, bool $cacheEnabled = true)
45
    {
46
        $this->builder = $builder;
47
        $this->cache = $cache;
48
        $this->cacheEnabled = $cacheEnabled;
49
    }
50
51
    public function dispatch(ServerRequestInterface $request): ResponseInterface
52
    {
53
        $router = $this->buildRouter($request);
54
        return $router->dispatch($request);
55
    }
56
57
    protected function buildRouter(ServerRequestInterface $request): MainRouter
58
    {
59
        if (true === $this->cacheEnabled && $cache = $this->cache->get(static::CACHE_KEY)) {
60
            $router = u($cache, ['allowed_classes' => true]);
61
62
            if ($router instanceof MainRouter) {
63
                return $router;
64
            }
65
        }
66
67
        $builder = $this->builder;
68
        $router = $builder(new MainRouter());
69
70
        if (false === $this->cacheEnabled) {
71
            return $router;
72
        }
73
74
        if ($router instanceof MainRouter) {
75
            $router->prepareRoutes($request);
76
            $this->cache->set(static::CACHE_KEY, s($router));
77
            return $router;
78
        }
79
80
        throw new InvalidArgumentException('Invalid Router builder provided to cached router');
81
    }
82
}
83