Passed
Push — remanufacture/json-object-deco... ( 5405f8...fe5ece )
by Bas
05:33
created

ArangoClient::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ArangoClient;
6
7
use ArangoClient\Exceptions\ArangoException;
8
use ArangoClient\Http\HttpClientConfig;
9
use ArangoClient\Http\HttpRequestOptions;
10
use ArangoClient\Statement\Statement;
11
use ArangoClient\Transactions\SupportsTransactions;
12
use GuzzleHttp\Client as GuzzleClient;
13
use GuzzleHttp\Exception\GuzzleException;
14
use GuzzleHttp\Exception\RequestException;
15
use Psr\Http\Message\ResponseInterface;
16
use Spatie\DataTransferObject\Exceptions\UnknownProperties;
17
use stdClass;
18
use Throwable;
19
use Traversable;
20
21
/**
22
 * The arangoClient handles connections to ArangoDB's HTTP REST API.
23
 *
24
 * @see https://www.arangodb.com/docs/stable/http/
25
 */
26
class ArangoClient
27
{
28
    use HandlesJson;
29
    use HasManagers;
30
    use SupportsTransactions;
31
32
    protected GuzzleClient $httpClient;
33
34
    protected HttpClientConfig $config;
35
36
    /**
37
     * ArangoClient constructor.
38
     *
39
     * @param  array<string|numeric|null>  $config
40
     * @param  GuzzleClient|null  $httpClient
41 104
     * @throws UnknownProperties
42
     */
43 104
    public function __construct(array $config = [], GuzzleClient $httpClient = null)
44 104
    {
45
        $config['endpoint'] = $this->generateEndpoint($config);
46 104
        $this->config = new HttpClientConfig($config);
47 104
48
        $this->httpClient = $httpClient ?? new GuzzleClient($this->config->mapGuzzleHttpClientConfig());
49
    }
50
51
    /**
52
     * @param  array<mixed>  $config
53 104
     * @return string
54
     */
55 104
    public function generateEndpoint(array $config): string
56
    {
57
        if (isset($config['endpoint'])) {
58 104
            return (string) $config['endpoint'];
59 104
        }
60 2
        $endpoint = 'http://localhost:8529';
61
        if (isset($config['host'])) {
62 104
            $endpoint = (string) $config['host'];
63 2
        }
64
        if (isset($config['port'])) {
65
            $endpoint .= ':' . (string) $config['port'];
66 104
        }
67
68
        return $endpoint;
69
    }
70
71
    /**
72
     * @psalm-suppress MixedReturnStatement
73
     *
74
     * @param  string  $method
75
     * @param  string  $uri
76
     * @param  array<mixed>|HttpRequestOptions  $options
77
     * @param  string|null  $database
78
     * @return stdClass
79 104
     * @throws ArangoException
80
     */
81 104
    public function request(string $method, string $uri, $options = [], ?string $database = null): stdClass
82
    {
83 104
        $uri = $this->prependDatabaseToUri($uri, $database);
84 104
85
        if (is_array($options)) {
86
            $options = $this->prepareRequestOptions($options);
87 104
        }
88
89 104
        $response = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
90 1
        try {
91 1
            $response = $this->httpClient->request($method, $uri, $options->all());
92
        } catch (Throwable $e) {
93
            $this->handleGuzzleException($e);
94 104
        }
95
96
        return $this->cleanupResponse($response);
97
    }
98
99
    /**
100
     * @param  array<mixed>  $options
101
     * @return HttpRequestOptions
102 104
     * @throws ArangoException
103
     */
104 104
    protected function prepareRequestOptions(array $options): HttpRequestOptions
105 67
    {
106
        if (isset($options['body'])) {
107
            $options['body'] = $this->jsonEncode($options['body']);
108 104
        }
109
110
        return new HttpRequestOptions($options);
111
    }
112
113
    /**
114
     * Return the response with debug information (for internal testing purposes).
115
     *
116
     * @param  string  $method
117
     * @param  string  $uri
118
     * @param  array<mixed>  $options
119
     * @param  string|null  $database
120
     * @return ResponseInterface
121 2
     * @throws GuzzleException
122
     */
123
    public function debugRequest(
124
        string $method,
125
        string $uri,
126
        array $options = [],
127 2
        ?string $database = null
128 2
    ): ResponseInterface {
129
        $uri = $this->prependDatabaseToUri($uri, $database);
130 2
        $options['debug'] = true;
131
132
        return $this->httpClient->request($method, $uri, $options);
133 104
    }
134
135 104
    protected function prependDatabaseToUri(string $uri, ?string $database = null): string
136 104
    {
137
        if (! isset($database)) {
138 104
            $database = $this->config->database;
139
        }
140
        return '/_db/' . urlencode($database) . $uri;
141
    }
142
143
    /**
144
     * @param  Throwable  $e
145 1
     * @throws ArangoException
146
     */
147 1
    protected function handleGuzzleException(Throwable $e): void
148 1
    {
149
        $message = $e->getMessage();
150 1
        $code = $e->getCode();
151 1
152 1
        if ($e instanceof RequestException && $e->hasResponse()) {
153 1
            $decodedResponse = $this->decodeResponse($e->getResponse());
154
            $message = (string) $decodedResponse->errorMessage;
155
            $code = (int) $decodedResponse->code;
156
        }
157 1
158 1
        throw(
159 1
            new ArangoException(
160
                $code . ' - ' .  $message,
161
                (int) $code
162
            )
163
        );
164
    }
165
166
    /**
167
     * @psalm-suppress MixedAssignment, MixedArrayOffset
168
     * @SuppressWarnings(PHPMD.StaticAccess)
169
     *
170
     * @param  ResponseInterface|null  $response
171 104
     * @return stdClass
172
     */
173 104
    protected function cleanupResponse(?ResponseInterface $response): stdClass
174 104
    {
175 104
        $response =  $this->decodeResponse($response);
176
        unset($response->error);
177 104
        unset($response->code);
178
179
        return $response;
180
    }
181
182
    /**
183
     * @param  string  $query
184
     * @param  array<scalar>  $bindVars
185
     * @param  array<mixed>  $options
186
     * @return Traversable<mixed>
187 104
     */
188
    public function prepare(
189 104
        string $query,
190
        array $bindVars = [],
191
        array $options = []
192
    ): Traversable {
193 104
        return new Statement($this, $query, $bindVars, $options);
194
    }
195 104
196 104
    /**
197
     * @return array<array-key, mixed>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, mixed> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, mixed>.
Loading history...
198 104
     */
199 104
    public function getConfig(): array
200
    {
201
        return $this->config->toArray();
202 104
    }
203
204
    /**
205
     * @param string $name
206
     * @return void
207
     */
208
    public function setDatabase(string $name): void
209
    {
210 71
        $this->config->database = $name;
211
    }
212 71
213 71
    /**
214 3
     * @return string
215
     */
216
    public function getDatabase(): string
217 71
    {
218
        return $this->config->database;
219 71
    }
220 1
221
    public function setHttpClient(GuzzleClient $httpClient): void
222
    {
223 70
        $this->httpClient = $httpClient;
224
    }
225
226
    public function getHttpClient(): GuzzleClient
227
    {
228
        return $this->httpClient;
229
    }
230
231
    public function getUser(): string
232 16
    {
233
        return (string) $this->config->username;
234
    }
235
}
236