Passed
Branch master (f61680)
by Pavel
02:38
created

CacheableRpcClient   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 87.88%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 6
dl 0
loc 69
ccs 29
cts 33
cp 0.8788
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 2
B invoke() 0 31 6
1
<?php
2
3
namespace ScayTrase\Api\Rpc\Decorators;
4
5
use Psr\Cache\CacheItemPoolInterface;
6
use ScayTrase\Api\Rpc\RpcClientInterface;
7
8
final class CacheableRpcClient implements RpcClientInterface
9
{
10
    const DEFAULT_KEY_PREFIX = 'rpc_client_cache';
11
12
    /** @var CacheItemPoolInterface */
13
    private $cache;
14
    /** @var RpcClientInterface */
15
    private $decoratedClient;
16
    /** @var CacheKeyStrategyInterface */
17
    private $keyStrategy;
18
    /** @var int|null */
19
    private $ttl;
20
21
    /**
22
     * CacheableRpcClient constructor.
23
     *
24
     * @param RpcClientInterface               $decoratedClient
25
     * @param CacheItemPoolInterface           $cache
26
     * @param int|null                         $ttl
27
     * @param CacheKeyStrategyInterface|string $strategy
28
     */
29 1
    public function __construct(
30
        RpcClientInterface $decoratedClient,
31
        CacheItemPoolInterface $cache,
32
        $ttl = null,
33
        $strategy = self::DEFAULT_KEY_PREFIX
34
    ) {
35 1
        $this->decoratedClient = $decoratedClient;
36 1
        $this->cache           = $cache;
37 1
        $this->ttl             = $ttl;
38
39 1
        if (!$strategy instanceof CacheKeyStrategyInterface) {
40 1
            $this->keyStrategy = new Sha1KeyStrategy((string)$strategy);
41 1
        }
42 1
    }
43
44
    /** {@inheritdoc} */
45 1
    public function invoke($calls)
46
    {
47 1
        if (!is_array($calls)) {
48
            $calls = [$calls];
49
        }
50
51 1
        $items           = [];
52 1
        $proxiedRequests = [];
53 1
        foreach ($calls as $call) {
54 1
            $key                    = $this->keyStrategy->getKey($call);
55 1
            $item                   = $this->cache->getItem($key);
56 1
            $items[$key]['request'] = $call;
57 1
            $items[$key]['item']    = $item;
58 1
            if (!$item->isHit()) {
59 1
                $proxiedRequests[] = $call;
60 1
            }
61 1
        }
62
63
        // Prevent batch calls when not necessary
64 1
        if (count($proxiedRequests) === 1 && !is_array($calls)) {
65
            $proxiedRequests = array_shift($proxiedRequests);
66
        }
67
68 1
        return new CacheableResponseCollection(
69 1
            $this->cache,
70 1
            $this->keyStrategy,
71 1
            $items,
72 1
            $this->decoratedClient->invoke($proxiedRequests),
73 1
            $this->ttl
74 1
        );
75
    }
76
}
77