Passed
Push — main ( 659659...7cf3e5 )
by Jeroen
09:29
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 14
cts 14
cp 1
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A addDirectory() 0 5 1
A getRoutes() 0 16 2
A getDirectories() 0 3 1
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
    public function __construct(private RouteLoaderInterface $routeLoader, private CacheInterface $cache)
19
    {
20
    }
21 3
22
    public function getDirectories() : array
23 3
    {
24 3
        return $this->routeLoader->getDirectories();
25 3
    }
26
27
    public function addDirectory(string ...$directories) : self
28
    {
29
        $this->routeLoader->addDirectory(...$directories);
30 2
31
        return $this;
32 2
    }
33 2
34
    /**
35 2
     * @throws JsonException
36 1
     */
37
    public function getRoutes() : Generator
38 1
    {
39
        $cacheKey = $this->createCacheKey($this->getDirectories());
40
        $payload  = $this->cache->get($cacheKey);
41 1
42
        if ($payload !== null) {
43 1
            yield from $this->mapCachePayloadToLoadedRoutes($payload);
44
45 1
            return;
46 1
        }
47
48
        $loadedRoutes = iterator_to_array($this->routeLoader->getRoutes());
49
50
        $this->cache->set($cacheKey, $this->mapLoadedRoutesToCachePayload(...$loadedRoutes));
51
52
        yield from $loadedRoutes;
53
    }
54
}
55