Completed
Push — master ( 59767d...4fd685 )
by Mikhail
01:23
created

ResponseTransformer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 2
dl 0
loc 30
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B transform() 0 20 7
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 $needHeader Whenever you need response header in your data
19
     * @param bool|null $noBody When HEAD Method used you dont'need to parse response Body
20
     * @return array
21
     * @throws TransformResponseException
22
     */
23 29
    public function transform(ResponseInterface $response, ?bool $needHeader = null, ?bool $noBody = null): array
24
    {
25 29
        $content = [];
26
27 29
        if (is_null($noBody) or !$noBody) {
28 27
            $body = (string)$response->getBody();
29 27
            if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) {
30 26
                $content = json_decode($body, true);
31 26
                if (!(JSON_ERROR_NONE === json_last_error()))
32 26
                    throw new TransformResponseException('Error transforming response to array. JSON_ERROR: ' . json_last_error());
33
            } else
34 1
                throw new TransformResponseException('Error transforming response to array. Content-Type is not application/json');
35
        }
36
37 27
        if (!is_null($needHeader) and $needHeader) {
38 2
            $content['responseHeaders'] = $response->getHeaders();
39
        }
40
41 27
        return $content;
42
    }
43
}
44