Passed
Push — main ( c1a481...89a1c8 )
by Jeroen
02:41 queued 01:15
created

CacheRouteLoaderDecorator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
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 41
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 getRoutes() 0 16 2
A __construct() 0 2 1
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 2
        $payload  = $this->cache->get($cacheKey);
41
42 2
        if ($payload !== null) {
43 1
            yield from $this->mapCachePayloadToLoadedRoutes($payload);
44
45 1
            return;
46
        }
47
48 1
        $loadedRoutes = iterator_to_array($this->routeLoader->getRoutes());
49
50 1
        $this->cache->set($cacheKey, $this->mapLoadedRoutesToCachePayload(...$loadedRoutes));
51
52 1
        yield from $loadedRoutes;
53 1
    }
54
}
55