-
Notifications
You must be signed in to change notification settings - Fork 172
/
Http.php
270 lines (235 loc) · 9.1 KB
/
Http.php
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
<?php
declare(strict_types=1);
namespace Shopify\Clients;
use Exception;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\Utils;
use Psr\Log\LogLevel;
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';
public const DATA_TYPE_GRAPHQL = 'application/graphql';
private const RETRIABLE_STATUS_CODES = [429, 500];
private const DEPRECATION_ALERT_SECONDS = 60;
/** @var string */
private $domain;
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 \Psr\Http\Client\ClientExceptionInterface
* @throws \Shopify\Exception\UninitializedContextException
*/
public function get(string $path, array $headers = [], array $query = [], ?int $tries = null): HttpResponse
{
return $this->request($path, self::METHOD_GET, null, $headers, $query, $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 \Psr\Http\Client\ClientExceptionInterface
* @throws \Shopify\Exception\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, self::METHOD_POST, $body, $headers, $query, $tries, $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 \Psr\Http\Client\ClientExceptionInterface
* @throws \Shopify\Exception\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, self::METHOD_PUT, $body, $headers, $query, $tries, $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 \Psr\Http\Client\ClientExceptionInterface
* @throws \Shopify\Exception\UninitializedContextException
*/
public function delete(string $path, array $headers = [], array $query = [], ?int $tries = null): HttpResponse
{
return $this->request(
$path,
self::METHOD_DELETE,
null,
$headers,
$query,
$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 \Psr\Http\Client\ClientExceptionInterface
* @throws \Shopify\Exception\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();
if (strpos($path, '/') !== 0) {
$path = "/$path";
}
$url = (new Uri())
->withScheme('https')
->withHost($this->domain)
->withPath($path)
->withQuery(http_build_query($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++;
$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;
usleep($retryAfter * 1000000);
} 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;
}
/**
* 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 \Shopify\Exception\UninitializedContextException
*/
private function logApiDeprecation(string $url, string $reason): void
{
$warningFilePath = $this->getApiDeprecationTimestampFilePath();
$lastWarning = null;
if (file_exists($warningFilePath)) {
$lastWarning = (int)(file_get_contents($warningFilePath));
}
if (time() - $lastWarning < self::DEPRECATION_ALERT_SECONDS) {
return;
}
file_put_contents($warningFilePath, time());
$e = new Exception();
$stackTrace = str_replace("\n", "\n ", $e->getTraceAsString());
// For some reason, code coverage doesn't like the heredoc string, but there's no branching here so if the lines
// above are hit, so is this.
// @codeCoverageIgnoreStart
Context::log(
<<<NOTICE
API Deprecation notice:
URL: $url
Reason: $reason
Stack trace:
$stackTrace
NOTICE,
LogLevel::WARNING,
);
// @codeCoverageIgnoreEnd
}
/**
* 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
*/
public function getApiDeprecationTimestampFilePath(): string
{
return dirname(__DIR__) . '/.last_api_deprecation_warning';
}
}