ResponseTransformer::transformHeader()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 9
ccs 7
cts 7
cp 1
c 0
b 0
f 0
rs 10
cc 3
nc 2
nop 1
crap 3
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 $needSequence
19
     * @return array
20
     * @throws TransformResponseException
21
     */
22 29
    public function transform(ResponseInterface $response, ?bool $needSequence = null): array
23
    {
24 29
        $body = (string)$response->getBody();
25
26 29
        if (!(strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0))
27 1
            throw new TransformResponseException('Error transforming response to array. Content-Type is not application/json');
28
29 28
        $content = json_decode($body, true);
30 28
        if (json_last_error() != JSON_ERROR_NONE)
31 1
            throw new TransformResponseException('Error transforming response to array. JSON_ERROR: ' . json_last_error());
32
33 27
        if ($needSequence)
34 1
            $content = array_merge($content, $this->transformHeader($response));
35
36 27
        return $content;
37
    }
38
39
    /**
40
     * @param ResponseInterface $response
41
     * @return array
42
     * @throws TransformResponseException
43
     */
44 4
    public function transformHeader(ResponseInterface $response): array
45
    {
46 4
        $responseHeaders = $response->getHeaders();
47 4
        if (!(isset($responseHeaders['Sequence'][0]) and is_numeric($responseHeaders['Sequence'][0])))
48 1
            throw new TransformResponseException('Error getting sequence from response headers.');
49
        else {
50 3
            $content = [];
51 3
            $content['Sequence'] = (int)$responseHeaders['Sequence'][0];
52 3
            return $content;
53
        }
54
    }
55
}