Completed
Push — master ( e5ac3f...15a5b4 )
by Drew
10:01 queued 02:26
created

MailChimp::makeRequest()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 66
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 66
rs 7.0832
cc 7
eloc 48
nc 12
nop 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace DrewM\MailChimp;
4
5
/**
6
 * Super-simple, minimum abstraction MailChimp API v3 wrapper
7
 * MailChimp API v3: http://developer.mailchimp.com
8
 * This wrapper: https://github.com/drewm/mailchimp-api
9
 *
10
 * @author  Drew McLellan <[email protected]>
11
 * @version 2.4
12
 */
13
class MailChimp
14
{
15
    private $api_key;
16
    private $api_endpoint = 'https://<dc>.api.mailchimp.com/3.0';
17
18
    const TIMEOUT = 10;
19
20
    /*  SSL Verification
21
        Read before disabling:
22
        http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
23
    */
24
    public $verify_ssl = true;
25
26
    private $request_successful = false;
27
    private $last_error         = '';
28
    private $last_response      = array();
29
    private $last_request       = array();
30
31
    /**
32
     * Create a new instance
33
     *
34
     * @param string $api_key      Your MailChimp API key
35
     * @param string $api_endpoint Optional custom API endpoint
36
     *
37
     * @throws \Exception
38
     */
39
    public function __construct($api_key, $api_endpoint = null)
40
    {
41
        if (!function_exists('curl_init') || !function_exists('curl_setopt')) {
42
            throw new \Exception("cURL support is required, but can't be found.");
43
        }
44
45
        $this->api_key = $api_key;
46
47
        if ($api_endpoint === null) {
48
            if (strpos($this->api_key, '-') === false) {
49
                throw new \Exception("Invalid MailChimp API key `{$api_key}` supplied.");
50
            }
51
            list(, $data_center) = explode('-', $this->api_key);
52
            $this->api_endpoint = str_replace('<dc>', $data_center, $this->api_endpoint);
53
        } else {
54
            $this->api_endpoint = $api_endpoint;
55
        }
56
57
        $this->last_response = array('headers' => null, 'body' => null);
58
    }
59
60
    /**
61
     * Create a new instance of a Batch request. Optionally with the ID of an existing batch.
62
     *
63
     * @param string $batch_id Optional ID of an existing batch, if you need to check its status for example.
64
     *
65
     * @return Batch            New Batch object.
66
     */
67
    public function new_batch($batch_id = null)
68
    {
69
        return new Batch($this, $batch_id);
70
    }
71
72
    /**
73
     * @return string The url to the API endpoint
74
     */
75
    public function getApiEndpoint()
76
    {
77
        return $this->api_endpoint;
78
    }
79
80
81
    /**
82
     * Convert an email address into a 'subscriber hash' for identifying the subscriber in a method URL
83
     *
84
     * @param   string $email The subscriber's email address
85
     *
86
     * @return  string          Hashed version of the input
87
     */
88
    public function subscriberHash($email)
89
    {
90
        return md5(strtolower($email));
91
    }
92
93
    /**
94
     * Was the last request successful?
95
     *
96
     * @return bool  True for success, false for failure
97
     */
98
    public function success()
99
    {
100
        return $this->request_successful;
101
    }
102
103
    /**
104
     * Get the last error returned by either the network transport, or by the API.
105
     * If something didn't work, this should contain the string describing the problem.
106
     *
107
     * @return  string|false  describing the error
108
     */
109
    public function getLastError()
110
    {
111
        return $this->last_error ?: false;
112
    }
113
114
    /**
115
     * Get an array containing the HTTP headers and the body of the API response.
116
     *
117
     * @return array  Assoc array with keys 'headers' and 'body'
118
     */
119
    public function getLastResponse()
120
    {
121
        return $this->last_response;
122
    }
123
124
    /**
125
     * Get an array containing the HTTP headers and the body of the API request.
126
     *
127
     * @return array  Assoc array
128
     */
129
    public function getLastRequest()
130
    {
131
        return $this->last_request;
132
    }
133
134
    /**
135
     * Make an HTTP DELETE request - for deleting data
136
     *
137
     * @param   string $method  URL of the API request method
138
     * @param   array  $args    Assoc array of arguments (if any)
139
     * @param   int    $timeout Timeout limit for request in seconds
140
     *
141
     * @return  array|false   Assoc array of API response, decoded from JSON
142
     */
143
    public function delete($method, $args = array(), $timeout = self::TIMEOUT)
144
    {
145
        return $this->makeRequest('delete', $method, $args, $timeout);
146
    }
147
148
    /**
149
     * Make an HTTP GET request - for retrieving data
150
     *
151
     * @param   string $method  URL of the API request method
152
     * @param   array  $args    Assoc array of arguments (usually your data)
153
     * @param   int    $timeout Timeout limit for request in seconds
154
     *
155
     * @return  array|false   Assoc array of API response, decoded from JSON
156
     */
157
    public function get($method, $args = array(), $timeout = self::TIMEOUT)
158
    {
159
        return $this->makeRequest('get', $method, $args, $timeout);
160
    }
161
162
    /**
163
     * Make an HTTP PATCH request - for performing partial updates
164
     *
165
     * @param   string $method  URL of the API request method
166
     * @param   array  $args    Assoc array of arguments (usually your data)
167
     * @param   int    $timeout Timeout limit for request in seconds
168
     *
169
     * @return  array|false   Assoc array of API response, decoded from JSON
170
     */
171
    public function patch($method, $args = array(), $timeout = self::TIMEOUT)
172
    {
173
        return $this->makeRequest('patch', $method, $args, $timeout);
174
    }
175
176
    /**
177
     * Make an HTTP POST request - for creating and updating items
178
     *
179
     * @param   string $method  URL of the API request method
180
     * @param   array  $args    Assoc array of arguments (usually your data)
181
     * @param   int    $timeout Timeout limit for request in seconds
182
     *
183
     * @return  array|false   Assoc array of API response, decoded from JSON
184
     */
185
    public function post($method, $args = array(), $timeout = self::TIMEOUT)
186
    {
187
        return $this->makeRequest('post', $method, $args, $timeout);
188
    }
189
190
    /**
191
     * Make an HTTP PUT request - for creating new items
192
     *
193
     * @param   string $method  URL of the API request method
194
     * @param   array  $args    Assoc array of arguments (usually your data)
195
     * @param   int    $timeout Timeout limit for request in seconds
196
     *
197
     * @return  array|false   Assoc array of API response, decoded from JSON
198
     */
199
    public function put($method, $args = array(), $timeout = self::TIMEOUT)
200
    {
201
        return $this->makeRequest('put', $method, $args, $timeout);
202
    }
203
204
    /**
205
     * Performs the underlying HTTP request. Not very exciting.
206
     *
207
     * @param  string $http_verb The HTTP verb to use: get, post, put, patch, delete
208
     * @param  string $method    The API method to be called
209
     * @param  array  $args      Assoc array of parameters to be passed
210
     * @param int     $timeout
211
     *
212
     * @return array|false Assoc array of decoded result
213
     */
214
    private function makeRequest($http_verb, $method, $args = array(), $timeout = self::TIMEOUT)
215
    {
216
        $url = $this->api_endpoint . '/' . $method;
217
218
        $response = $this->prepareStateForRequest($http_verb, $method, $url, $timeout);
219
220
        $httpHeader = array(
221
            'Accept: application/vnd.api+json',
222
            'Content-Type: application/vnd.api+json',
223
            'Authorization: apikey ' . $this->api_key
224
        );
225
226
        if (isset($args["language"])) {
227
            $httpHeader[] = "Accept-Language: " . $args["language"];
228
        }
229
230
        $ch = curl_init();
231
        curl_setopt($ch, CURLOPT_URL, $url);
232
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
233
        curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)');
234
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
235
        curl_setopt($ch, CURLOPT_VERBOSE, true);
236
        curl_setopt($ch, CURLOPT_HEADER, true);
237
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
238
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
239
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
240
        curl_setopt($ch, CURLOPT_ENCODING, '');
241
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
242
243
        switch ($http_verb) {
244
            case 'post':
245
                curl_setopt($ch, CURLOPT_POST, true);
246
                $this->attachRequestPayload($ch, $args);
247
                break;
248
249
            case 'get':
250
                $query = http_build_query($args, '', '&');
251
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
252
                break;
253
254
            case 'delete':
255
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
256
                break;
257
258
            case 'patch':
259
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
260
                $this->attachRequestPayload($ch, $args);
261
                break;
262
263
            case 'put':
264
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
265
                $this->attachRequestPayload($ch, $args);
266
                break;
267
        }
268
269
        $responseContent     = curl_exec($ch);
270
        $response['headers'] = curl_getinfo($ch);
271
        $response            = $this->setResponseState($response, $responseContent, $ch);
272
        $formattedResponse   = $this->formatResponse($response);
273
274
        curl_close($ch);
275
276
        $this->determineSuccess($response, $formattedResponse, $timeout);
277
278
        return $formattedResponse;
279
    }
