-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTarget.php
More file actions
269 lines (227 loc) · 7.27 KB
/
Target.php
File metadata and controls
269 lines (227 loc) · 7.27 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
<?php
namespace Utopia\Migration;
abstract class Target
{
/**
* Global Headers
*
* @var array<string, string>
*/
protected array $headers = [
'Content-Type' => '',
];
public Cache $cache;
/**
* Errors
*
* @var array<Exception>
*/
public array $errors = [];
/**
* Warnings
*
* @var array<Warning>
*/
public array $warnings = [];
protected string $endpoint = '';
protected string $rootResourceId = '';
protected string $rootResourceChildId = '';
protected string $rootResourceType = '';
abstract public static function getName(): string;
abstract public static function getSupportedResources(): array;
public function registerCache(Cache &$cache): void
{
$this->cache = &$cache;
}
/**
* Run Transfer
*
* @param array<string> $resources Resources to transfer
* @param callable $callback Callback to run after transfer
* @param string $rootResourceId Root resource ID. If set, only this root resource is transferred.
* @param string $rootResourceChildId Optional child filter under the root resource. For database roots, this is the collection/table ID.
*/
abstract public function run(array $resources, callable $callback, string $rootResourceId = '', string $rootResourceChildId = ''): void;
/**
* Report Resources
*
* This function performs a count of all resources that are available for transfer.
* It also serves a secondary purpose of checking if the API is available for the given adapter.
*
* On Destinations, this function should just return nothing but still check if the API is available.
* If any issues are found then an exception should be thrown with an error message.
*
* @param array<string> $resources Resources to report
* @param array<string, array<string>> $resourceIds Map of resource type to IDs. Only top-level resources supported.
* @return array<string, int>
*
* @throws \Exception if resourceIds contains non-top-level resource types
*/
abstract public function report(array $resources = [], array $resourceIds = []): array;
/**
* Make an API call
*
* @param array<string, string> $headers
* @param array<string, mixed> $params
* @param array<string, string> $responseHeaders
* @return array<mixed>|string
*
* @throws \Exception
*/
protected function call(
string $method,
string $path = '',
array $headers = [],
array $params = [],
array &$responseHeaders = []
): array|string {
$headers = \array_merge($this->headers, $headers);
$ch = \curl_init((
\str_contains($path, 'http')
? $path.(($method == 'GET' && ! empty($params)) ? '?'.\http_build_query($params) : '')
: $this->endpoint.$path.(
($method == 'GET' && ! empty($params))
? '?'.\http_build_query($params)
: ''
)
));
$query = match ($headers['Content-Type']) {
'application/json' => \json_encode($params),
'multipart/form-data' => $this->flatten($params),
default => \http_build_query($params),
};
foreach ($headers as $i => $header) {
$headers[] = $i.':'.$header;
unset($headers[$i]);
}
if ($method === 'HEAD') {
\curl_setopt($ch, CURLOPT_NOBODY, true);
} else {
\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, true);
\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 != 'GET') {
\curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
}
$responseBody = curl_exec($ch);
$responseType = $responseHeaders['Content-Type'] ?? $responseHeaders['content-type'] ?? '';
$responseStatus = \curl_getinfo($ch, CURLINFO_HTTP_CODE);
switch (\substr($responseType, 0, \strpos($responseType, ';'))) {
case 'application/json':
$responseBody = \json_decode($responseBody, true);
break;
}
if (\curl_errno($ch)) {
throw new \Exception(\curl_error($ch), Exception::CODE_INTERNAL);
}
if ($responseStatus >= 400) {
if (\is_array($responseBody)) {
throw new \Exception(\json_encode($responseBody), $responseStatus);
} else {
throw new \Exception($responseStatus.': '.$responseBody, $responseStatus);
}
}
return $responseBody;
}
/**
* Flatten params array to PHP multiple format
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
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);
} else {
$output[$finalKey] = $value;
}
}
return $output;
}
/**
* Validate that resourceIds only contains top-level resources
*/
protected function validateResourceIds(array $resourceIds): void
{
foreach (array_keys($resourceIds) as $resourceType) {
if (!in_array($resourceType, Transfer::ROOT_RESOURCES)) {
throw new \Exception(
'Invalid resource type in resourceIds: ' . $resourceType . '. ' .
'Only top-level resources are supported: ' . implode(', ', Transfer::ROOT_RESOURCES)
);
}
}
}
/**
* Get Errors
*
* @returns array<Exception>
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* Add Error
*/
public function addError(Exception $error): void
{
$this->errors[] = $error;
}
/**
* Get Warnings
*
* @returns array<Warning>
*/
public function getWarnings(): array
{
return $this->warnings;
}
/**
* Add Warning
*/
public function addWarning(Warning $warning): void
{
$this->warnings[] = $warning;
}
/**
* Completion callback
*/
public function shutdown(): void
{
}
/**
* Success callback
*/
public function success(): void
{
}
/**
* Error callback
*/
public function error(): void
{
}
/**
* Clean up callback
*/
public function cleanUp(): void
{
}
}