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

LazyResponseCollection::getIterator()   A

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 0
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 4
    public function __construct(RpcClientInterface $client)
26
    {
27 4
        $this->client = $client;
28 4
    }
29
30
    /** {@inheritdoc} */
31 3
    public function getResponse(RpcRequestInterface $request)
32
    {
33 3
        if (!$this->isFrozen()) {
34 3
            $this->init();
35 3
        }
36
37 3
        return $this->collection->getResponse($request);
38
    }
39
40 4
    public function append(RpcRequestInterface $request)
41
    {
42 4
        if ($this->isFrozen()) {
43 1
            throw new \LogicException('Cannot add request to frozen lazy collection');
44
        }
45
46 4
        $this->requests[] = $request;
47 4
    }
48
49 4
    public function isFrozen()
50
    {
51 4
        return $this->initialized;
52
    }
53
54
    /** {@inheritdoc} */
55 1
    public function getIterator()
56
    {
57 1
        if (!$this->isFrozen()) {
58 1
            $this->init();
59 1
        }
60
61 1
        return $this->collection;
62
    }
63
64 4
    private function init()
65
    {
66 4
        $this->collection  = $this->client->invoke($this->requests);
67 4
        $this->requests    = [];
68 4
        $this->initialized = true;
69 4
    }
70
}
71