Completed
Push — master ( dda319...6c9b4c )
by Mikhail
01:15
created

ResponseTransformer::transform()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 10
cts 11
cp 0.9091
rs 9.6666
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0119
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 26
            $content = json_decode($body, true);
27 26
            if (JSON_ERROR_NONE === json_last_error()) {
28 25
                if ($needSequence)
29
                    $content = array_merge($content, $this->transformHeader($response));
30 25
                return $content;
31
            }
32
33 1
            throw new TransformResponseException('Error transforming response to array. JSON_ERROR: '
34 1
                . json_last_error());
35
        }
36
37 2
        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 1
    public function transformHeader(ResponseInterface $response): array
47
    {
48 1
        $responseHeaders = $response->getHeaders();
49 1
        if (!(isset($responseHeaders['Sequence'][0]) and is_numeric($responseHeaders['Sequence'][0])))
50
            throw new TransformResponseException('Error getting sequence from response headers.');
51
        else {
52 1
            $content = [];
53 1
            $content['Sequence'] = (int)$responseHeaders['Sequence'][0];
54 1
            return $content;
55
        }
56
    }
57
}