|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Softonic\GraphQL; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\ClientInterface; |
|
6
|
|
|
use GuzzleHttp\Exception\TransferException; |
|
7
|
|
|
use Softonic\GraphQL\DataObjects\Mutation\MutationObject; |
|
8
|
|
|
|
|
9
|
|
|
class Client |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var ClientInterface |
|
13
|
|
|
*/ |
|
14
|
|
|
private $httpClient; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @var ResponseBuilder |
|
18
|
|
|
*/ |
|
19
|
|
|
private $responseBuilder; |
|
20
|
|
|
|
|
21
|
20 |
|
public function __construct(ClientInterface $httpClient, ResponseBuilder $responseBuilder) |
|
22
|
|
|
{ |
|
23
|
20 |
|
$this->httpClient = $httpClient; |
|
24
|
20 |
|
$this->responseBuilder = $responseBuilder; |
|
25
|
20 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @throws \UnexpectedValueException When response body is not a valid json |
|
29
|
|
|
* @throws \RuntimeException When there are transfer errors |
|
30
|
|
|
*/ |
|
31
|
10 |
|
public function query(string $query, array $variables = null): Response |
|
32
|
|
|
{ |
|
33
|
10 |
|
return $this->executeQuery($query, $variables); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* @throws \UnexpectedValueException When response body is not a valid json |
|
38
|
|
|
* @throws \RuntimeException When there are transfer errors |
|
39
|
|
|
*/ |
|
40
|
2 |
|
public function mutate(string $query, MutationObject $mutation): Response |
|
41
|
|
|
{ |
|
42
|
2 |
|
return $this->executeQuery($query, $mutation); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
12 |
|
private function executeQuery(string $query, $variables): Response |
|
46
|
|
|
{ |
|
47
|
|
|
$options = [ |
|
48
|
|
|
'json' => [ |
|
49
|
12 |
|
'query' => $query, |
|
50
|
|
|
], |
|
51
|
|
|
]; |
|
52
|
12 |
|
if (!is_null($variables)) { |
|
53
|
4 |
|
$options['json']['variables'] = $variables; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
try { |
|
57
|
12 |
|
$response = $this->httpClient->request('POST', '', $options); |
|
58
|
4 |
|
} catch (TransferException $e) { |
|
59
|
4 |
|
throw new \RuntimeException('Network Error.' . $e->getMessage(), 0, $e); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
8 |
|
return $this->responseBuilder->build($response); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|