-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathHttp.php
More file actions
319 lines (278 loc) · 10.1 KB
/
Http.php
File metadata and controls
319 lines (278 loc) · 10.1 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
<?php
declare(strict_types=1);
namespace Shopify\Clients;
use Psr\Http\Client\ClientExceptionInterface;
use Shopify\Exception\UninitializedContextException;
use Exception;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\Utils;
use Shopify\Context;
class Http
{
public const METHOD_GET = 'GET';
public const METHOD_POST = 'POST';
public const METHOD_PUT = 'PUT';
public const METHOD_DELETE = 'DELETE';
public const DATA_TYPE_JSON = 'application/json';
private const RETRIABLE_STATUS_CODES = [429, 500];
private const DEPRECATION_ALERT_SECONDS = 3600;
private readonly string $domain;
private int $lastApiDeprecationWarning = 0;
public function __construct(string $domain)
{
$this->domain = $domain;
}
/**
* Makes a GET request to this client's domain.
*
* @param string $path The URL path to request
* @param array $headers Any extra headers to send along with the request
* @param array $query Parameters on a query to be added to the URL
* @param int|null $tries How many times to attempt the request
*
* @return HttpResponse
* @throws ClientExceptionInterface
* @throws UninitializedContextException
*/
public function get(string $path, array $headers = [], array $query = [], ?int $tries = null): HttpResponse
{
return $this->request(
path: $path,
method: self::METHOD_GET,
headers: $headers,
query: $query,
tries: $tries,
);
}
/**
* Makes a POST request to this client's domain.
*
* @param string $path The URL path to request
* @param string|array $body The body of the request
* @param array $headers Any extra headers to send along with the request
* @param array $query Parameters on a query to be added to the URL
* @param int|null $tries How many times to attempt the request
* @param string $dataType The data type to expect in the response
*
* @return HttpResponse
* @throws ClientExceptionInterface
* @throws UninitializedContextException
*/
public function post(
string $path,
$body,
array $headers = [],
array $query = [],
?int $tries = null,
string $dataType = self::DATA_TYPE_JSON
): HttpResponse {
return $this->request(
path: $path,
method: self::METHOD_POST,
body: $body,
headers: $headers,
query: $query,
tries: $tries,
dataType: $dataType,
);
}
/**
* Makes a PUT request to this client's domain.
*
* @param string $path The URL path to request
* @param string|array $body The body of the request
* @param array $headers Any extra headers to send along with the request
* @param array $query Parameters on a query to be added to the URL
* @param int|null $tries How many times to attempt the request
* @param string $dataType The data type to expect in the response
*
* @return HttpResponse
* @throws ClientExceptionInterface
* @throws UninitializedContextException
*/
public function put(
string $path,
$body,
array $headers = [],
array $query = [],
?int $tries = null,
string $dataType = self::DATA_TYPE_JSON
): HttpResponse {
return $this->request(
path: $path,
method: self::METHOD_PUT,
body: $body,
headers: $headers,
query: $query,
tries: $tries,
dataType: $dataType,
);
}
/**
* Makes a DELETE request to this client's domain.
*
* @param string $path The URL path to request
* @param array $headers Any extra headers to send along with the request
* @param array $query Parameters on a query to be added to the URL
* @param int|null $tries How many times to attempt the request
*
* @return HttpResponse
* @throws ClientExceptionInterface
* @throws UninitializedContextException
*/
public function delete(string $path, array $headers = [], array $query = [], ?int $tries = null): HttpResponse
{
return $this->request(
path: $path,
method: self::METHOD_DELETE,
headers: $headers,
query: $query,
tries: $tries,
);
}
/**
* Internally handles the logic for making requests.
*
* @param string $path The path to query
* @param string $method The method to use
* @param string|array|null $body The request body to send
* @param array $headers Any extra headers to send along with the request
* @param array $query Parameters on a query to be added to the URL
* @param int|null $tries How many times to attempt the request
* @param string $dataType The data type of the request
*
* @return HttpResponse
* @throws ClientExceptionInterface
* @throws UninitializedContextException
*/
protected function request(
string $path,
string $method,
$body = null,
array $headers = [],
array $query = [],
?int $tries = null,
string $dataType = self::DATA_TYPE_JSON
) {
$maxTries = $tries ?? 1;
$version = require dirname(__FILE__) . '/../version.php';
$userAgentParts = ["Shopify Admin API Library for PHP v$version"];
if (Context::$USER_AGENT_PREFIX) {
array_unshift($userAgentParts, Context::$USER_AGENT_PREFIX);
}
if (isset($headers[HttpHeaders::USER_AGENT])) {
array_unshift($userAgentParts, $headers[HttpHeaders::USER_AGENT]);
unset($headers[HttpHeaders::USER_AGENT]);
}
$client = Context::$HTTP_CLIENT_FACTORY->client();
$query = preg_replace("/%5B[0-9]+%5D/", "%5B%5D", http_build_query($query));
$url = (new Uri())
->withScheme('https')
->withHost($this->domain)
->withPath($this->getRequestPath($path))
->withQuery($query);
$request = new Request($method, $url, $headers);
$request = $request->withHeader(HttpHeaders::USER_AGENT, implode(' | ', $userAgentParts));
if ($body) {
if (is_string($body)) {
$bodyString = $body;
} else {
$bodyString = json_encode($body);
}
$stream = Utils::streamFor($bodyString);
$request = $request
->withBody($stream)
->withHeader(HttpHeaders::CONTENT_TYPE, $dataType)
->withHeader(HttpHeaders::CONTENT_LENGTH, mb_strlen($bodyString));
}
$currentTries = 0;
do {
$currentTries++;
if ($currentTries > 1) {
usleep((int)($retryAfter * 1000000));
}
$response = HttpResponse::fromResponse($client->sendRequest($request));
if (in_array($response->getStatusCode(), self::RETRIABLE_STATUS_CODES)) {
$retryAfter = $response->hasHeader(HttpHeaders::RETRY_AFTER)
? $response->getHeaderLine(HttpHeaders::RETRY_AFTER)
: Context::$RETRY_TIME_IN_SECONDS;
} else {
break;
}
} while ($currentTries < $maxTries);
if ($response->hasHeader(HttpHeaders::X_SHOPIFY_API_DEPRECATED_REASON)) {
$this->logApiDeprecation(
$url->__toString(),
$response->getHeaderLine(HttpHeaders::X_SHOPIFY_API_DEPRECATED_REASON)
);
}
return $response;
}
protected function getRequestPath(string $path): string
{
if (strpos($path, '/') !== 0) {
$path = "/$path";
}
return $path;
}
/**
* Logs an API deprecation for the given URL to the app's logged, if one was given.
*
* @param string $url The URL that used a deprecated resource
* @param string $reason The deprecation reason
* @throws UninitializedContextException
*/
private function logApiDeprecation(string $url, string $reason): void
{
if (!$this->shouldLogApiDeprecation()) {
return;
}
$e = new Exception();
$stackTrace = str_replace("\n", "\n ", $e->getTraceAsString());
Context::logWarning('API Deprecation notice', [
'url' => $url,
'reason' => $reason,
'stack trace' => $stackTrace
]);
}
/**
* Determines whether to log an API deprecation based on last logged time
*
* @return bool
*/
private function shouldLogApiDeprecation(): bool
{
if (function_exists('apcu_enabled') && apcu_enabled()) {
$apcuKey = 'shopify/shopify-api/last-api-deprecation-warning';
} else {
$apcuKey = null;
}
if ($this->lastApiDeprecationWarning === 0 && $apcuKey) {
$this->lastApiDeprecationWarning = (int) apcu_fetch($apcuKey);
}
$secondsSinceLastAlert = time() - $this->lastApiDeprecationWarning;
if ($secondsSinceLastAlert < self::DEPRECATION_ALERT_SECONDS) {
return false;
}
$this->lastApiDeprecationWarning = time();
if ($apcuKey) {
apcu_store($apcuKey, $this->lastApiDeprecationWarning, self::DEPRECATION_ALERT_SECONDS);
}
return true;
}
/**
* Fetches the path to the file holding the timestamp of the last API deprecation warning we logged.
*
* @codeCoverageIgnore This is mocked in tests so we don't use real files
* @deprecated 5.4.1 This method is no longer used internally.
*/
public function getApiDeprecationTimestampFilePath(): string
{
$filename = '.last_api_deprecation_warning';
return join(DIRECTORY_SEPARATOR, [
rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR),
ltrim($filename, DIRECTORY_SEPARATOR),
]);
}
}