Completed
Pull Request — master (#283)
by Phil
02:20
created

CachedRouter::buildRouter()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0852

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 13
cts 15
cp 0.8667
rs 8.8817
c 0
b 0
f 0
cc 6
nc 7
nop 1
crap 6.0852
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 3
    public function __construct(callable $builder, string $cacheFile, bool $cacheEnabled = true)
31
    {
32 3
        $this->builder = $builder;
33 3
        $this->cacheFile = $cacheFile;
34 3
        $this->cacheEnabled = $cacheEnabled;
35 3
    }
36
37 3
    public function dispatch(ServerRequestInterface $request): ResponseInterface
38
    {
39 3
        $router = $this->buildRouter($request);
40 3
        return $router->dispatch($request);
41
    }
42
43 3
    protected function buildRouter(ServerRequestInterface $request): Router
44
    {
45 3
        if (true === $this->cacheEnabled && file_exists($this->cacheFile)) {
46 3
            $cache  = file_get_contents($this->cacheFile);
47 3
            $router = u($cache, ['allowed_classes' => true]);
48
49 3
            if ($router instanceof Router) {
50 3
                return $router;
51
            }
52
        }
53
54 3
        $builder = $this->builder;
55 3
        $router  = $builder(new Router());
56
57 3
        if (false === $this->cacheEnabled) {
58
            return $router;
59
        }
60
61 3
        if ($router instanceof Router) {
62 3
            $router->prepareRoutes($request);
63 3
            file_put_contents($this->cacheFile, s($router));
64 3
            return $router;
65
        }
66
67
        throw new InvalidArgumentException('Invalid Router builder provided to cached router');
68
    }
69
}
70