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) |
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 |
|
return new Response( |
23
|
6 |
|
$normalizedResponse['data'], |
24
|
6 |
|
$normalizedResponse['dataObject'], |
25
|
6 |
|
$normalizedResponse['errors'] |
26
|
|
|
); |
27
|
|
|
} |
28
|
|
|
|
29
|
12 |
|
private function getNormalizedResponse(string $body) |
30
|
|
|
{ |
31
|
12 |
|
$decodedResponse = $this->getJsonDecodedResponse($body); |
32
|
|
|
|
33
|
10 |
|
if (false === array_key_exists('data', $decodedResponse) && empty($decodedResponse['errors'])) { |
34
|
4 |
|
throw new \UnexpectedValueException( |
35
|
4 |
|
'Invalid GraphQL JSON response. Response body: ' . json_encode($decodedResponse) |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
return [ |
40
|
6 |
|
'data' => $decodedResponse['data'] ?? [], |
41
|
6 |
|
'dataObject' => $this->dataObjectBuilder->build($decodedResponse['data'] ?? []), |
42
|
6 |
|
'errors' => $decodedResponse['errors'] ?? [], |
43
|
|
|
]; |
44
|
|
|
} |
45
|
|
|
|
46
|
12 |
|
private function getJsonDecodedResponse(string $body) |
47
|
|
|
{ |
48
|
12 |
|
$response = json_decode($body, true); |
49
|
|
|
|
50
|
12 |
|
$error = json_last_error(); |
51
|
12 |
|
if (JSON_ERROR_NONE !== $error) { |
52
|
2 |
|
throw new \UnexpectedValueException( |
53
|
2 |
|
'Invalid JSON response. Response body: ' . $body |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
10 |
|
return $response; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|