CacheableRpcClient   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 6
dl 0
loc 71
ccs 35
cts 35
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 2
B invoke() 0 33 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 3
    public function __construct(
30
        RpcClientInterface $decoratedClient,
31
        CacheItemPoolInterface $cache,
32
        $ttl = null,
33
        $strategy = self::DEFAULT_KEY_PREFIX
34
    ) {
35 3
        $this->decoratedClient = $decoratedClient;
36 3
        $this->cache           = $cache;
37 3
        $this->ttl             = $ttl;
38
39 3
        if (!$strategy instanceof CacheKeyStrategyInterface) {
40 3
            $this->keyStrategy = new Sha1KeyStrategy((string)$strategy);
41 3
        }
42 3
    }
43
44
    /** {@inheritdoc} */
45 3
    public function invoke($calls)
46
    {
47 3
        $isArray = true;
48 3
        if (!is_array($calls)) {
49 2
            $isArray = false;
50 2
            $calls = [$calls];
51 2
        }
52
53 3
        $items           = [];
54 3
        $proxiedRequests = [];
55 3
        foreach ($calls as $call) {
56 3
            $key                    = $this->keyStrategy->getKey($call);
57 3
            $item                   = $this->cache->getItem($key);
58 3
            $items[$key]['request'] = $call;
59 3
            $items[$key]['item']    = $item;
60 3
            if (!$item->isHit()) {
61 3
                $proxiedRequests[] = $call;
62 3
            }
63 3
        }
64
65
        // Prevent batch calls when not necessary
66 3
        if (count($proxiedRequests) === 1 && !$isArray) {
67 1
            $proxiedRequests = array_shift($proxiedRequests);
68 1
        }
69
70 3
        return new CacheableResponseCollection(
71 3
            $this->cache,
72 3
            $this->keyStrategy,
73 3
            $items,
74 3
            $this->decoratedClient->invoke($proxiedRequests),
75 3
            $this->ttl
76 3
        );
77
    }
78
}
79