Completed
Push — master ( f61680...98184f )
by Pavel
02:28
created

CacheableResponseCollection::getIterator()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
crap 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