CacheableResponseCollection   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 4
dl 0
loc 71
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getResponse() 0 18 2
A __construct() 0 13 2
A getIterator() 0 13 3
1
<?php
2
3
namespace ScayTrase\Api\Rpc\Decorators;
4
5
use Psr\Cache\CacheItemInterface;
6
use Psr\Cache\CacheItemPoolInterface;
7
use ScayTrase\Api\Rpc\ResponseCollectionInterface;
8
use ScayTrase\Api\Rpc\RpcRequestInterface;
9
10
final class CacheableResponseCollection implements \IteratorAggregate, ResponseCollectionInterface
11
{
12
    /** @var  CacheItemPoolInterface */
13
    private $cache;
14
    /** @var  CacheKeyStrategyInterface */
15
    private $keyStrategy;
16
    /** @var  array */
17
    private $items;
18
    /** @var  ResponseCollectionInterface */
19
    private $proxiedCollection;
20
    /** @var  int|null */
21
    private $ttl;
22
23
    /**
24
     * CacheableResponseCollection constructor.
25
     *
26
     * @param CacheItemPoolInterface      $cache
27
     * @param CacheKeyStrategyInterface   $keyStrategy
28
     * @param array                       $items
29
     * @param ResponseCollectionInterface $proxiedCollection
30
     * @param int|null                    $ttl
31
     */
32 3
    public function __construct(
33
        CacheItemPoolInterface $cache,
34
        CacheKeyStrategyInterface $keyStrategy,
35
        array $items,
36
        ResponseCollectionInterface $proxiedCollection,
37
        $ttl
38
    ) {
39 3
        $this->cache             = $cache;
40 3
        $this->keyStrategy       = $keyStrategy;
41 3
        $this->items             = $items;
42 3
        $this->proxiedCollection = $proxiedCollection;
43 3
        $this->ttl               = $ttl ?: null;
44 3
    }
45
46
    /** {@inheritdoc} */
47 3
    public function getResponse(RpcRequestInterface $request)
48
    {
49 3
        $key = $this->keyStrategy->getKey($request);
50
51
        /** @var CacheItemInterface $item */
52 3
        $item = $this->items[$key]['item'];
53
54 3
        if ($item->isHit()) {
55 3
            return $item->get();
56
        }
57
58 3
        $item->expiresAfter($this->ttl);
59 3
        $item->set($this->proxiedCollection->getResponse($request));
60
61 3
        $this->cache->save($item);
62
63 3
        return $item->get();
64
    }
65
66
    /** {@inheritdoc} */
67 1
    public function getIterator()
68
    {
69 1
        foreach ($this->items as $key => $data) {
70
            /** @var CacheItemInterface $item */
71 1
            $item = $data['item'];
72
73 1
            if ($item->isHit()) {
74 1
                yield $item->get();
75 1
            }
76
77 1
            yield $this->getResponse($data['request']);
78 1
        }
79 1
    }
80
}
81