ResponseBuilder::build()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Softonic\GraphQL;
4
5
use Psr\Http\Message\ResponseInterface;
6
7
class ResponseBuilder
8
{
9 12
    public function build(ResponseInterface $httpResponse)
10
    {
11 12
        $body = $httpResponse->getBody();
12
13 12
        $normalizedResponse = $this->getNormalizedResponse($body);
14
15 6
        return new Response($normalizedResponse['data'], $normalizedResponse['errors']);
16
    }
17
18 12
    private function getNormalizedResponse(string $body)
19
    {
20 12
        $decodedResponse = $this->getJsonDecodedResponse($body);
21
22 10
        if (false === array_key_exists('data', $decodedResponse) && empty($decodedResponse['errors'])) {
23 4
            throw new \UnexpectedValueException(
24 4
                'Invalid GraphQL JSON response. Response body: ' . json_encode($decodedResponse)
25
            );
26
        }
27
28
        return [
29 6
            'data' => $decodedResponse['data'] ?? [],
30 6
            'errors' => $decodedResponse['errors'] ?? [],
31
        ];
32
    }
33
34 12
    private function getJsonDecodedResponse(string $body)
35
    {
36 12
        $response = json_decode($body, true);
37
38 12
        $error = json_last_error();
39 12
        if (JSON_ERROR_NONE !== $error) {
40 2
            throw new \UnexpectedValueException(
41 2
                'Invalid JSON response. Response body: ' . $body
42
            );
43
        }
44
45 10
        return $response;
46
    }
47
}
48