|
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 |
|
$message = 'Invalid GraphQL JSON response.'; |
|
24
|
|
|
if (array_key_exists('errors', $decodedResponse) |
|
25
|
|
|
&& is_array($decodedResponse['errors']) |
|
26
|
|
|
&& array_key_exists('message', $decodedResponse['errors'][0])) { |
|
27
|
4 |
|
$message .= ' ' . stripslashes($decodedResponse['errors'][0]['message']); |
|
28
|
4 |
|
} |
|
29
|
|
|
throw new \UnexpectedValueException($message); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
10 |
|
return [ |
|
33
|
|
|
'data' => $decodedResponse['data'] ?? [], |
|
34
|
10 |
|
'errors' => $decodedResponse['errors'] ?? [], |
|
35
|
|
|
]; |
|
36
|
10 |
|
} |
|
37
|
10 |
|
|
|
38
|
2 |
|
private function getJsonDecodedResponse(string $body) |
|
39
|
|
|
{ |
|
40
|
8 |
|
$response = json_decode($body, true); |
|
41
|
|
|
|
|
42
|
|
|
$error = json_last_error(); |
|
43
|
|
|
if (JSON_ERROR_NONE !== $error) { |
|
44
|
|
|
$message = 'Invalid JSON response.'; |
|
45
|
|
|
if (json_last_error_msg()) { |
|
46
|
|
|
$message .= ' ' . json_last_error_msg(); |
|
47
|
|
|
} |
|
48
|
|
|
throw new \UnexpectedValueException($message); |
|
49
|
|
|
} |
|
50
|
|
|
return $response; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|