Passed
Push — feature/coverage ( 34ed7c )
by Darío
02:51
created

GuzzleResponse::parseJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
namespace EasyHttp\GuzzleLayer;
4
5
use EasyHttp\GuzzleLayer\Concerns\NeedsParseHeaders;
6
use EasyHttp\LayerContracts\Contracts\HttpClientResponse;
7
use EasyHttp\LayerContracts\Exceptions\ImpossibleToParseJsonException;
8
use Psr\Http\Message\ResponseInterface;
9
10
class GuzzleResponse implements HttpClientResponse
11
{
12
    use NeedsParseHeaders;
13
14
    protected ResponseInterface $response;
15
16 13
    public function __construct(ResponseInterface $response)
17
    {
18 13
        $this->response = $response;
19 13
    }
20
21 5
    public function getStatusCode(): int
22
    {
23 5
        return $this->response->getStatusCode();
24
    }
25
26 1
    public function getHeaders(): array
27
    {
28 1
        return $this->parseHeaders($this->response->getHeaders());
29
    }
30
31 1
    public function getBody(): string
32
    {
33 1
        return $this->toString();
34
    }
35
36 11
    public function parseJson(): array
37
    {
38 11
        $response = $this->toString();
39 11
        $data     = json_decode($response, true);
40
41 11
        if (! $data) {
42 2
            throw new ImpossibleToParseJsonException(
43
                'Service response could not be parsed to JSON, Response: ' .
44 2
                $response . ', Reason: ' . json_last_error()
45
            );
46
        }
47
48 9
        return $data;
49
    }
50
51 12
    private function toString(): string
52
    {
53 12
        $stream = $this->response->getBody();
54 12
        $stream->rewind();
55
56 12
        return $stream->getContents();
57
    }
58
}
59