Completed
Branch master (888209)
by Pavel
04:20
created

JsonRpcResponseCollection::sync()   C

Complexity

Conditions 8
Paths 14

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8.8638

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 16
cts 21
cp 0.7619
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 18
nc 14
nop 0
crap 8.8638
1
<?php
2
3
namespace Bankiru\Api\BrowserKit;
4
5
use ScayTrase\Api\JsonRpc\Exception\JsonRpcProtocolException;
6
use ScayTrase\Api\JsonRpc\Exception\ResponseParseException;
7
use ScayTrase\Api\JsonRpc\JsonRpcNotificationResponse;
8
use ScayTrase\Api\JsonRpc\JsonRpcResponseInterface;
9
use ScayTrase\Api\JsonRpc\RequestTransformation;
10
use ScayTrase\Api\JsonRpc\SyncResponse;
11
use ScayTrase\Api\Rpc\Exception\RemoteCallFailedException;
12
use ScayTrase\Api\Rpc\ResponseCollectionInterface;
13
use ScayTrase\Api\Rpc\RpcRequestInterface;
14
use Symfony\Component\BrowserKit\Response;
15
16
final class JsonRpcResponseCollection implements \IteratorAggregate, ResponseCollectionInterface
17
{
18
    /** @var JsonRpcResponseInterface[] */
19
    protected $hashedResponses = [];
20
    /** @var  Response */
21
    private $response;
22
    /** @var  RequestTransformation[] */
23
    private $transformations;
24
    /** @var  JsonRpcResponseInterface[] */
25
    private $responses = [];
26
27
    /**
28
     * JsonRpcResponseCollection constructor.
29
     *
30
     * @param Response                $response
31
     * @param RequestTransformation[] $transformations
32
     */
33 2
    public function __construct(Response $response, array $transformations)
34
    {
35 2
        $this->response        = $response;
36 2
        $this->transformations = $transformations;
37 2
        $this->sync();
38 2
    }
39
40
    /** {@inheritdoc} */
41 2
    public function getIterator()
42
    {
43 2
        return new \ArrayIterator($this->responses);
44
    }
45
46
    /** {@inheritdoc} */
47 2
    public function getResponse(RpcRequestInterface $request)
48
    {
49 2
        if (array_key_exists(spl_object_hash($request), $this->hashedResponses)) {
50
            return $this->hashedResponses[spl_object_hash($request)];
51
        }
52
53 2
        $storedRequest = null;
54 2
        foreach ($this->transformations as $transformation) {
55 2
            if ($transformation->getOriginalCall() === $request) {
56 2
                $storedRequest = $transformation->getTransformedCall();
57 2
                break;
58
            }
59 2
        }
60
61 2
        if (null === $storedRequest) {
62
            throw new \OutOfBoundsException('Given request was not invoked for this collection');
63
        }
64
65 2
        if ($storedRequest->isNotification()) {
66 2
            $this->hashedResponses[spl_object_hash($request)] = new JsonRpcNotificationResponse();
67
68 2
            return $this->hashedResponses[spl_object_hash($request)];
69
        }
70
71 2
        if (!array_key_exists($storedRequest->getId(), $this->responses)) {
72
            throw JsonRpcProtocolException::requestSendButNotResponded($storedRequest);
73
        }
74
75 2
        $this->hashedResponses[spl_object_hash($request)] = $this->responses[$storedRequest->getId()];
76
77 2
        return $this->hashedResponses[spl_object_hash($request)];
78
    }
79
80 2
    private function sync()
81
    {
82 2
        if (200 !== $this->response->getStatus()) {
83
            throw new RemoteCallFailedException();
84
        }
85
86 2
        $data = (string)$this->response->getContent();
87
88
        // Null (empty response) is expected if only notifications were sent
89 2
        $rawResponses = [];
90
91 2
        if ('' !== $data) {
92 2
            $rawResponses = json_decode($data, false);
93 2
            if (json_last_error() !== JSON_ERROR_NONE) {
94
                throw ResponseParseException::notAJsonResponse();
95
            }
96 2
        }
97
98 2
        if (!is_array($rawResponses) && $rawResponses instanceof \stdClass) {
99
            $rawResponses = [$rawResponses];
100
        }
101
102 2
        $this->responses = [];
103 2
        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...
104
            try {
105 2
                $response = new SyncResponse($rawResponse);
106 2
            } catch (ResponseParseException $exception) {
107
                //todo: logging??? (@scaytrase)
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
108
                continue;
109
            }
110
111 2
            $this->responses[$response->getId()] = $response;
112 2
        }
113 2
    }
114
}
115