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
|
|
|
protected int $ttl; |
28
|
3 |
|
|
29
|
|
|
public function __construct( |
30
|
|
|
callable $builder, |
31
|
|
|
protected CacheInterface $cache, |
32
|
|
|
protected bool $cacheEnabled = true, |
33
|
|
|
protected string $cacheKey = 'league/route/cache' |
34
|
3 |
|
) { |
35
|
3 |
|
$this->builder = $builder; |
36
|
|
|
} |
37
|
|
|
|
38
|
3 |
|
/** |
39
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
40
|
|
|
*/ |
41
|
|
|
public function dispatch(ServerRequestInterface $request): ResponseInterface |
42
|
|
|
{ |
43
|
|
|
$router = $this->buildRouter($request); |
44
|
3 |
|
return $router->dispatch($request); |
45
|
|
|
} |
46
|
3 |
|
|
47
|
3 |
|
/** |
48
|
|
|
* @throws \Psr\SimpleCache\InvalidArgumentException |
49
|
|
|
*/ |
50
|
|
|
protected function buildRouter(ServerRequestInterface $request): MainRouter |
51
|
|
|
{ |
52
|
|
|
if (true === $this->cacheEnabled && $cache = $this->cache->get($this->cacheKey)) { |
53
|
3 |
|
$router = u($cache, ['allowed_classes' => true]); |
54
|
|
|
|
55
|
3 |
|
if ($router instanceof MainRouter) { |
56
|
3 |
|
return $router; |
57
|
|
|
} |
58
|
3 |
|
} |
59
|
3 |
|
|
60
|
|
|
$builder = $this->builder; |
61
|
|
|
$router = $builder(new MainRouter()); |
62
|
|
|
|
63
|
3 |
|
if (false === $this->cacheEnabled) { |
64
|
|
|
return $router; |
65
|
3 |
|
} |
66
|
3 |
|
|
67
|
|
|
if ($router instanceof MainRouter) { |
68
|
|
|
$router->prepareRoutes($request); |
69
|
3 |
|
$this->cache->set($this->cacheKey, s($router)); |
70
|
|
|
return $router; |
71
|
3 |
|
} |
72
|
|
|
|
73
|
|
|
throw new InvalidArgumentException('Invalid Router builder provided to cached router'); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|