CacheRouteLoaderDecorator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 42
ccs 16
cts 16
cp 1
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getDirectories() 0 3 1
A addDirectory() 0 5 1
A __construct() 0 2 1
A getRoutes() 0 17 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jerowork\RouteAttributeProvider\RouteLoader\Cache;
6
7
use Generator;
8
use Jerowork\RouteAttributeProvider\RouteLoader\RouteLoaderInterface;
9
use JsonException;
10
use Psr\SimpleCache\CacheInterface;
11
12
final class CacheRouteLoaderDecorator implements RouteLoaderInterface
13
{
14
    use CreateCacheKeyTrait;
15
    use MapCachePayloadToLoadedRoutesTrait;
16
    use MapLoadedRoutesToCachePayloadTrait;
17
18 3
    public function __construct(private RouteLoaderInterface $routeLoader, private CacheInterface $cache)
19
    {
20 3
    }
21
22 2
    public function getDirectories() : array
23
    {
24 2
        return $this->routeLoader->getDirectories();
25
    }
26
27 2
    public function addDirectory(string ...$directories) : self
28
    {
29 2
        $this->routeLoader->addDirectory(...$directories);
30
31 2
        return $this;
32
    }
33
34
    /**
35
     * @throws JsonException
36
     */
37 2
    public function getRoutes() : Generator
38
    {
39 2
        $cacheKey = $this->createCacheKey($this->getDirectories());
40
        /** @var null|string $payload */
41 2
        $payload = $this->cache->get($cacheKey);
42
43 2
        if ($payload !== null) {
44 1
            yield from $this->mapCachePayloadToLoadedRoutes($payload);
45
46 1
            return;
47
        }
48
49 1
        $loadedRoutes = iterator_to_array($this->routeLoader->getRoutes());
50
51 1
        $this->cache->set($cacheKey, $this->mapLoadedRoutesToCachePayload(...$loadedRoutes));
52
53 1
        yield from $loadedRoutes;
54
    }
55
}
56