Completed
Push — master ( 3150c4...4cbb1c )
by
unknown
02:06
created

HttpClient::getResponseHeaders()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 10
nc 4
nop 0
1
<?php
2
/**
3
 * WooCommerce REST API HTTP Client
4
 *
5
 * @category HttpClient
6
 * @package  Automattic/WooCommerce
7
 */
8
9
namespace Automattic\WooCommerce\HttpClient;
10
11
use Automattic\WooCommerce\Client;
12
use Automattic\WooCommerce\HttpClient\BasicAuth;
13
use Automattic\WooCommerce\HttpClient\HttpClientException;
14
use Automattic\WooCommerce\HttpClient\OAuth;
15
use Automattic\WooCommerce\HttpClient\Options;
16
use Automattic\WooCommerce\HttpClient\Request;
17
use Automattic\WooCommerce\HttpClient\Response;
18
19
/**
20
 * REST API HTTP Client class.
21
 *
22
 * @package Automattic/WooCommerce
23
 */
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
            $url .= '?' . \http_build_query($parameters);
139
        }
140
141
        return $url;
142
    }
143
144
    /**
145
     * Authenticate.
146
     *
147
     * @param string $url        Request URL.
148
     * @param string $method     Request method.
149
     * @param array  $parameters Request parameters.
150
     *
151
     * @return array
152
     */
153
    protected function authenticate($url, $method, $parameters = [])
154
    {
155
        // Setup authentication.
156
        if ($this->isSsl()) {
157
            $basicAuth  = new BasicAuth($this->ch, $this->consumerKey, $this->consumerSecret, $this->options->isQueryStringAuth(), $parameters);
158
            $parameters = $basicAuth->getParameters();
159
        } else {
160
            $oAuth      = new OAuth($url, $this->consumerKey, $this->consumerSecret, $this->options->getVersion(), $method, $parameters, $this->options->oauthTimestamp());
161
            $parameters = $oAuth->getParameters();
162
        }
163
164
        return $parameters;
165
    }
166
167
    /**
168
     * Setup method.
169
     *
170
     * @param string $method Request method.
171
     */
172
    protected function setupMethod($method)
173
    {
174
        if ('POST' == $method) {
175
            \curl_setopt($this->ch, CURLOPT_POST, true);
176
        } else if (\in_array($method, ['PUT', 'DELETE', 'OPTIONS'])) {
177
            \curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
178
        }
179
    }
180
181
    /**
182
     * Get request headers.
183
     *
184
     * @return array
185
     */
186
    protected function getRequestHeaders()
187
    {
188
        return [
189
            'Accept'       => 'application/json',
190
            'Content-Type' => 'application/json',
191
            'User-Agent'   => 'WooCommerce API Client-PHP/' . Client::VERSION,
192
        ];
193
    }
194
195
    /**
196
     * Create request.
197
     *
198
     * @param string $endpoint   Request endpoint.
199
     * @param string $method     Request method.
200
     * @param array  $data       Request data.
201
     * @param array  $parameters Request parameters.
202
     *
203
     * @return Request
204
     */
205
    protected function createRequest($endpoint, $method, $data = [], $parameters = [])
206
    {
207
        $body = '';
208
        $url  = $this->url . $endpoint;
209
210
        // Setup authentication.
211
        $parameters = $this->authenticate($url, $method, $parameters);
212
213
        // Setup method.
214
        $this->setupMethod($method);
215
216
        // Include post fields.
217
        if (!empty($data)) {
218
            $body = \json_encode($data);
219
            \curl_setopt($this->ch, CURLOPT_POSTFIELDS, $body);
220
        }
221
222
        $this->request = new Request($this->buildUrlQuery($url, $parameters), $method, $parameters, $this->getRequestHeaders(), $body);
223
224
        return $this->getRequest();
225
    }
226
227
    /**
228
     * Get response headers.
229
     *
230
     * @return array
231
     */
232
    protected function getResponseHeaders()
233
    {
234
        $headers = [];
235
        $lines   = \explode("\n", $this->responseHeaders);
236
        $lines   = \array_filter($lines, 'trim');
237
238
        foreach ($lines as $index => $line) {
239
            // Remove HTTP/xxx params.
240
            if (strpos($line, ': ') === false) {
241
                continue;
242
            }
243
244
            list($key, $value) = \explode(': ', $line);
245
246
            $headers[$key] = isset($headers[$key]) ? $headers[$key] .= ', ' . trim($value) : trim($value);
247
        }
248
249
        return $headers;
250
    }
