|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Softonic\GraphQL; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
|
|
7
|
|
|
class ResponseBuilder |
|
8
|
|
|
{ |
|
9
|
|
|
private $dataObjectBuilder; |
|
10
|
|
|
|
|
11
|
20 |
|
public function __construct(DataObjectBuilder $dataObjectBuilder = null) |
|
12
|
|
|
{ |
|
13
|
20 |
|
$this->dataObjectBuilder = $dataObjectBuilder; |
|
14
|
20 |
|
} |
|
15
|
|
|
|
|
16
|
12 |
|
public function build(ResponseInterface $httpResponse) |
|
17
|
|
|
{ |
|
18
|
12 |
|
$body = $httpResponse->getBody(); |
|
19
|
|
|
|
|
20
|
12 |
|
$normalizedResponse = $this->getNormalizedResponse($body); |
|
21
|
|
|
|
|
22
|
6 |
|
$dataObject = array_key_exists('dataObject', $normalizedResponse) |
|
23
|
6 |
|
? $normalizedResponse['dataObject'] |
|
24
|
6 |
|
: []; |
|
25
|
|
|
|
|
26
|
6 |
|
return new Response( |
|
27
|
6 |
|
$normalizedResponse['data'], |
|
28
|
6 |
|
$normalizedResponse['errors'], |
|
29
|
|
|
$dataObject |
|
30
|
|
|
); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
12 |
|
private function getNormalizedResponse(string $body) |
|
34
|
|
|
{ |
|
35
|
12 |
|
$decodedResponse = $this->getJsonDecodedResponse($body); |
|
36
|
|
|
|
|
37
|
10 |
|
if (false === array_key_exists('data', $decodedResponse) && empty($decodedResponse['errors'])) { |
|
38
|
4 |
|
throw new \UnexpectedValueException( |
|
39
|
4 |
|
'Invalid GraphQL JSON response. Response body: ' . json_encode($decodedResponse) |
|
40
|
|
|
); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$result = [ |
|
44
|
6 |
|
'data' => $decodedResponse['data'] ?? [], |
|
45
|
6 |
|
'errors' => $decodedResponse['errors'] ?? [], |
|
46
|
|
|
]; |
|
47
|
|
|
|
|
48
|
6 |
|
if (!is_null($this->dataObjectBuilder)) { |
|
49
|
6 |
|
$result['dataObject'] = $this->dataObjectBuilder->buildQuery($decodedResponse['data'] ?? []); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
6 |
|
return $result; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
12 |
|
private function getJsonDecodedResponse(string $body) |
|
56
|
|
|
{ |
|
57
|
12 |
|
$response = json_decode($body, true); |
|
58
|
|
|
|
|
59
|
12 |
|
$error = json_last_error(); |
|
60
|
12 |
|
if (JSON_ERROR_NONE !== $error) { |
|
61
|
2 |
|
throw new \UnexpectedValueException( |
|
62
|
2 |
|
'Invalid JSON response. Response body: ' . $body |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
10 |
|
return $response; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|