-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathClient.php
More file actions
386 lines (327 loc) Β· 9.15 KB
/
Client.php
File metadata and controls
386 lines (327 loc) Β· 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
<?php
namespace Appwrite;
class Client
{
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_HEAD = 'HEAD';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_CONNECT = 'CONNECT';
const METHOD_TRACE = 'TRACE';
const CHUNK_SIZE = 5 * 1024 * 1024;
/**
* Is Self Signed Certificates Allowed?
*
* @var bool
*/
protected bool $selfSigned = false;
/**
* Service host name
*
* @var string
*/
protected string $endpoint = 'https://cloud.appwrite.io/v1';
/**
* Global Headers
*
* @var array
*/
protected array $headers = [
'content-type' => '',
'user-agent' => 'AppwritePHPSDK/20.2.0 ()',
'x-sdk-name'=> 'PHP',
'x-sdk-platform'=> 'server',
'x-sdk-language'=> 'php',
'x-sdk-version'=> '20.2.0',
];
/**
* Timeout in seconds
*
* @var int|null
*/
protected ?int $timeout = null;
/**
* Connect timeout in seconds
*
* @var int|null
*/
protected ?int $connectTimeout = null;
/**
* Client constructor.
*/
public function __construct()
{
$this->headers['X-Appwrite-Response-Format'] = '1.8.0';
}
/**
* Set Project
*
* Your project ID
*
* @param string $value
*
* @return Client
*/
public function setProject(string $value): Client
{
$this->addHeader('X-Appwrite-Project', $value);
return $this;
}
/**
* Set Key
*
* Your secret API key
*
* @param string $value
*
* @return Client
*/
public function setKey(string $value): Client
{
$this->addHeader('X-Appwrite-Key', $value);
return $this;
}
/**
* Set JWT
*
* Your secret JSON Web Token
*
* @param string $value
*
* @return Client
*/
public function setJWT(string $value): Client
{
$this->addHeader('X-Appwrite-JWT', $value);
return $this;
}
/**
* Set Locale
*
* @param string $value
*
* @return Client
*/
public function setLocale(string $value): Client
{
$this->addHeader('X-Appwrite-Locale', $value);
return $this;
}
/**
* Set Session
*
* The user session to authenticate with
*
* @param string $value
*
* @return Client
*/
public function setSession(string $value): Client
{
$this->addHeader('X-Appwrite-Session', $value);
return $this;
}
/**
* Set ForwardedUserAgent
*
* The user agent string of the client that made the request
*
* @param string $value
*
* @return Client
*/
public function setForwardedUserAgent(string $value): Client
{
$this->addHeader('X-Forwarded-User-Agent', $value);
return $this;
}
/***
* @param bool $status
* @return $this
*/
public function setSelfSigned(bool $status = true): Client
{
$this->selfSigned = $status;
return $this;
}
/***
* @param $endpoint
* @return $this
*/
public function setEndpoint(string $endpoint): Client
{
if (!str_starts_with($endpoint, 'http://') && !str_starts_with($endpoint, 'https://')) {
throw new AppwriteException("Invalid endpoint URL: $endpoint");
}
$this->endpoint = $endpoint;
return $this;
}
/**
* Set Timeout
*
* @param int $timeout Timeout in seconds
* @return Client
*/
public function setTimeout(int $timeout): Client
{
$this->timeout = $timeout;
return $this;
}
/**
* Set Connect Timeout
*
* @param int $connectTimeout Connect timeout in seconds
* @return Client
*/
public function setConnectTimeout(int $connectTimeout): Client
{
$this->connectTimeout = $connectTimeout;
return $this;
}
/**
* @param $key
* @param $value
*/
public function addHeader(string $key, string $value): Client
{
$this->headers[strtolower($key)] = $value;
return $this;
}
/**
* Call
*
* Make an API call
*
* @param string $method
* @param string $path
* @param array $params
* @param array $headers
* @return array|string
* @throws AppwriteException
*/
public function call(
string $method,
string $path = '',
array $headers = [],
array $params = [],
?string $responseType = null
)
{
$headers = array_merge($this->headers, $headers);
$ch = curl_init($this->endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : ''));
$responseHeaders = [];
switch ($headers['content-type']) {
case 'application/json':
$query = json_encode($this->prepareParams($params));
break;
case 'multipart/form-data':
$query = $this->flatten($params);
break;
default:
$query = http_build_query($params);
break;
}
foreach ($headers as $i => $header) {
$headers[] = $i . ':' . $header;
unset($headers[$i]);
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, php_uname('s') . '-' . php_uname('r') . ':php-' . phpversion());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $responseType !== 'location');
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header) use (&$responseHeaders) {
$len = strlen($header);
$header = explode(':', strtolower($header), 2);
if (count($header) < 2) { // ignore invalid headers
return $len;
}
$responseHeaders[strtolower(trim($header[0]))] = trim($header[1]);
return $len;
});
if($method != self::METHOD_GET) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}
// Allow self signed certificates
if($this->selfSigned) {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// Set timeout if configured
if($this->timeout !== null) {
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
}
// Set connect timeout if configured
if($this->connectTimeout !== null) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
}
$responseBody = curl_exec($ch);
$contentType = $responseHeaders['content-type'] ?? '';
$responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$warnings = $responseHeaders['x-appwrite-warning'] ?? '';
if ($warnings) {
foreach(explode(';', $warnings) as $warning) {
\trigger_error($warning, E_USER_WARNING);
}
}
switch(substr($contentType, 0, strpos($contentType, ';'))) {
case 'application/json':
$responseBody = json_decode($responseBody, true);
break;
}
if (curl_errno($ch)) {
throw new AppwriteException(curl_error($ch), $responseStatus, $responseBody['type'] ?? '', $responseBody);
}
curl_close($ch);
if($responseStatus >= 400) {
if(is_array($responseBody)) {
throw new AppwriteException($responseBody['message'], $responseStatus, $responseBody['type'] ?? '', json_encode($responseBody));
} else {
throw new AppwriteException($responseBody, $responseStatus, '', $responseBody);
}
}
if ($responseType === 'location') {
return $responseHeaders['location'];
}
return $responseBody;
}
/**
* Flatten params array to PHP multiple format
*
* @param array $data
* @param string $prefix
* @return array
*/
protected function flatten(array $data, string $prefix = ''): array {
$output = [];
foreach($data as $key => $value) {
$finalKey = $prefix ? "{$prefix}[{$key}]" : $key;
if (is_array($value)) {
$output += $this->flatten($value, $finalKey); // @todo: handle name collision here if needed
}
else {
$output[$finalKey] = $value;
}
}
return $output;
}
/**
* Prepare params for JSON encoding by converting model objects to arrays
*
* @param mixed $data
* @return mixed
*/
protected function prepareParams($data)
{
if (is_array($data)) {
return array_map([$this, 'prepareParams'], $data);
}
if (is_object($data) && method_exists($data, 'toArray')) {
return $data->toArray();
}
return $data;
}
}