-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathShipEngineClient.php
226 lines (201 loc) · 6.37 KB
/
ShipEngineClient.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
<?php declare(strict_types=1);
namespace ShipEngine;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Client\ClientExceptionInterface;
use ShipEngine\Message\AccountStatusException;
use ShipEngine\Message\BusinessRuleException;
use ShipEngine\Message\RateLimitExceededException;
use ShipEngine\Message\SecurityException;
use ShipEngine\Message\ShipEngineException;
use ShipEngine\Message\SystemException;
use ShipEngine\Message\ValidationException;
use ShipEngine\Util\Assert;
/**
* A wrapped `REST` HTTP client to send HTTP requests from the SDK.
*
* @package ShipEngine
*/
final class ShipEngineClient
{
/**
* Implement a GET request and return output
*
* @param string $path
* @param ShipEngineConfig $config
*
* @return array
*/
public function get($path, ShipEngineConfig $config)
{
return $this->sendRequestWithRetries('GET', $path, null, $config);
}
/**
* Implement a POST request and return output
*
* @param string $path
* @param ShipEngineConfig $config
* @param array $params
*
* @return array
*/
public function post($path, ShipEngineConfig $config, array $params = null)
{
return $this->sendRequestWithRetries('POST', $path, $params, $config);
}
/**
* Implement a PUT request and return output
*
* @param string $path
* @param ShipEngineConfig $config
* @param array $params
*
* @return array
*/
public function put($path, ShipEngineConfig $config, array $params = null)
{
return $this->sendRequestWithRetries('PUT', $path, $params, $config);
}
/**
* Implement a DELETE request and return output
*
* @param string $path
* @param ShipEngineConfig $config
*
* @return array
*/
public function delete($path, ShipEngineConfig $config)
{
return $this->sendRequestWithRetries('DELETE', $path, null, $config);
}
/**
* Send a `REST` request via *ShipEngineClient*.
*
* @param string $method
* @param string $path
* @param array|null $params
* @param ShipEngineConfig $config
* @return array
* @throws GuzzleException
*/
private function sendRequestWithRetries(
string $method,
string $path,
?array $params,
ShipEngineConfig $config
): array
{
$apiResponse = null;
for ($retry = 0; $retry <= $config->retries; $retry++) {
try {
$apiResponse = $this->sendRequest($method, $path, $params, $retry, $config);
break;
} catch (\RuntimeException $err) {
if (($retry < $config->retries) &&
$err instanceof RateLimitExceededException &&
($err->retryAfter->s < $config->timeout->s)
) {
// The request was blocked due to exceeding the rate limit.
// So wait the specified amount of time and then retry.
sleep($err->retryAfter->s);
} else {
throw $err;
}
}
}
return $apiResponse;
}
/**
* Send a `REST` request via HTTP Messages to ShipEngine API. If the response
* is successful, the result is returned. Otherwise, an error is thrown.
*
* @param string $method
* @param string $path
* @param array|null $params
* @param int $retry
* @param ShipEngineConfig $config
* @return array
* @throws GuzzleException
*/
private function sendRequest(
string $method,
string $path,
?array $params,
int $retry,
ShipEngineConfig $config
): array {
$requestHeaders = array(
'api-key' => $config->apiKey,
'User-Agent' => $this->deriveUserAgent(),
'Content-Type' => 'application/json',
'Accept' => 'application/json'
);
$client = new Client(
[
'base_uri' => $config->baseUrl,
'timeout' => $config->timeout,
'max_retry_attempts' => $config->retries
]
);
$jsonData = json_encode($params, JSON_UNESCAPED_SLASHES);
$request = new Request($method, $path, $requestHeaders, $jsonData);
try {
$response = $client->send(
$request,
['timeout' => $config->timeout->s, 'http_errors' => false]
);
} catch (ClientException $err) {
throw new ShipEngineException(
"An unknown error occurred while calling the ShipEngine $method API:\n" .
$err->getMessage(),
null,
'ShipEngine',
'System',
'Unspecified'
);
}
$responseBody = (string)$response->getBody();
$parsedResponse = json_decode($responseBody, true);
$statusCode = $response->getStatusCode();
// $assert->isResponse404($statusCode, $parsedResponse);
// $assert->isResponse429($statusCode, $parsedResponse, $config);
// $assert->isResponse500($statusCode, $parsedResponse);
return $this->handleResponse($parsedResponse);
}
/**
* Handles the response from ShipEngine API.
*
* @param array $response
* @return array
*/
private function handleResponse(array $response): array
{
if (!isset($response['errors']) || (count($response['errors']) == 0)) {
return $response;
}
$error = $response['errors'][0];
throw new ShipEngineException(
$error['message'],
$response['request_id'],
$error['error_source'],
$error['error_type'],
$error['error_code']
);
}
/**
* Derive a User-Agent header from the environment. This is the user-agent that will be set on every request
* via the ShipEngine Client.
*
* @returns string
*/
private function deriveUserAgent(): string
{
$sdk_version = 'shipengine-php/' . ShipEngine::VERSION;
$os = explode(' ', php_uname());
$os_kernel = $os[0] . '/' . $os[2];
$php_version = 'PHP/' . phpversion();
return $sdk_version . ' ' . $os_kernel . ' ' . $php_version;
}
}