Passed
Push — master ( b091a1...a43e6f )
by Pavel
03:13
created

JsonRpcResponseCollection   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 128
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 74.13%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 11
dl 0
loc 128
ccs 43
cts 58
cp 0.7413
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A getIterator() 0 6 1
C getResponse() 0 34 7
C sync() 0 52 10
1
<?php
2
3
namespace ScayTrase\Api\JsonRpc;
4
5
use GuzzleHttp\Exception\GuzzleException;
6
use GuzzleHttp\Promise\PromiseInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\NullLogger;
10
use ScayTrase\Api\JsonRpc\Exception\JsonRpcProtocolException;
11
use ScayTrase\Api\JsonRpc\Exception\ResponseParseException;
12
use ScayTrase\Api\Rpc\Exception\RemoteCallFailedException;
13
use ScayTrase\Api\Rpc\ResponseCollectionInterface;
14
use ScayTrase\Api\Rpc\RpcRequestInterface;
15
16
/**
17
 * Class JsonRpcResponseCollection
18
 *
19
 * Json Rpc Collection contains responses only for non-notification responses
20
 * getResponse method will provide response stub for notification if request was successful
21
 */
22
final class JsonRpcResponseCollection implements \IteratorAggregate, ResponseCollectionInterface
23
{
24
    /** @var JsonRpcResponseInterface[] */
25
    private $hashedResponses = [];
26
    /** @var  RequestTransformation[] */
27
    private $transformations;
28
    /** @var  PromiseInterface */
29
    private $promise;
30
    /** @var  JsonRpcResponseInterface[] */
31
    private $responses = [];
32
33
    /** @var bool */
34
    private $synchronized = false;
35
    /**
36
     * @var LoggerInterface
37
     */
38
    private $logger;
39
40
    /**
41
     * JsonRpcResponseCollection constructor.
42
     * @param PromiseInterface $promise
43
     * @param RequestTransformation[] $transformations
44
     * @param LoggerInterface|null $logger
45
     */
46 17
    public function __construct(PromiseInterface $promise, array $transformations, LoggerInterface $logger = null)
47
    {
48 17
        $this->promise = $promise;
49 17
        $this->transformations = $transformations;
50 17
        $this->logger = $logger ?: new NullLogger();
51 17
    }
52
53
    /** {@inheritdoc} */
54
    public function getIterator()
55
    {
56
        $this->sync();
57
58
        return new \ArrayIterator($this->responses);
59
    }
60
61
    /** {@inheritdoc} */
62 7
    public function getResponse(RpcRequestInterface $request)
63
    {
64 7
        if (array_key_exists(spl_object_hash($request), $this->hashedResponses)) {
65
            return $this->hashedResponses[spl_object_hash($request)];
66
        }
67
68 7
        $this->sync();
69
70 5
        $storedRequest = null;
71 5
        foreach ($this->transformations as $transformation) {
72 5
            if ($transformation->getOriginalCall() === $request) {
73 5
                $storedRequest = $transformation->getTransformedCall();
74 5
                break;
75
            }
76 5
        }
77
78 5
        if (null === $storedRequest) {
79
            throw new \OutOfBoundsException('Given request was not invoked for this collection');
80
        }
81
82 5
        if ($storedRequest->isNotification()) {
83 2
            $this->hashedResponses[spl_object_hash($request)] = new JsonRpcNotificationResponse();
84
85 2
            return $this->hashedResponses[spl_object_hash($request)];
86
        }
87
88 4
        if (!array_key_exists($storedRequest->getId(), $this->responses)) {
89
            throw JsonRpcProtocolException::requestSendButNotResponded($storedRequest);
90
        }
91
92 4
        $this->hashedResponses[spl_object_hash($request)] = $this->responses[$storedRequest->getId()];
93
94 4
        return $this->hashedResponses[spl_object_hash($request)];
95
    }
96
97 7
    private function sync()
98
    {
99 7
        if ($this->synchronized) {
100 1
            return;
101
        }
102
103
        try {
104
            /** @var ResponseInterface $clientResponse */
105 7
            $clientResponse = $this->promise->wait();
106 5
            if (200 !== $clientResponse->getStatusCode()) {
107
                throw new RemoteCallFailedException('Response was not successful');
108
            }
109 7
        } catch (GuzzleException $exception) {
110 2
            throw new RemoteCallFailedException($exception->getMessage(), 0, $exception);
111
        }
112
113 5
        $data = (string)$clientResponse->getBody();
114
115
        // Null (empty response) is expected if only notifications were sent
116 5
        $rawResponses = [];
117
118 5
        if ('' !== $data) {
119 4
            $rawResponses = json_decode($data, false);
120 4
            if (json_last_error() !== JSON_ERROR_NONE) {
121
                throw ResponseParseException::notAJsonResponse();
122
            }
123 4
        }
124
125 5
        if (!is_array($rawResponses) && $rawResponses instanceof \stdClass) {
126
            $rawResponses = [$rawResponses];
127
        }
128
129 5
        $this->responses = [];
130 5
        foreach ($rawResponses as $rawResponse) {
0 ignored issues
show
Bug introduced by
The expression $rawResponses of type object|integer|double|string|null|boolean|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
131
            try {
132 4
                $response = new SyncResponse($rawResponse);
133 4
            } catch (ResponseParseException $exception) {
134
                $this->logger->warning(
135
                    'Invalid JSON-RPC response skipped: '.$exception->getMessage(),
136
                    [
137
                        'data' => json_decode(json_encode($rawResponse), true),
138
                    ]
139
                );
140
141
                continue;
142
            }
143
144 4
            $this->responses[$response->getId()] = $response;
145 5
        }
146
147 5
        $this->synchronized = true;
148 5
    }
149
}
150