-
Notifications
You must be signed in to change notification settings - Fork 1
/
RestClient_php_74_lower.php
308 lines (275 loc) · 7.74 KB
/
RestClient_php_74_lower.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
<?php
/**
* PHP 6-7.3 REST Client build with cURL
*
* @author Fabio Agostinho Boris <fabioboris@gmail.com>
* @added DataForSEO
*/
class RestClient {
public $host; // the url to the rest server
public $port;
public $scheme;
public $post_type = 'json';
public $timeout = 60;
public $connection_timeout = 10;
private $token; // Auth token
private $ba_user;
private $ba_password;
private $ba_ua;
public $last_url = '';
public $last_response = null;
public $last_http_code = null;
public function __construct($host, $token = null, $ba_user = null, $ba_password = null, $ba_user_agent = null) {
$arr_h = parse_url($host);
if (isset($arr_h['port'])) {
$this->port = (int)$arr_h['port'];
$this->host = str_replace(":" . $this->port, "", $host);
} else {
$this->port = null;
$this->host = $host;
}
if (isset($arr_h['scheme'])) {
$this->scheme = $arr_h['scheme'];
}
$this->token = $token;
$this->ba_user = $ba_user;
$this->ba_password = $ba_password;
$this->ba_ua = $ba_user_agent;
}
private function http_parse_headers($raw_headers) {
$headers = array();
$key = '';
foreach (explode("\n", $raw_headers) as $h) {
$h = explode(':', $h, 2);
if (isset($h[1])) {
if (!isset($headers[$h[0]])) {
$headers[$h[0]] = trim($h[1]);
} elseif (is_array($headers[$h[0]])) {
$headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1])));
} else {
$headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1])));
}
$key = $h[0];
} else {
if (substr($h[0], 0, 1) == "\t") {
$headers[$key] .= "\r\n\t" . trim($h[0]);
} elseif (!$key) {
$headers[0] = trim($h[0]);
}
}
}
return $headers;
}
/**
* Returns the absolute URL
*
* @param string $url
*/
private function url($url = null) {
$_host = rtrim($this->host, '/');
$_url = ltrim($url, '/');
return "{$_host}:{$this->port}/{$_url}";
}
/**
* Returns the URL with encoded query string params
*
* @param string $url
* @param array $params
*/
private function urlQueryString($url, $params = null) {
$qs = array();
if ($params) {
foreach ($params as $key => $value) {
$qs[] = "{$key}=" . urlencode($value);
}
}
$url = explode('?', $url);
if (isset($url[1])) {
$url_qs = $url[1];
}
$url = $url[0];
if (isset($url_qs)) {
$url = "{$url}?{$url_qs}";
}
if (count($qs)) {
return "{$url}?" . implode('&', $qs);
} else {
return $url;
}
}
/**
* Make an HTTP request using cURL
*
* @param string $verb
* @param string $url
* @param array $params
*/
private function request($verb, $url, $params = array()) {
$ch = curl_init(); // the cURL handler
$url = $this->url($url); // the absolute URL
$request_headers = array();
if (!empty($this->token)) {
$request_headers[] = "Authorization: {$this->token}";
}
if ((!empty($this->ba_user)) and (!empty($this->ba_password))) {
curl_setopt($ch, CURLOPT_USERPWD, $this->ba_user . ":" . $this->ba_password);
}
// encoded query string on GET
switch (true) {
case 'GET' == $verb:
$url = $this->urlQueryString($url, $params);
break;
case in_array($verb, array(
'POST',
'PUT',
'DELETE'
)):
if ($this->post_type == 'json') {
$request_headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
} else {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
}
}
// set the URL
curl_setopt($ch, CURLOPT_URL, $url);
$this->last_url = $url;
// set the HTTP verb for the request
switch ($verb) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case 'PUT':
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $verb);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connection_timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
if (!empty($this->ba_ua)) {
curl_setopt($ch, CURLOPT_USERAGENT, $this->ba_ua);
}
if (!empty($this->port)) {
curl_setopt($ch, CURLOPT_PORT, $this->port);
}
if ((!empty($this->scheme)) and ($this->scheme == 'https')) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
} else {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = $this->http_parse_headers(substr($response, 0, $header_size));
$response = substr($response, $header_size);
$http_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$content_error = curl_error($ch);
//var_dump($content_error);
curl_close($ch);
if (strpos($content_type, 'json')) {
$response = json_decode($response, true);
}
$this->last_response = $response;
$this->last_http_code = $http_code;
switch (true) {
case 'GET' == $verb:
if ($http_code !== 200) {
if (is_array($response)) {
$this->throw_error($response, $http_code);
} else {
$this->throw_error(trim($content_error . "\n" . $response), $http_code);
}
}
return $response;
case in_array($verb, array(
'POST',
'PUT',
'DELETE'
)):
if (($http_code !== 303) and ($http_code !== 200)) {
if (is_array($response)) {
$this->throw_error($response, $http_code);
} else {
$this->throw_error(trim($content_error . "\n" . $response), $http_code);
}
}
if ($http_code === 200) {
return $response;
} else {
return str_replace(rtrim($this->host, '/') . '/', '', $headers['Location']);
}
}
}
private function throw_error($response, $http_code) {
if (is_array($response) && array_key_exists('error', $response)) {
if ((isset($response['error']['message'])) and (isset($response['error']['code']))) {
if (is_array($response['error']['message'])) {
throw new RestClientException(implode("; ", $response['error']['message']), (int)$response['error']['code'], $http_code);
} else {
throw new RestClientException($response['error']['message'], (int)$response['error']['code'], $http_code);
}
} else {
throw new RestClientException(implode("; ", $response), 0, $http_code);
}
} else {
if (is_string($response)) {
throw new RestClientException($response, 0, $http_code);
} else {
throw new RestClientException(json_encode($response), 0, $http_code);
}
}
}
/**
* Make an HTTP GET request
*
* @param string $url
* @param array $params
*/
public function get($url, $params = array()) {
return $this->request('GET', $url, $params);
}
/**
* Make an HTTP POST request
*
* @param string $url
* @param array $params
*/
public function post($url, $params = array()) {
return $this->request('POST', $url, $params);
}
/**
* Make an HTTP PUT request
*
* @param string $url
* @param array $params
*/
public function put($url, $params = array()) {
return $this->request('PUT', $url, $params);
}
/**
* Make an HTTP DELETE request
*
* @param string $url
* @param array $params
*/
public function delete($url, $params = array()) {
return $this->request('DELETE', $url, $params);
}
}
class RestClientException extends Exception {
protected $http_code;
public function __construct($message, $code = 0, $http_code = 0, Exception $previous = null) {
$this->http_code = $http_code;
parent::__construct($message, $code, $previous);
}
public function getHttpCode() {
return $this->http_code;
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message} (HTTP status code: {$this->http_code})\n";
}
}