Completed
Push — master ( 54a1aa...415108 )
by Mikhail
01:23
created

ResponseTransformer::transform()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 16
cts 16
cp 1
rs 8.1795
c 0
b 0
f 0
cc 8
nc 9
nop 2
crap 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace R3bers\BittrexApi\Message;
6
7
use Psr\Http\Message\ResponseInterface;
8
use R3bers\BittrexApi\Exception\TransformResponseException;
9
10
/**
11
 * Class ResponseTransformer
12
 * @package R3bers\BittrexApi\Message
13
 */
14
class ResponseTransformer
15
{
16
    /**
17
     * @param ResponseInterface $response
18
     * @param bool|null $onlyHeader If null header not included in response to back compatibility, if true only header return.
19
     * @return array
20
     * @throws TransformResponseException
21
     */
22 29
    public function transform(ResponseInterface $response, ?bool $onlyHeader = null): array
23
    {
24
25 29
        $content = [];
26
27 29
        if (isset($onlyHeader)) {
28 2
            $responseHeaders = $response->getHeaders();
29 2
            if (isset($responseHeaders['Sequence'][0]) and is_numeric($responseHeaders['Sequence'][0])) {
30 1
                $content['Sequence'] = (int)$responseHeaders['Sequence'][0];
31
            }else{
32 1
                throw new TransformResponseException('Error getting sequence from response headers.');
33
            }
34
        }
35
36 28
        if (is_null($onlyHeader) or !$onlyHeader) {
37 27
            if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) {
38 26
                $body = (string)$response->getBody();
39 26
                $bodyArray = json_decode($body, true);
40 26
                if (json_last_error() != JSON_ERROR_NONE) {
41 1
                    throw new TransformResponseException('Error transforming response to array. JSON_ERROR: ' . json_last_error());
42
                } else {
43 25
                    $content = array_merge($content, $bodyArray);
44
                }
45
            } else {
46 1
                throw new TransformResponseException('Error transforming response to array. Content-Type is not application/json');
47
            }
48
        }
49
50 26
        return $content;
51
52
    }
53
}
54