forked from tcdent/php-restclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restclient.php
executable file
·279 lines (230 loc) · 10.2 KB
/
restclient.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
<?php declare(strict_types=1);
/**
* PHP REST Client
* https://github.com/tcdent/php-restclient
* (c) 2013-2022 Travis Dent <tcdent@gmail.com>
*/
class RestClientException extends Exception {}
class RestClient implements Iterator, ArrayAccess {
public $options;
public $handle; // cURL resource handle.
// Populated after execution:
public $response; // Response body.
public $headers; // Parsed reponse header object.
public $info; // Response info object.
public $error; // Response error string.
public $response_status_lines; // indexed array of raw HTTP response status lines.
// Populated as-needed.
public $decoded_response; // Decoded response body.
public function __construct(array $options=[]){
$default_options = [
'headers' => [],
'parameters' => [],
'curl_options' => [],
'build_indexed_queries' => FALSE,
'user_agent' => "PHP RestClient/0.1.8",
'base_url' => NULL,
'format' => NULL,
'format_regex' => "/(\w+)\/(\w+)(;[.+])?/",
'decoders' => [
'json' => 'json_decode',
'php' => 'unserialize'
],
'username' => NULL,
'password' => NULL
];
$this->options = array_merge($default_options, $options);
if(array_key_exists('decoders', $options))
$this->options['decoders'] = array_merge(
$default_options['decoders'], $options['decoders']);
}
public function set_option($key, $value) : void {
$this->options[$key] = $value;
}
public function register_decoder(string $format, callable $method) : void {
// Decoder callbacks must adhere to the following pattern:
// array my_decoder(string $data)
$this->options['decoders'][$format] = $method;
}
// Iterable methods:
public function rewind() : void {
$this->decode_response();
reset($this->decoded_response);
}
public function current() : mixed {
return current($this->decoded_response);
}
public function key() : mixed {
return key($this->decoded_response);
}
public function next() : void {
next($this->decoded_response);
}
public function valid() : bool {
return is_array($this->decoded_response)
&& (key($this->decoded_response) !== NULL);
}
// ArrayAccess methods:
public function offsetExists($key) : bool {
$this->decode_response();
return is_array($this->decoded_response)?
isset($this->decoded_response[$key]) : isset($this->decoded_response->{$key});
}
public function offsetGet($key) : mixed {
$this->decode_response();
if(!$this->offsetExists($key))
return NULL;
return is_array($this->decoded_response)?
$this->decoded_response[$key] : $this->decoded_response->{$key};
}
public function offsetSet($key, $value) : void {
throw new RestClientException("Decoded response data is immutable.");
}
public function offsetUnset($key) : void {
throw new RestClientException("Decoded response data is immutable.");
}
// Request methods:
public function get(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'GET', $parameters, $headers);
}
public function post(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'POST', $parameters, $headers);
}
public function put(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'PUT', $parameters, $headers);
}
public function patch(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'PATCH', $parameters, $headers);
}
public function delete(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'DELETE', $parameters, $headers);
}
public function head(string $url, $parameters=[], array $headers=[]) : RestClient {
return $this->execute($url, 'HEAD', $parameters, $headers);
}
public function execute(string $url, string $method='GET', $parameters=[], array $headers=[]) : RestClient {
$client = clone $this;
$client->url = $url;
$client->handle = curl_init();
$curlopt = [
CURLOPT_HEADER => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_USERAGENT => $client->options['user_agent']
];
if($client->options['username'] && $client->options['password'])
$curlopt[CURLOPT_USERPWD] = sprintf("%s:%s",
$client->options['username'], $client->options['password']);
if(count($client->options['headers']) || count($headers)){
$curlopt[CURLOPT_HTTPHEADER] = [];
$headers = array_merge($client->options['headers'], $headers);
foreach($headers as $key => $values){
foreach(is_array($values)? $values : [$values] as $value){
$curlopt[CURLOPT_HTTPHEADER][] = sprintf("%s:%s", $key, $value);
}
}
}
if($client->options['format'])
$client->url .= '.'.$client->options['format'];
// Allow passing parameters as a pre-encoded string (or something that
// allows casting to a string). Parameters passed as strings will not be
// merged with parameters specified in the default options.
if(is_array($parameters)){
$parameters = array_merge($client->options['parameters'], $parameters);
$parameters_string = http_build_query($parameters);
// http_build_query automatically adds an array index to repeated
// parameters which is not desirable on most systems. This hack
// reverts "key[0]=foo&key[1]=bar" to "key[]=foo&key[]=bar"
if(!$client->options['build_indexed_queries'])
$parameters_string = preg_replace(
"/%5B[0-9]+%5D=/simU", "%5B%5D=", $parameters_string);
}
else
$parameters_string = (string) $parameters;
if(strtoupper($method) === 'POST'){
$curlopt[CURLOPT_POST] = TRUE;
$curlopt[CURLOPT_POSTFIELDS] = $parameters_string;
}
elseif(strtoupper($method) !== 'GET'){
$curlopt[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
$curlopt[CURLOPT_POSTFIELDS] = $parameters_string;
}
elseif($parameters_string){
$client->url .= strpos($client->url, '?')? '&' : '?';
$client->url .= $parameters_string;
}
if($client->options['base_url']){
if($client->url[0] !== '/' && substr($client->options['base_url'], -1) !== '/')
$client->url = '/' . $client->url;
$client->url = $client->options['base_url'] . $client->url;
}
$curlopt[CURLOPT_URL] = $client->url;
if($client->options['curl_options']){
// array_merge would reset our numeric keys.
foreach($client->options['curl_options'] as $key => $value){
$curlopt[$key] = $value;
}
}
curl_setopt_array($client->handle, $curlopt);
$response = curl_exec($client->handle);
if($response !== FALSE)
$client->parse_response($response);
$client->info = (object) curl_getinfo($client->handle);
$client->error = curl_error($client->handle);
curl_close($client->handle);
return $client;
}
public function parse_response($response) : void {
$headers = [];
$this->response_status_lines = [];
$line = strtok($response, "\n");
do {
if(strlen(trim($line)) == 0){
// Since we tokenize on \n, use the remaining \r to detect empty lines.
if(count($headers) > 0) break; // Must be the newline after headers, move on to response body
}
elseif(strpos($line, 'HTTP') === 0){
// One or more HTTP status lines
$this->response_status_lines[] = trim($line);
}
else {
// Has to be a header
[$key, $value] = explode(':', $line, 2);
$key = strtolower(trim(str_replace('-', '_', $key)));
$value = trim($value);
if(empty($headers[$key]))
$headers[$key] = $value;
elseif(is_array($headers[$key]))
$headers[$key][] = $value;
else
$headers[$key] = [$headers[$key], $value];
}
} while($line = strtok("\n"));
$this->headers = (object) $headers;
$this->response = strtok("");
}
public function get_response_format() : string {
if(!$this->response)
throw new RestClientException(
"A response must exist before it can be decoded.");
// User-defined format.
if(!empty($this->options['format']))
return $this->options['format'];
// Extract format from response content-type header.
if(!empty($this->headers->content_type))
if(preg_match($this->options['format_regex'], $this->headers->content_type, $matches))
return $matches[2];
throw new RestClientException(
"Response format could not be determined.");
}
public function decode_response(){
if(empty($this->decoded_response)){
$format = $this->get_response_format();
if(!array_key_exists($format, $this->options['decoders']))
throw new RestClientException("'${format}' is not a supported ".
"format, register a decoder to handle this response.");
$this->decoded_response = call_user_func(
$this->options['decoders'][$format], $this->response);
}
return $this->decoded_response;
}
}