Completed
Push — master ( 40bf07...dbb18c )
by Mikhail
01:23
created

ResponseTransformer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 2
dl 0
loc 44
ccs 18
cts 19
cp 0.9474
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 18 4
A transformHeader() 0 11 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 27
    public function transform(ResponseInterface $response, ?bool $needSequence = null): array
23
    {
24 27
        $body = (string)$response->getBody();
25 27
        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 1
                    $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 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
}