1 | <?php |
||
24 | class HttpClient |
||
25 | { |
||
26 | |||
27 | /** |
||
28 | * cURL handle. |
||
29 | * |
||
30 | * @var resource |
||
31 | */ |
||
32 | protected $ch; |
||
33 | |||
34 | /** |
||
35 | * Store API URL. |
||
36 | * |
||
37 | * @var string |
||
38 | */ |
||
39 | protected $url; |
||
40 | |||
41 | /** |
||
42 | * Consumer key. |
||
43 | * |
||
44 | * @var string |
||
45 | */ |
||
46 | protected $consumerKey; |
||
47 | |||
48 | /** |
||
49 | * Consumer secret. |
||
50 | * |
||
51 | * @var string |
||
52 | */ |
||
53 | protected $consumerSecret; |
||
54 | |||
55 | /** |
||
56 | * Client options. |
||
57 | * |
||
58 | * @var Options |
||
59 | */ |
||
60 | protected $options; |
||
61 | |||
62 | /** |
||
63 | * Request. |
||
64 | * |
||
65 | * @var Request |
||
66 | */ |
||
67 | private $request; |
||
68 | |||
69 | /** |
||
70 | * Response. |
||
71 | * |
||
72 | * @var Response |
||
73 | */ |
||
74 | private $response; |
||
75 | |||
76 | /** |
||
77 | * Response headers. |
||
78 | * |
||
79 | * @var string |
||
80 | */ |
||
81 | private $responseHeaders; |
||
82 | |||
83 | /** |
||
84 | * Initialize HTTP client. |
||
85 | * |
||
86 | * @param string $url Store URL. |
||
87 | * @param string $consumerKey Consumer key. |
||
88 | * @param string $consumerSecret Consumer Secret. |
||
89 | * @param array $options Client options. |
||
90 | */ |
||
91 | public function __construct($url, $consumerKey, $consumerSecret, $options) |
||
92 | { |
||
93 | if (!\function_exists('curl_version')) { |
||
94 | throw new HttpClientException('cURL is NOT installed on this server', -1, new Request(), new Response()); |
||
95 | } |
||
96 | |||
97 | $this->options = new Options($options); |
||
98 | $this->url = $this->buildApiUrl($url); |
||
99 | $this->consumerKey = $consumerKey; |
||
100 | $this->consumerSecret = $consumerSecret; |
||
101 | } |
||
102 | |||
103 | /** |
||
104 | * Check if is under SSL. |
||
105 | * |
||
106 | * @return bool |
||
107 | */ |
||
108 | protected function isSsl() |
||
109 | { |
||
110 | return 'https://' === \substr($this->url, 0, 8); |
||
111 | } |
||
112 | |||
113 | /** |
||
114 | * Build API URL. |
||
115 | * |
||
116 | * @param string $url Store URL. |
||
117 | * |
||
118 | * @return string |
||
119 | */ |
||
120 | protected function buildApiUrl($url) |
||
121 | { |
||
122 | $api = $this->options->isWPAPI() ? $this->options->apiPrefix() : '/wc-api/'; |
||
123 | |||
124 | return \rtrim($url, '/') . $api . $this->options->getVersion() . '/'; |
||
125 | } |
||
126 | |||
127 | /** |
||
128 | * Build URL. |
||
129 | * |
||
130 | * @param string $url URL. |
||
131 | * @param array $parameters Query string parameters. |
||
132 | * |
||
133 | * @return string |
||
134 | */ |
||
135 | protected function buildUrlQuery($url, $parameters = []) |
||
136 | { |
||
137 | if (!empty($parameters)) { |
||
138 | if (false !== strpos($url, '?') { |
||
139 | $url .= '&' . \http_build_query($parameters); |
||
|
|||
140 | } else { |
||
141 | $url .= '?' . \http_build_query($parameters); |
||
142 | } |
||
143 | } |
||
144 | |||
145 | return $url; |
||
146 | } |
||
147 | |||
148 | /** |
||
149 | * Authenticate. |
||
150 | * |
||
151 | * @param string $url Request URL. |
||
152 | * @param string $method Request method. |
||
153 | * @param array $parameters Request parameters. |
||
154 | * |
||
155 | * @return array |
||
156 | */ |
||
157 | protected function authenticate($url, $method, $parameters = []) |
||
158 | { |
||
159 | // Setup authentication. |
||
160 | if ($this->isSsl()) { |
||
161 | $basicAuth = new BasicAuth( |
||
162 | $this->ch, |
||
163 | $this->consumerKey, |
||
164 | $this->consumerSecret, |
||
165 | $this->options->isQueryStringAuth(), |
||
166 | $parameters |
||
167 | ); |
||
168 | $parameters = $basicAuth->getParameters(); |
||
169 | } else { |
||
170 | $oAuth = new OAuth( |
||
171 | $url, |
||
172 | $this->consumerKey, |
||
173 | $this->consumerSecret, |
||
174 | $this->options->getVersion(), |
||
175 | $method, |
||
176 | $parameters, |
||
177 | $this->options->oauthTimestamp() |
||
178 | ); |
||
179 | $parameters = $oAuth->getParameters(); |
||
180 | } |
||
181 | |||
182 | return $parameters; |
||
183 | } |
||
184 | |||
185 | /** |
||
186 | * Setup method. |
||
187 | * |
||
188 | * @param string $method Request method. |
||
189 | */ |
||
190 | protected function setupMethod($method) |
||
191 | { |
||
192 | if ('POST' == $method) { |
||
193 | \curl_setopt($this->ch, CURLOPT_POST, true); |
||
194 | } elseif (\in_array($method, ['PUT', 'DELETE', 'OPTIONS'])) { |
||
195 | \curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method); |
||
196 | } |
||
197 | } |
||
198 | |||
199 | /** |
||
200 | * Get request headers. |
||
201 | * |
||
202 | * @param bool $sendData If request send data or not. |
||
203 | * |
||
204 | * @return array |
||
205 | */ |
||
206 | protected function getRequestHeaders($sendData = false) |
||
207 | { |
||
208 | $headers = [ |
||
209 | 'Accept' => 'application/json', |
||
210 | 'User-Agent' => $this->options->userAgent() . '/' . Client::VERSION, |
||
211 | ]; |
||
212 | |||
213 | if ($sendData) { |
||
214 | $headers['Content-Type'] = 'application/json;charset=utf-8'; |
||
215 | } |
||
216 | |||
217 | return $headers; |
||
218 | } |
||
219 | |||
220 | /** |
||
221 | * Create request. |
||
222 | * |
||
223 | * @param string $endpoint Request endpoint. |
||
224 | * @param string $method Request method. |
||
225 | * @param array $data Request data. |
||
226 | * @param array $parameters Request parameters. |
||
227 | * |
||
228 | * @return Request |
||
229 | */ |
||
230 | protected function createRequest($endpoint, $method, $data = [], $parameters = []) |
||
231 | { |
||
232 | $body = ''; |
||
233 | $url = $this->url . $endpoint; |
||
234 | $hasData = !empty($data); |
||
235 | |||
236 | // Setup authentication. |
||
237 | $parameters = $this->authenticate($url, $method, $parameters); |
||
238 | |||
239 | // Setup method. |
||
240 | $this->setupMethod($method); |
||
241 | |||
242 | // Include post fields. |
||
243 | if ($hasData) { |
||
244 | $body = \json_encode($data); |
||
245 | \curl_setopt($this->ch, CURLOPT_POSTFIELDS, $body); |
||
246 | } |
||
247 | |||
248 | $this->request = new Request( |
||
249 | $this->buildUrlQuery($url, $parameters), |
||
250 | $method, |
||
251 | $parameters, |
||
252 | $this->getRequestHeaders($hasData), |
||
253 | $body |
||
254 | ); |
||
255 | |||
256 | return $this->getRequest(); |
||
257 | } |
||
258 | |||
259 | /** |
||
260 | * Get response headers. |
||
261 | * |
||
262 | * @return array |
||
263 | */ |
||
264 | protected function getResponseHeaders() |
||
265 | { |
||
266 | $headers = []; |
||
267 | $lines = \explode("\n", $this->responseHeaders); |
||
268 | $lines = \array_filter($lines, 'trim'); |
||
269 | |||
270 | foreach ($lines as $index => $line) { |
||
271 | // Remove HTTP/xxx params. |
||
272 | if (strpos($line, ': ') === false) { |
||
273 | continue; |
||
274 | } |
||
275 | |||
276 | list($key, $value) = \explode(': ', $line); |
||
277 | |||
278 | $headers[$key] = isset($headers[$key]) ? $headers[$key] . ', ' . trim($value) : trim($value); |
||
279 | } |
||
280 | |||
281 | return $headers; |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * Create response. |
||
286 | * |
||
287 | * @return Response |
||
288 | */ |
||
289 | protected function createResponse() |
||
290 | { |
||
291 | |||
292 | // Set response headers. |
||
293 | $this->responseHeaders = ''; |
||
294 | \curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($_, $headers) { |
||
295 | $this->responseHeaders .= $headers; |
||
296 | return \strlen($headers); |
||
297 | }); |
||
298 | |||
299 | // Get response data. |
||
300 | $body = \curl_exec($this->ch); |
||
301 | $code = \curl_getinfo($this->ch, CURLINFO_HTTP_CODE); |
||
302 | $headers = $this->getResponseHeaders(); |
||
303 | |||
304 | // Register response. |
||
305 | $this->response = new Response($code, $headers, $body); |
||
306 | |||
307 | return $this->getResponse(); |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * Set default cURL settings. |
||
312 | */ |
||
313 | protected function setDefaultCurlSettings() |
||
314 | { |
||
315 | $verifySsl = $this->options->verifySsl(); |
||
316 | $timeout = $this->options->getTimeout(); |
||
317 | $followRedirects = $this->options->getFollowRedirects(); |
||
318 | |||
319 | \curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verifySsl); |
||
320 | if (!$verifySsl) { |
||
321 | \curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $verifySsl); |
||
322 | } |
||
323 | if ($followRedirects) { |
||
324 | \curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); |
||
325 | } |
||
326 | \curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout); |
||
327 | \curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout); |
||
328 | \curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); |
||
329 | \curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->request->getRawHeaders()); |
||
330 | \curl_setopt($this->ch, CURLOPT_URL, $this->request->getUrl()); |
||
331 | } |
||
332 | |||
333 | /** |
||
334 | * Look for errors in the request. |
||
335 | * |
||
336 | * @param array $parsedResponse Parsed body response. |
||
337 | */ |
||
338 | protected function lookForErrors($parsedResponse) |
||
339 | { |
||
340 | // Any non-200/201/202 response code indicates an error. |
||
341 | if (!\in_array($this->response->getCode(), ['200', '201', '202'])) { |
||
342 | $errors = isset($parsedResponse->errors) ? $parsedResponse->errors : $parsedResponse; |
||
343 | $errorMessage = ''; |
||
344 | $errorCode = ''; |
||
345 | |||
346 | if (is_array($errors)) { |
||
347 | $errorMessage = $errors[0]->message; |
||
348 | $errorCode = $errors[0]->code; |
||
349 | } elseif (isset($errors->message, $errors->code)) { |
||
350 | $errorMessage = $errors->message; |
||
351 | $errorCode = $errors->code; |
||
352 | } |
||
353 | |||
354 | throw new HttpClientException( |
||
355 | \sprintf('Error: %s [%s]', $errorMessage, $errorCode), |
||
356 | $this->response->getCode(), |
||
357 | $this->request, |
||
358 | $this->response |
||
359 | ); |
||
360 | } |
||
361 | } |
||
362 | |||
363 | /** |
||
364 | * Process response. |
||
365 | * |
||
366 | * @return array |
||
367 | */ |
||
368 | protected function processResponse() |
||
369 | { |
||
370 | $body = $this->response->getBody(); |
||
371 | |||
372 | // Look for UTF-8 BOM and remove. |
||
373 | if (0 === strpos(bin2hex(substr($body, 0, 4)), 'efbbbf')) { |
||
374 | $body = substr($body, 3); |
||
375 | } |
||
376 | |||
377 | $parsedResponse = \json_decode($body); |
||
378 | |||
379 | // Test if return a valid JSON. |
||
380 | if (JSON_ERROR_NONE !== json_last_error()) { |
||
381 | $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned'; |
||
382 | throw new HttpClientException( |
||
383 | sprintf('JSON ERROR: %s', $message), |
||
384 | $this->response->getCode(), |
||
385 | $this->request, |
||
386 | $this->response |
||
387 | ); |
||
388 | } |
||
389 | |||
390 | $this->lookForErrors($parsedResponse); |
||
391 | |||
392 | return $parsedResponse; |
||
393 | } |
||
394 | |||
395 | /** |
||
396 | * Make requests. |
||
397 | * |
||
398 | * @param string $endpoint Request endpoint. |
||
399 | * @param string $method Request method. |
||
400 | * @param array $data Request data. |
||
401 | * @param array $parameters Request parameters. |
||
402 | * |
||
403 | * @return array |
||
404 | */ |
||
405 | public function request($endpoint, $method, $data = [], $parameters = []) |
||
406 | { |
||
407 | // Initialize cURL. |
||
408 | $this->ch = \curl_init(); |
||
409 | |||
410 | // Set request args. |
||
411 | $request = $this->createRequest($endpoint, $method, $data, $parameters); |
||
412 | |||
413 | // Default cURL settings. |
||
414 | $this->setDefaultCurlSettings(); |
||
415 | |||
416 | // Get response. |
||
417 | $response = $this->createResponse(); |
||
418 | |||
419 | // Check for cURL errors. |
||
420 | if (\curl_errno($this->ch)) { |
||
421 | throw new HttpClientException('cURL Error: ' . \curl_error($this->ch), 0, $request, $response); |
||
422 | } |
||
423 | |||
424 | \curl_close($this->ch); |
||
425 | |||
426 | return $this->processResponse(); |
||
427 | } |
||
428 | |||
429 | /** |
||
430 | * Get request data. |
||
431 | * |
||
432 | * @return Request |
||
433 | */ |
||
434 | public function getRequest() |
||
435 | { |
||
436 | return $this->request; |
||
437 | } |
||
438 | |||
439 | /** |
||
440 | * Get response data. |
||
441 | * |
||
442 | * @return Response |
||
443 | */ |
||
444 | public function getResponse() |
||
445 | { |
||
449 |