-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClient.php
More file actions
91 lines (79 loc) · 2.86 KB
/
Client.php
File metadata and controls
91 lines (79 loc) · 2.86 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
<?php
namespace Tests\E2E;
use Utopia\Fetch\Client as FetchClient;
use OpenRuntimes\Executor\BodyMultipart;
class Client extends FetchClient
{
/**
* @param array<string, string> $baseHeaders
*/
public function __construct(
private readonly string $endpoint,
private array $baseHeaders = []
) {
}
public function setKey(string $key): void
{
$this->baseHeaders['Authorization'] = 'Bearer ' . $key;
}
/**
* Wrapper method for client calls to make requests to the executor
*
* @param array<string, string> $headers
* @param array<string, mixed> $params
* @return array<string, mixed>
*/
public function call(string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true, ?callable $callback = null): array
{
$url = $this->endpoint . $path;
$client = new FetchClient();
$client->setTimeout(60000);
foreach ($this->baseHeaders as $key => $value) {
$client->addHeader($key, $value);
}
foreach ($headers as $key => $value) {
$client->addHeader($key, $value);
}
$response = $client->fetch(
url: $url,
method: $method,
body: $method !== FetchClient::METHOD_GET ? $params : [],
query: $method === FetchClient::METHOD_GET ? $params : [],
chunks: $callback ? function ($chunk) use ($callback): void {
$callback($chunk->getData());
} : null
);
$body = null;
if ($callback === null) {
if ($decode) {
$contentType = $response->getHeaders()['content-type'] ?? '';
$strpos = strpos($contentType, ';');
$strpos = is_bool($strpos) ? strlen($contentType) : $strpos;
$contentType = substr($contentType, 0, $strpos);
switch ($contentType) {
case 'multipart/form-data':
$boundary = explode('boundary=', $response->getHeaders()['content-type'] ?? '')[1] ?? '';
$multipartResponse = new BodyMultipart($boundary);
$multipartResponse->load($response->text());
$body = $multipartResponse->getParts();
break;
case 'application/json':
$body = $response->json();
break;
default:
$body = $response->text();
break;
}
} else {
$body = $response->text();
}
}
return [
'headers' => array_merge(
$response->getHeaders(),
['status-code' => $response->getStatusCode()]
),
'body' => $body
];
}
}