Completed
Push — master ( f51ba2...e89362 )
by Mikhail
01:20
created

ResponseTransformer::transform()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7.0283

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 12
cp 0.9167
rs 8.8333
c 0
b 0
f 0
cc 7
nc 6
nop 3
crap 7.0283
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 27
    public function transform(ResponseInterface $response, ?bool $needHeader = null, ?bool $noBody = null): array
24
    {
25 27
        $content = [];
26 27
        if (is_null($noBody) or !$noBody) {
27 27
            $body = (string)$response->getBody();
28 27
            if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0)
29 26
                if (JSON_ERROR_NONE === json_last_error())
30 26
                    $content = json_decode($body, true);
31
                else
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 26
        if (!is_null($needHeader) and $needHeader) {
37
            $content['responseHeaders'] = $response->getHeaders();
38
        }
39 26
        return $content;
40
    }
41
}
42