251
252
    /**
253
     * Create response.
254
     *
255
     * @return Response
256
     */
257
    protected function createResponse()
258
    {
259
260
        // Set response headers.
261
        $this->responseHeaders = '';
262
        \curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($_, $headers) {
263
            $this->responseHeaders .= $headers;
264
            return \strlen($headers);
265
        });
266
267
        // Get response data.
268
        $body    = \curl_exec($this->ch);
269
        $code    = \curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
270
        $headers = $this->getResponseHeaders();
271
272
        // Register response.
273
        $this->response = new Response($code, $headers, $body);
274
275
        return $this->getResponse();
276
    }
277
278
    /**
279
     * Set default cURL settings.
280
     */
281
    protected function setDefaultCurlSettings()
282
    {
283
        $verifySsl = $this->options->verifySsl();
284
        $timeout   = $this->options->getTimeout();
285
286
        \curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verifySsl);
287
        if (!$verifySsl) {
288
            \curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $verifySsl);
289
        }
290
        \curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);
291
        \curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);
292
        \curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
293
        \curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->request->getRawHeaders());
294
        \curl_setopt($this->ch, CURLOPT_URL, $this->request->getUrl());
295
    }
296
297
    /**
298
     * Look for errors in the request.
299
     *
300
     * @param array $parsedResponse Parsed body response.
301
     */
302
    protected function lookForErrors($parsedResponse)
303
    {
304
        // Any non-200/201/202 response code indicates an error.
305
        if (!\in_array($this->response->getCode(), ['200', '201', '202'])) {
306
            $errors = !empty($parsedResponse['errors']) ? $parsedResponse['errors'] : $parsedResponse;
307
308
            if (!empty($errors[0])) {
309
                $errorMessage = $errors[0]['message'];
310
                $errorCode    = $errors[0]['code'];
311
            } else {
312
                $errorMessage = $errors['message'];
313
                $errorCode    = $errors['code'];
314
            }
315
316
            throw new HttpClientException(\sprintf('Error: %s [%s]', $errorMessage, $errorCode), $this->response->getCode(), $this->request, $this->response);
317
        }
318
    }
319
320
    /**
321
     * Process response.
322
     *
323
     * @return array
324
     */
325
    protected function processResponse()
326
    {
327
        $parsedResponse = \json_decode($this->response->getBody(), true);
328
329
        // Test if return a valid JSON.
330
        if (JSON_ERROR_NONE !== json_last_error()) {
331
            $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned';
332
            throw new HttpClientException($message, $this->response->getCode(), $this->request, $this->response);
333
        }
334
335
        $this->lookForErrors($parsedResponse);
336
337
        return $parsedResponse;
338
    }
339
340
    /**
341
     * Make requests.
342
     *
343
     * @param string $endpoint   Request endpoint.
344
     * @param string $method     Request method.
345
     * @param array  $data       Request data.
346
     * @param array  $parameters Request parameters.
347
     *
348
     * @return array
349
     */
350
    public function request($endpoint, $method, $data = [], $parameters = [])
351
    {
352
        // Initialize cURL.
353
        $this->ch = \curl_init();
354
355
        // Set request args.
356
        $request = $this->createRequest($endpoint, $method, $data, $parameters);
357
358
        // Default cURL settings.
359
        $this->setDefaultCurlSettings();
360
361
        // Get response.
362
        $response = $this->createResponse();
363
364
        // Check for cURL errors.
365
        if (\curl_errno($this->ch)) {
366
            throw new HttpClientException('cURL Error: ' . \curl_error($this->ch), 0, $request, $response);
367
        }
368
369
        \curl_close($this->ch);
370
371
        return $this->processResponse();
372
    }
373
374
    /**
375
     * Get request data.
376
     *
377
     * @return Request
378
     */
379
    public function getRequest()
380
    {
381
        return $this->request;
382
    }
383
384
    /**
385
     * Get response data.
386
     *
387
     * @return Response
388
     */
389
    public function getResponse()
390
    {
391
        return $this->response;
392
    }
393
}
394