280
281
    /**
282
     * @param string  $http_verb
283
     * @param string  $method
284
     * @param string  $url
285
     * @param integer $timeout
286
     *
287
     * @return array
288
     */
289
    private function prepareStateForRequest($http_verb, $method, $url, $timeout)
290
    {
291
        $this->last_error = '';
292
293
        $this->request_successful = false;
294
295
        $this->last_response = array(
296
            'headers'     => null, // array of details from curl_getinfo()
297
            'httpHeaders' => null, // array of HTTP headers
298
            'body'        => null // content of the response
299
        );
300
301
        $this->last_request = array(
302
            'method'  => $http_verb,
303
            'path'    => $method,
304
            'url'     => $url,
305
            'body'    => '',
306
            'timeout' => $timeout,
307
        );
308
309
        return $this->last_response;
310
    }
311
312
    /**
313
     * Get the HTTP headers as an array of header-name => header-value pairs.
314
     *
315
     * The "Link" header is parsed into an associative array based on the
316
     * rel names it contains. The original value is available under
317
     * the "_raw" key.
318
     *
319
     * @param string $headersAsString
320
     *
321
     * @return array
322
     */
323
    private function getHeadersAsArray($headersAsString)
324
    {
325
        $headers = array();
326
327
        foreach (explode("\r\n", $headersAsString) as $i => $line) {
328
            if ($i === 0) { // HTTP code
329
                continue;
330
            }
331
332
            $line = trim($line);
333
            if (empty($line)) {
334
                continue;
335
            }
336
337
            list($key, $value) = explode(': ', $line);
338
339
            if ($key == 'Link') {
340
                $value = array_merge(
341
                    array('_raw' => $value),
342
                    $this->getLinkHeaderAsArray($value)
343
                );
344
            }
345
346
            $headers[$key] = $value;
347
        }
348
349
        return $headers;
350
    }
