-
Notifications
You must be signed in to change notification settings - Fork 0
/
HTTPRequester.php
357 lines (311 loc) · 8.55 KB
/
HTTPRequester.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
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
<?php
namespace HTTPRequester;
class HTTPRequester {
// ----- HTTP Method Constants -----
const GET = "GET";
const POST = "POST";
const PATCH = "PATCH";
const DELETE = "DELETE";
const PUT = "PUT";
const HEAD = "HEAD";
// ----- Instance Variables -----
public $response;
public $responsHeaders;
protected $url;
protected $parameters;
protected $outHeaders;
protected $payload;
private $curl;
private $requested = false;
private $frozen = false;
public static function init(string $url) {
return new HTTPRequester($url);
}
public function __construct(string $url) {
$this->url = $url;
$this->parameters = $this->outHeaders = $this->payload = $this->responsHeaders = [];
$this->curl = curl_init($url);
$this->setOption(CURLOPT_RETURNTRANSFER, true);
$this->setOption(CURLOPT_HEADERFUNCTION, function($curl, $header) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) {
// ignore invalid headers
return $len;
}
$this->responsHeaders[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
});
}
public function __destruct() {
curl_close($this->curl);
}
// ----------------------------------------
// Setter
// ----------------------------------------
/**
* set request query parameters
* a `?` will be append to the end of the URL
*
* @param array $parameters query parameter(s) `['key' => value]`
*/
public function withQuery(array $parameters) {
return $this->setOption(CURLOPT_URL, $this->url."?".http_build_query($parameters));
}
/**
* set request header
*
* @param array $header
*/
public function setHeaders(array $header){
$this->outHeaders = $header;
$this->setOption(CURLOPT_HTTPHEADER, $header);
return $this;
}
/**
* set request payload/body
* JSON-encoded `application/json`
*
* @param array $payload
*/
public function withJson(array $payload) {
$this->payload = $payload;
$this->setOption(CURLOPT_POSTFIELDS, json_encode($payload));
return $this;
}
/**
* set request payload/body
* URL-encoded `application/x-www-form-urlencoded`
*
* @param array $payload
*/
public function withForm(array $payload) {
$this->payload = $payload;
$this->setOption(CURLOPT_POSTFIELDS, http_build_query($payload));
return $this;
}
/**
* set request payload/body with no encoding
*/
public function withRawPayload($payload) {
$this->payload = $payload;
$this->setOption(CURLOPT_POSTFIELDS, $payload);
return $this;
}
/**
* set CurlHandle option
* see: https://www.php.net/manual/en/function.curl-setopt.php
*
* @param array $options curl option
* @throws \RuntimeException indicate failure of setting the option
*/
public function setOption(int $option, $value) {
if (curl_setopt($this->curl, $option, $value) === false){
throw new \RuntimeException('failed to set option');
}
return $this;
}
/**
* set multiple CurlHandle options at once
* see: https://www.php.net/manual/en/function.curl-setopt.php
*
* @param array $options curl options
* @throws \RuntimeException indicate failure of setting options
*/
public function setOptions(array $options) {
if (curl_setopt_array($this->curl, $options) === false){
throw new \RuntimeException('failed to set option');
}
return $this;
}
/**
* freeze the instance after making the first request
* (cannot make further request)
*/
public function frozen() {
$this->frozen = true;
return $this;
}
// ----------------------------------------
// Request
// ----------------------------------------
public function request(string $method) {
if ($this->requested && $this->frozen) {
throw new \BadMethodCallException("frozen,
cannot use current instance to make request again.");
}
else if (!isset($this->curl)){
throw new \BadMethodCallException("please call HTTPRequester::init() first");
}
else if (!isset($this->curl)){
throw new \BadMethodCallException("request URL is not set");
}
curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $method);
$this->response = curl_exec($this->curl);
$this->requested = true;
return $this;
}
/**
* make a HTTP GET requset
*/
public function get() {
return $this->request(self::GET);
}
/**
* make a HTTP POST requset
*/
public function post() {
return $this->request(self::POST);
}
/**
* make a HTTP PUT requset
*/
public function put() {
return $this->request(self::PUT);
}
/**
* make a HTTP DELETE requset
*/
public function delete() {
return $this->request(self::DELETE);
}
/**
* make a HTTP HEAD requset
*/
public function head() {
return $this->request(self::HEAD);
}
// ----------------------------------------
// Getter
// ----------------------------------------
/**
* get the reponse body of last request
*
* @return string|null
*/
public function response() {
return $this->response ?? null;
}
/**
* decodes the json response
*
* @param bool|null $associative When `true` , JSON objects will be returned as associative `array`s; when `false` , JSON objects will be returned as `object`s. When `null` , JSON objects will be returned as associative `array`s or `object`s depending on whether `JSON_OBJECT_AS_ARRAY` is set in the `flags`.
* @param int|null $depth Maximum nesting depth of the structure being decoded. The value must be greater than `0`, and less than or equal to `2147483647`.
* @param int|null $flags Bitmask of `JSON_BIGINT_AS_STRING` , `JSON_INVALID_UTF8_IGNORE` , `JSON_INVALID_UTF8_SUBSTITUTE` , `JSON_OBJECT_AS_ARRAY` , `JSON_THROW_ON_ERROR` . The behaviour of these constants is described on the JSON constants page.
* @return mixed Returns the value encoded in `json` in appropriate PHP type. Values `true`, `false` and `null` are returned as `true` , `false` and `null` respectively. `null` is returned if the `json` cannot be decoded or if the encoded data is deeper than the nesting limit.
*/
public function jsonResponse($associative = null, $depth = 512, $flags = 0) {
return json_decode($this->response() ?? [], $associative, $depth, $flags);
}
/**
* decodes the form response
*/
public function formResponse() {
$arr = [];
parse_str($this->response() ?? "", $arr);
return $arr;
}
/**
* get the infomations of the requests
*
* see: https://www.php.net/manual/en/function.curl-getinfo.php
*
* @param mixed $info `curl_getinfo` supported option
* @return mixed if no `$info` is supplied, return an array containing all info
*/
public function requestInfo($info = null) {
if ($info === null) {
return curl_getinfo($this->curl);
}
return curl_getinfo($this->curl, $info);
}
/**
* get HTTP response status code code
*
* @return int
*/
public function statusCode() {
return $this->requestInfo(CURLINFO_HTTP_CODE);
}
/**
* @return bool `true` if the status code is not 2xx
*/
public function failed() {
return !$this->success();
}
/**
* @return bool `true` if the status code is 2xx
*/
public function success() {
return 200 <= $this->statusCode() && $this->statusCode() < 300;
}
/**
* @return bool `true` if the status code is 4xx
*/
public function clientError() {
return 400 <= $this->statusCode() && $this->statusCode() < 500;
}
/**
* @return bool `true` if the status code is 5xx
*/
public function serverError() {
return 500 <= $this->statusCode() && $this->statusCode() < 600;
}
/**
* get the response headers
*
* @return array<string>
*/
public function header() {
return $this->responsHeaders;
}
/**
* get effective URL
*
* @return string
*/
public function url() {
return $this->requestInfo(CURLINFO_EFFECTIVE_URL);
}
/**
* get IP address of the most recent connection
*
* @return string
*/
public function remoteIp() {
return $this->requestInfo(CURLINFO_PRIMARY_IP);
}
/**
* get destination port of the most recent connection
*
* @return string
*/
public function remotePort() {
return $this->requestInfo(CURLINFO_PRIMARY_PORT);
}
/**
* `Content-Type` of the requested document. `NULL` indicates server did not send valid `Content-Type:` header
*/
public function contentType() {
return $this->requestInfo(CURLINFO_CONTENT_TYPE);
}
public function dump() {
return [
'outgoing' => [
'url' => [
'original' => $this->url,
'last' => $this->url()
],
'query' => $this->parameters,
'header' => $this->outHeaders,
'payload' => $this->payload
],
'incoming' => [
'response' => $this->response ?? null,
'header' => $this->responsHeaders ?? null,
'requestInfo' => $this->requestInfo(),
]
];
}
}
?>