Completed
Pull Request — master (#21)
by
unknown
14:49
created

Client::uploadFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 0
cts 0
cp 0
rs 9.424
c 0
b 0
f 0
cc 2
nc 2
nop 4
crap 6
1
<?php
2
3
namespace Softonic\GraphQL;
4
5
use GuzzleHttp\ClientInterface;
6
use GuzzleHttp\Exception\TransferException;
7
8
class Client
9
{
10
    private $httpClient;
11
    private $responseBuilder;
12
13 18
    public function __construct(ClientInterface $httpClient, ResponseBuilder $responseBuilder)
14
    {
15 18
        $this->httpClient = $httpClient;
16 18
        $this->responseBuilder = $responseBuilder;
17 18
    }
18
19
    /**
20
     * @throws \UnexpectedValueException When response body is not a valid json
21
     * @throws \RuntimeException         When there are transfer errors
22
     */
23 10
    public function query(string $query, array $variables = null): Response
24
    {
25
        $options = [
26
            'json' => [
27 10
                'query' => $query,
28
            ],
29
        ];
30 10
        if (!is_null($variables)) {
31 2
            $options['json']['variables'] = $variables;
32
        }
33
34
        try {
35 10
            $response = $this->httpClient->request('POST', '', $options);
36 4
        } catch (TransferException $e) {
37 4
            throw new \RuntimeException('Network Error.' . $e->getMessage(), 0, $e);
38
        }
39
40 6
        return $this->responseBuilder->build($response);
41
    }
42
43
    public function uploadFile(string $query, array $variables = null, string $file, string $fileName): Response
44
    {
45
        $options = [
46
            'multipart' => 
47
              [
48
                [
49
                    'name'     => 'query',
50
                    'contents' => $query,
51
52
                ],
53
                [
54
                    'name'     => 'variables',
55
                    'contents' => json_encode($variables)
56
                ],
57
                [
58
                    'name'     => 'file',
59
                    'contents' => $file,
60
                    'filename' => $fileName,
61
                ]
62
              ]
63
64
        ];
65
66
        try {
67
            $response = $this->httpClient->request('POST', '', $options);
68
        } catch (TransferException $e) {
69
            throw new \RuntimeException('Network Error.' . $e->getMessage(), 0, $e);
70
        }
71
72
        return $this->responseBuilder->build($response);
73
    }
74
}
75