Completed
Branch master (c90d5b)
by Riccardo
02:51
created

ResponseBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 36
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 8 1
A getNormalizedResponse() 0 13 2
A getJsonDecodedResponse() 0 10 2
1
<?php
2
3
namespace Softonic\GraphQL;
4
5
use Psr\Http\Message\ResponseInterface;
6
7
class ResponseBuilder
8
{
9 10
    public function build(ResponseInterface $httpResponse)
10
    {
11 10
        $body = $httpResponse->getBody();
12
        
13 10
        $normalizedResponse = $this->getNormalizedResponse($body);
14
15 4
        return new Response($normalizedResponse['data'], $normalizedResponse['errors']);
16
    }
17
18 10
    private function getNormalizedResponse(string $body)
19
    {
20 10
        $decodedResponse = $this->getJsonDecodedResponse($body);
21
        
22 8
        if (!array_key_exists('data', $decodedResponse)) {
23 4
            throw new \UnexpectedValueException('Invalid GraphQL JSON response.');
24
        }
25
26
        return [
27 4
            'data' => $decodedResponse['data'] ?? [],
28 2
            'errors' => $decodedResponse['errors'] ?? [],
29
        ];
30
    }
31
32 10
    private function getJsonDecodedResponse(string $body)
33
    {
34 10
        $response = json_decode($body, true);
35
36 10
        $error = json_last_error();
37 10
        if (JSON_ERROR_NONE !== $error) {
38 2
            throw new \UnexpectedValueException('Invalid JSON response.');
39
        }
40 8
        return $response;
41
    }
42
}
43