Passed
Push — develop ( 7a32b4...bc8c97 )
by Darío
05:40 queued 03:21
created

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