-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAPIWrapper.php
More file actions
279 lines (238 loc) · 9.8 KB
/
APIWrapper.php
File metadata and controls
279 lines (238 loc) · 9.8 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
<?php
// Copyright (c) 2021 Harry [Majored] [hello@majored.pw]
// MIT License (https://github.com/Majored/php-bbb-api-wrapper/blob/main/LICENSE)
namespace Majored\PhpBbbApiWrapper;
use CurlHandle;
use Majored\PhpBbbApiWrapper\Helpers\AlertsHelper;
use Majored\PhpBbbApiWrapper\Helpers\ConversationsHelper;
use Majored\PhpBbbApiWrapper\Helpers\MembersHelper;
use Majored\PhpBbbApiWrapper\Helpers\Resources\ResourcesHelper;
use Majored\PhpBbbApiWrapper\Helpers\ThreadsHelper;
/** The primary class for interactions with BuiltByBit's API. */
class APIWrapper {
/** @var string The base URL of BuiltByBit's API that we prepend to endpoints. */
const BASE_URL = "https://api.builtbybit.com/v1";
/** @var string The complete header line for request bodies (JSON). */
const CONTENT_TYPE_HEADER = "Content-Type: application/json";
/** @var string The the number of entities returned per page for paginated endpoints. */
const PER_PAGE = 20;
/** @var CurlHandle The current CURL instance being used within this wrapper. */
private $http;
/** @var Throttler The current throttler instance being used within this wrapper. */
private $throttler;
/** @var APIToken The pre-constructed API token passed to this wrapper during initilisation. */
private $token;
/**
* Initialises this wrapper with a provided API token, and runs a health check if requested.
*
* @param APIToken The pre-constructed API token.
* @param bool Whether or not to run a health check.
* @return APIResponse The parsed response of the request to `health`.
*/
function initialise(APIToken $token, bool $health = true): APIResponse {
$this->token = $token;
$this->http = curl_init();
$this->throttler = new Throttler();
curl_setopt($this->http, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->http, CURLOPT_HEADER, 1);
if ($health) {
return $this->health();
} else {
return ["result" => "success"];
}
}
/**
* Schedules a GET request to a specific endpoint and stalls if we've previously hit a rate limit.
*
* @param string The path of the endpoint.
* @param array An optional associated array of sort options.
* @return APIResponse The parsed response.
*/
function get(string $endpoint, array $sort = []): APIResponse {
$this->stallUntilCanMakeRequest(RequestType::READ);
$url = sprintf("%s/%s?%s", APIWrapper::BASE_URL, $endpoint, http_build_query($sort));
curl_setopt($this->http, CURLOPT_HTTPGET, true);
curl_setopt($this->http, CURLOPT_URL, $url);
curl_setopt($this->http, CURLOPT_HTTPHEADER, array($this->token->asHeader()));
if ($body = $this->handleResponse(RequestType::READ)) {
return APIResponse::from_json($body);
} else {
return $this->get($endpoint, $sort);
}
}
/**
* Schedules a PATCH request to a specific endpoint and stalls if we've previously hit a rate limit.
*
* @param string The path of the endpoint.
* @param mixed The body of the request which will be serialised into JSON.
* @return APIResponse The parsed response.
*/
function patch(string $endpoint, mixed $body): APIResponse {
$this->stallUntilCanMakeRequest(RequestType::WRITE);
curl_setopt($this->http, CURLOPT_HTTPGET, true);
curl_setopt($this->http, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($this->http, CURLOPT_URL, sprintf("%s/%s", APIWrapper::BASE_URL, $endpoint));
curl_setopt($this->http, CURLOPT_HTTPHEADER, [$this->token->asHeader(), APIWrapper::CONTENT_TYPE_HEADER]);
curl_setopt($this->http, CURLOPT_POSTFIELDS, json_encode($body));
if ($body = $this->handleResponse(RequestType::WRITE)) {
return APIResponse::from_json($body);
} else {
return $this->patch($endpoint, $body);
}
}
/**
* Schedules a POST request to a specific endpoint and stalls if we've previously hit a rate limit.
*
* @param string The path of the endpoint.
* @param mixed The body of the request which will be serialised into JSON.
* @return APIResponse The parsed response.
*/
function post(string $endpoint, mixed $body): APIResponse {
$this->stallUntilCanMakeRequest(RequestType::WRITE);
curl_setopt($this->http, CURLOPT_HTTPGET, true);
curl_setopt($this->http, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($this->http, CURLOPT_URL, sprintf("%s/%s", APIWrapper::BASE_URL, $endpoint));
curl_setopt($this->http, CURLOPT_HTTPHEADER, [$this->token->asHeader(), APIWrapper::CONTENT_TYPE_HEADER]);
curl_setopt($this->http, CURLOPT_POSTFIELDS, json_encode($body));
if ($body = $this->handleResponse(RequestType::WRITE)) {
return APIResponse::from_json($body);
} else {
return $this->post($endpoint, $body);
}
}
/**
* Schedules a DELETE request to a specific endpoint and stalls if we've previously hit a rate limit.
*
* @param string The path of the endpoint.
* @return APIResponse The parsed response.
*/
function delete(string $endpoint): APIResponse {
$this->stallUntilCanMakeRequest(RequestType::WRITE);
curl_setopt($this->http, CURLOPT_HTTPGET, true);
curl_setopt($this->http, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($this->http, CURLOPT_URL, sprintf("%s/%s", APIWrapper::BASE_URL, $endpoint));
curl_setopt($this->http, CURLOPT_HTTPHEADER, array($this->token->asHeader()));
if ($body = $this->handleResponse(RequestType::WRITE)) {
return APIResponse::from_json($body);
} else {
return $this->delete($endpoint);
}
}
/**
* Handles a CURL response and sets/resets local rate limiting metadata.
*
* @param int The type of request which the response originated from (RequestType).
* @return string|null The raw JSON response or null if a rate limit was hit.
*/
private function handleResponse(int $type): ?string {
list($header, $body) = explode("\r\n\r\n", curl_exec($this->http), 2);
$status = curl_getinfo($this->http, CURLINFO_HTTP_CODE);
$header = APIWrapper::parseHeaders(explode("\r\n", $header));
if ($status === 429 && $type === RequestType::READ) {
$this->throttler->setRead(intval($header["Retry-After"]));
return null;
} else if ($status === 429 && $type === RequestType::WRITE) {
$this->throttler->setWrite(intval($header["Retry-After"]));
return null;
}
if ($type = RequestType::READ) {
$this->throttler->resetRead();
} else if ($type = RequestType::WRITE) {
$this->throttler->resetWrite();
}
return $body;
}
/**
* Converts raw header lines into an associated array of key/value pairs.
*
* @param array An array of raw header lines.
* @return string An associated array of header key/value pairs.
*/
private static function parseHeaders(array $headers): array {
$new = [];
foreach ($headers as $header) {
$split = explode(":", $header, 2);
if (count($split) === 2) {
$new[$split[0]] = $split[1];
}
}
return $new;
}
/**
* Sleep until we no longer need to stall a request.
*
* @param int The type of request which the response originated from (RequestType).
*/
private function stallUntilCanMakeRequest(int $type) {
while ($stall_for = $this->throttler->stallFor($type)) {
usleep($stall_for * 1000);
}
}
/**
* Schedule an empty request which we expect to always succeed under nominal conditions.
*
* @return APIResponse The parsed response.
*/
function health(): APIResponse {
return $this->get("health");
}
/**
* Schedule an empty request and measure how long the API took to respond.
*
* This duration may not be representative of the raw request latency due to the fact that requests may be stalled
* locally within this wrapper to ensure compliance with rate limiting rules. Whilst this is a trade-off, it can
* be argued that the returned duration will be more representative of the true latencies experienced.
*
* @return APIResponse The parsed response with the data field overriden by the response time in milliseconds.
*/
function ping(): APIResponse {
$start = microtime(true);
$res = $this->health();
$end = microtime(true);
if ($res->getData()) {
return new APIResponse("success", ($end - $start) * 1000, null);
} else {
return $res;
}
}
/**
* Construct and return an alerts helper instance.
*
* @return AlertsHelper The constructed alerts helper.
*/
function alerts(): AlertsHelper {
return new AlertsHelper($this);
}
/**
* Construct and return a conversations helper instance.
*
* @return ConversationsHelper The constructed conversations helper.
*/
function conversations(): ConversationsHelper {
return new ConversationsHelper($this);
}
/**
* Construct and return a members helper instance.
*
* @return MembersHelper The constructed members helper.
*/
function members(): MembersHelper {
return new MembersHelper($this);
}
/**
* Construct and return a threads helper instance.
*
* @return ThreadsHelper The constructed threads helper.
*/
function threads(): ThreadsHelper {
return new ThreadsHelper($this);
}
/**
* Construct and return a resources helper instance.
*
* @return ResourcesHelper The constructed resources helper.
*/
function resources(): ResourcesHelper {
return new ResourcesHelper($this);
}
}