351
352
    /**
353
     * Extract all rel => URL pairs from the provided Link header value
354
     *
355
     * Mailchimp only implements the URI reference and relation type from
356
     * RFC 5988, so the value of the header is something like this:
357
     *
358
     * 'https://us13.api.mailchimp.com/schema/3.0/Lists/Instance.json; rel="describedBy",
359
     * <https://us13.admin.mailchimp.com/lists/members/?id=XXXX>; rel="dashboard"'
360
     *
361
     * @param string $linkHeaderAsString
362
     *
363
     * @return array
364
     */
365
    private function getLinkHeaderAsArray($linkHeaderAsString)
366
    {
367
        $urls = array();
368
369
        if (preg_match_all('/<(.*?)>\s*;\s*rel="(.*?)"\s*/', $linkHeaderAsString, $matches)) {
370
            foreach ($matches[2] as $i => $relName) {
371
                $urls[$relName] = $matches[1][$i];
372
            }
373
        }
374
375
        return $urls;
376
    }
377
378
    /**
379
     * Encode the data and attach it to the request
380
     *
381
     * @param   resource $ch   cURL session handle, used by reference
382
     * @param   array    $data Assoc array of data to attach
383
     */
384
    private function attachRequestPayload(&$ch, $data)
385
    {
386
        $encoded                    = json_encode($data);
387
        $this->last_request['body'] = $encoded;
388
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
389
    }
