LazyResponseCollection::append()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace ScayTrase\Api\Rpc\Decorators;
4
5
use ScayTrase\Api\Rpc\ResponseCollectionInterface;
6
use ScayTrase\Api\Rpc\RpcClientInterface;
7
use ScayTrase\Api\Rpc\RpcRequestInterface;
8
9
final class LazyResponseCollection implements \IteratorAggregate, ResponseCollectionInterface
10
{
11
    /** @var bool */
12
    private $initialized = false;
13
    /** @var RpcRequestInterface[] */
14
    private $requests = [];
15
    /** @var RpcClientInterface */
16
    private $client;
17
    /** @var ResponseCollectionInterface */
18
    private $collection;
19
20
    /**
21
     * LazyResponseCollection constructor.
22
     *
23
     * @param RpcClientInterface $client
24
     */
25 8
    public function __construct(RpcClientInterface $client)
26
    {
27 8
        $this->client = $client;
28 8
    }
29
30
    /** {@inheritdoc} */
31 4
    public function getResponse(RpcRequestInterface $request)
32
    {
33 4
        if (!$this->isFrozen()) {
34 4
            $this->init();
35 4
        }
36
37 4
        return $this->collection->getResponse($request);
38
    }
39
40 8
    public function append(RpcRequestInterface $request)
41
    {
42 8
        if ($this->isFrozen()) {
43 1
            throw new \LogicException('Cannot add request to frozen lazy collection');
44
        }
45
46 8
        $this->requests[] = $request;
47 8
    }
48
49 8
    public function isFrozen()
50
    {
51 8
        return $this->initialized;
52
    }
53
54
    /** {@inheritdoc} */
55 3
    public function getIterator()
56
    {
57 3
        if (!$this->isFrozen()) {
58 3
            $this->init();
59 3
        }
60
61 3
        return $this->collection;
62
    }
63
64 7
    private function init()
65
    {
66 7
        $this->collection  = $this->client->invoke($this->requests);
67 7
        $this->requests    = [];
68 7
        $this->initialized = true;
69 7
    }
70
}
71