Completed
Push — master ( 3c720a...0593e5 )
by
unknown
03:47
created

HttpClient::getResponseHeaders()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 8.7972
cc 4
eloc 13
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);
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
            if(isset($headers[$key])) {
247
                $headers[$key] .= ', ' . trim($value);
248
            } else {
249
                $headers[$key] = trim($value);
250
            }
251
        }
252
253
        return $headers;
254
    }
255
256
    /**
257
     * Create response.
258
     *
259
     * @return Response
260
     */
261
    protected function createResponse()
262
    {
263
264
        // Set response headers.
265
        $this->responseHeaders = '';
266
        \curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, function ($_, $headers) {
267
            $this->responseHeaders .= $headers;
268
            return \strlen($headers);
269
        });
270
271
        // Get response data.
272
        $body    = \curl_exec($this->ch);
273
        $code    = \curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
274
        $headers = $this->getResponseHeaders();
275
276
        // Register response.
277
        $this->response = new Response($code, $headers, $body);
278
279
        return $this->getResponse();
280
    }
281
282
    /**
283
     * Set default cURL settings.
284
     */
285
    protected function setDefaultCurlSettings()
286
    {
287
        $verifySsl = $this->options->verifySsl();
288
        $timeout   = $this->options->getTimeout();
289
290
        \curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verifySsl);
291
        if (!$verifySsl) {
292
            \curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $verifySsl);
293
        }
294
        \curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);
295
        \curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);
296
        \curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
297
        \curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->request->getRawHeaders());
298
        \curl_setopt($this->ch, CURLOPT_URL, $this->request->getUrl());
299
    }
300
301
    /**
302
     * Look for errors in the request.
303
     *
304
     * @param array $parsedResponse Parsed body response.
305
     */
306
    protected function lookForErrors($parsedResponse)
307
    {
308
        // Any non-200/201/202 response code indicates an error.
309
        if (!\in_array($this->response->getCode(), ['200', '201', '202'])) {
310
            $errors = !empty($parsedResponse['errors']) ? $parsedResponse['errors'] : $parsedResponse;
311
312
            if (!empty($errors[0])) {
313
                $errorMessage = $errors[0]['message'];
314
                $errorCode    = $errors[0]['code'];
315
            } else {
316
                $errorMessage = $errors['message'];
317
                $errorCode    = $errors['code'];
318
            }
319
320
            throw new HttpClientException(\sprintf('Error: %s [%s]', $errorMessage, $errorCode), $this->response->getCode(), $this->request, $this->response);
321
        }
322
    }
323
324
    /**
325
     * Process response.
326
     *
327
     * @return array
328
     */
329
    protected function processResponse()
330
    {
331
        $parsedResponse = \json_decode($this->response->getBody(), true);
332
333
        // Test if return a valid JSON.
334
        if (JSON_ERROR_NONE !== json_last_error()) {
335
            $message = function_exists('json_last_error_msg') ? json_last_error_msg() : 'Invalid JSON returned';
336
            throw new HttpClientException($message, $this->response->getCode(), $this->request, $this->response);
337
        }
338
339
        $this->lookForErrors($parsedResponse);
340
341
        return $parsedResponse;
342
    }
343
344
    /**
345
     * Make requests.
346
     *
347
     * @param string $endpoint   Request endpoint.
348
     * @param string $method     Request method.
349
     * @param array  $data       Request data.
350
     * @param array  $parameters Request parameters.
351
     *
352
     * @return array
353
     */
354
    public function request($endpoint, $method, $data = [], $parameters = [])
355
    {
356
        // Initialize cURL.
357
        $this->ch = \curl_init();
358
359
        // Set request args.
360
        $request = $this->createRequest($endpoint, $method, $data, $parameters);
361
362
        // Default cURL settings.
363
        $this->setDefaultCurlSettings();
364
365
        // Get response.
366
        $response = $this->createResponse();
367
368
        // Check for cURL errors.
369
        if (\curl_errno($this->ch)) {
370
            throw new HttpClientException('cURL Error: ' . \curl_error($this->ch), 0, $request, $response);
371
        }
372
373
        \curl_close($this->ch);
374
375
        return $this->processResponse();
376
    }
377
378
    /**
379
     * Get request data.
380
     *
381
     * @return Request
382
     */
383
    public function getRequest()
384
    {
385
        return $this->request;
386
    }
387
388
    /**
389
     * Get response data.
390
     *
391
     * @return Response
392
     */
393
    public function getResponse()
394
    {
395
        return $this->response;
396
    }
397
}
398