Completed
Push — master ( b0f401...90606c )
by Mikhail
01:11
created

ResponseTransformer::transformHeader()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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