390
391
    /**
392
     * Decode the response and format any error messages for debugging
393
     *
394
     * @param array $response The response from the curl request
395
     *
396
     * @return array|false    The JSON decoded into an array
397
     */
398
    private function formatResponse($response)
399
    {
400
        $this->last_response = $response;
401
402
        if (!empty($response['body'])) {
403
            return json_decode($response['body'], true);
404
        }
405
406
        return false;
407
    }
408
409
    /**
410
     * Do post-request formatting and setting state from the response
411
     *
412
     * @param array    $response        The response from the curl request
413
     * @param string   $responseContent The body of the response from the curl request
414
     * @param resource $ch              The curl resource
415
     *
416
     * @return array    The modified response
417
     */
418
    private function setResponseState($response, $responseContent, $ch)
419
    {
420
        if ($responseContent === false) {
421
            $this->last_error = curl_error($ch);
422
        } else {
423
424
            $headerSize = $response['headers']['header_size'];
425
426
            $response['httpHeaders'] = $this->getHeadersAsArray(substr($responseContent, 0, $headerSize));
427
            $response['body']        = substr($responseContent, $headerSize);
428
429
            if (isset($response['headers']['request_header'])) {
430
                $this->last_request['headers'] = $response['headers']['request_header'];
431
            }
432
        }
433
434
        return $response;
435
    }
436
437
    /**
438
     * Check if the response was successful or a failure. If it failed, store the error.
439
     *
440
     * @param array       $response          The response from the curl request
441
     * @param array|false $formattedResponse The response body payload from the curl request
442
     * @param int         $timeout           The timeout supplied to the curl request.
443
     *
444
     * @return bool     If the request was successful
445
     */
446
    private function determineSuccess($response, $formattedResponse, $timeout)
447
    {
448
        $status = $this->findHTTPStatus($response, $formattedResponse);
449
450
        if ($status >= 200 && $status <= 299) {
451
            $this->request_successful = true;
452
            return true;
453
        }
454
455
        if (isset($formattedResponse['detail'])) {
456
            $this->last_error = sprintf('%d: %s', $formattedResponse['status'], $formattedResponse['detail']);
457
            return false;
458
        }
459
460
        if ($timeout > 0 && $response['headers'] && $response['headers']['total_time'] >= $timeout) {
461
            $this->last_error = sprintf('Request timed out after %f seconds.', $response['headers']['total_time']);
462
            return false;
463
        }
464
465
        $this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
466
        return false;
467
    }
468
469
    /**
470
     * Find the HTTP status code from the headers or API response body
471
     *
472
     * @param array       $response          The response from the curl request
473
     * @param array|false $formattedResponse The response body payload from the curl request
474
     *
475
     * @return int  HTTP status code
476
     */
477
    private function findHTTPStatus($response, $formattedResponse)
478
    {
479
        if (!empty($response['headers']) && isset($response['headers']['http_code'])) {
480
            return (int)$response['headers']['http_code'];
481
        }
482
483
        if (!empty($response['body']) && isset($formattedResponse['status'])) {
484
            return (int)$formattedResponse['status'];
485
        }
486
487
        return 418;
488
    }
489
}
490