Completed
Push — master ( d6460c...c7cd2a )
by Elf
46:10 queued 08:12
created

HttpClient::getResponseData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 3
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 3
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae;
4
5
use Closure;
6
use Exception;
7
use ReflectionClass;
8
use GuzzleHttp\Client;
9
use BadMethodCallException;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Str;
12
use InvalidArgumentException;
13
use GuzzleHttp\RequestOptions;
14
use Psr\Http\Message\UriInterface;
15
16
/**
17
 * @method $this get(string|UriInterface $uri = '', array $options = [])
18
 * @method $this head(string|UriInterface $uri = '', array $options = [])
19
 * @method $this post(string|UriInterface $uri = '', array $options = [])
20
 * @method $this put(string|UriInterface $uri = '', array $options = [])
21
 * @method $this patch(string|UriInterface $uri = '', array $options = [])
22
 * @method $this delete(string|UriInterface $uri = '', array $options = [])
23
 * @method $this options(string|UriInterface $uri = '', array $options = [])
24
 * @method \GuzzleHttp\Promise\PromiseInterface getAsync(string|UriInterface $uri = '', array $options = [])
25
 * @method \GuzzleHttp\Promise\PromiseInterface headAsync(string|UriInterface $uri = '', array $options = [])
26
 * @method \GuzzleHttp\Promise\PromiseInterface postAsync(string|UriInterface $uri = '', array $options = [])
27
 * @method \GuzzleHttp\Promise\PromiseInterface putAsync(string|UriInterface $uri = '', array $options = [])
28
 * @method \GuzzleHttp\Promise\PromiseInterface patchAsync(string|UriInterface $uri = '', array $options = [])
29
 * @method \GuzzleHttp\Promise\PromiseInterface deleteAsync(string|UriInterface $uri = '', array $options = [])
30
 * @method \GuzzleHttp\Promise\PromiseInterface optionsAsync(string|UriInterface $uri = '', array $options = [])
31
 * @method int getStatusCode()
32
 * @method string getReasonPhrase()
33
 * @method string getProtocolVersion()
34
 * @method array getHeaders()
35
 * @method bool hasHeader(string $header)
36
 * @method array getHeader(string $header)
37
 * @method string getHeaderLine(string $header)
38
 * @method \Psr\Http\Message\StreamInterface getBody()
39
 * @method $this allowRedirects(bool|array $value)
40
 * @method $this auth(array|string|null $value)
41
 * @method $this body(mixed $value)
42
 * @method $this cert(string|array $value)
43
 * @method $this cookies(bool|\GuzzleHttp\Cookie\CookieJarInterface $value)
44
 * @method $this connectTimeout(float $value)
45
 * @method $this debug(bool|resource $value)
46
 * @method $this decodeContent(bool $value)
47
 * @method $this delay(int|float $value)
48
 * @method $this expect(bool|int $value)
49
 * @method $this formParams(array $value)
50
 * @method $this headers(array $value)
51
 * @method $this httpErrors(bool $value)
52
 * @method $this json(mixed $value)
53
 * @method $this multipart(array $value)
54
 * @method $this onHeaders(callable $value)
55
 * @method $this onStats(callable $value)
56
 * @method $this progress(callable $value)
57
 * @method $this proxy(string|array $value)
58
 * @method $this query(array|string $value)
59
 * @method $this sink(string|resource|\Psr\Http\Message\StreamInterface $value)
60
 * @method $this sslKey(array|string $value)
61
 * @method $this stream(bool $value)
62
 * @method $this verify(bool|string $value)
63
 * @method $this timeout(float $value)
64
 * @method $this readTimeout(float $value)
65
 * @method $this version(float|string $value)
66
 * @method $this forceIpResolve(string $value)
67
 *
68
 * @see http://docs.guzzlephp.org/en/stable/request-options.html Request Options
69
 */
70
class HttpClient
71
{
72
    /**
73
     * The default request options.
74
     *
75
     * @var array
76
     */
77
    protected static $defaultOptions = [
78
        'catch_exceptions' => true,
79
        'http_errors' => false,
80
        'connect_timeout' => 5,
81
        'timeout' => 20,
82
    ];
83
84
    /**
85
     * The Guzzle client.
86
     *
87
     * @var \GuzzleHttp\Client
88
     */
89
    protected $client;
90
91
    /**
92
     * The request options.
93
     *
94
     * @var array
95
     */
96
    protected $options = [];
97
98
    /**
99
     * The Guzzle response.
100
     *
101
     * @var \GuzzleHttp\Psr7\Response
102
     */
103
    protected $response;
104
105
    /**
106
     * Get the default request options.
107
     *
108
     * @return array
109
     */
110 124
    public static function defaultOptions()
111
    {
112 124
        return static::$defaultOptions;
113
    }
114
115
    /**
116
     * Set the default request options.
117
     *
118
     * @param  array  $options
119
     * @return void
120
     */
121 124
    public static function setDefaultOptions(array $options)
122
    {
123 124
        static::$defaultOptions = $options;
124 124
    }
125
126
    /**
127
     * Create a new HTTP client instance.
128
     *
129
     * @param  array|string|\Psr\Http\Message\UriInterface  $options  base URI or any request options
130
     * @return static
131
     */
132 8
    public static function create($options = [])
133
    {
134 8
        return new static($options);
135
    }
136
137
    /**
138
     * Create a new HTTP client instance.
139
     *
140
     * @param  array|string|\Psr\Http\Message\UriInterface  $options  base URI or any request options
141
     *
142
     * @throws \InvalidArgumentException
143
     */
144 128
    public function __construct($options = [])
145
    {
146 128
        if (is_string($options) || $options instanceof UriInterface) {
147 8
            $options = ['base_uri' => $options];
148 126
        } elseif (! is_array($options)) {
149 4
            throw new InvalidArgumentException('Options must be a string, UriInterface, or an array');
150
        }
151
152 124
        $this->client = new Client(
153 124
            $this->getMergedOptions(static::defaultOptions(), $options)
154 62
        );
155
156 124
        $this->options = $this->client->getConfig();
157 124
    }
158
159
    /**
160
     * Get merged given request options.
161
     *
162
     * @param  array  ...$options
163
     * @return array
164
     */
165 124
    protected function getMergedOptions(...$options)
166
    {
167 124
        return array_replace_recursive(...$options);
0 ignored issues
show
Bug introduced by
$options is expanded, but the parameter $array of array_replace_recursive() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

167
        return array_replace_recursive(/** @scrutinizer ignore-type */ ...$options);
Loading history...
Bug introduced by
The call to array_replace_recursive() has too few arguments starting with array1. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

167
        return /** @scrutinizer ignore-call */ array_replace_recursive(...$options);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
168
    }
169
170
    /**
171
     * Get the Guzzle client instance.
172
     *
173
     * @return \GuzzleHttp\Client
174
     */
175 24
    public function getClient()
176
    {
177 24
        return $this->client;
178
    }
179
180
    /**
181
     * Get the request options using "dot" notation.
182
     *
183
     * @param  string|null  $key
184
     * @param  mixed  $default
185
     * @return mixed
186
     */
187 60
    public function getOption($key = null, $default = null)
188
    {
189 60
        return Arr::get($this->options, $key, $default);
190
    }
191
192
    /**
193
     * Set the request options using "dot" notation.
194
     *
195
     * @param  string|array  $key
196
     * @param  mixed  $value
197
     * @return $this
198
     */
199 44
    public function option($key, $value = null)
200
    {
201 44
        $keys = is_array($key) ? $key : [$key => $value];
202
203 44
        foreach ($keys as $key => $value) {
204 44
            Arr::set($this->options, $key, $value);
205 22
        }
206
207 44
        return $this;
208
    }
209
210
    /**
211
     * Merge the given options to the request options.
212
     *
213
     * @param  array  $options
214
     * @return $this
215
     */
216 4
    public function mergeOptions(array $options)
217
    {
218 4
        $this->options = $this->getMergedOptions($this->options, $options);
219
220 4
        return $this;
221
    }
222
223
    /**
224
     * Remove one or many request options using "dot" notation.
225
     *
226
     * @param  array|string  $keys
227
     * @return $this
228
     */
229 8
    public function removeOption($keys)
230
    {
231 8
        Arr::forget($this->options, is_array($keys) ? $keys : func_get_args());
232
233 8
        return $this;
234
    }
235
236
    /**
237
     * Determine whether to catch Guzzle exceptions.
238
     *
239
     * @return bool
240
     */
241 8
    public function areExceptionsCaught()
242
    {
243 8
        return $this->getOption('catch_exceptions', false);
244
    }
245
246
    /**
247
     * Set whether to catch Guzzle exceptions or not.
248
     *
249
     * @param  bool  $catch
250
     * @return $this
251
     */
252 8
    public function catchExceptions($catch)
253
    {
254 8
        return $this->option('catch_exceptions', (bool) $catch);
255
    }
256
257
    /**
258
     * Set a request header.
259
     *
260
     * @param  string  $name
261
     * @param  mixed  $value
262
     * @return $this
263
     */
264 20
    public function header($name, $value)
265
    {
266 20
        return $this->option('headers.'.$name, $value);
267
    }
268
269
    /**
270
     * Remove one or many request headers.
271
     *
272
     * @param  array|string  $names
273
     * @return $this
274
     */
275 4
    public function removeHeader($names)
276
    {
277 4
        $names = is_array($names) ? $names : func_get_args();
278
279 4
        return $this->option(
280 4
            'headers',
281 4
            Arr::except($this->getOption('headers', []), $names)
282 2
        );
283
    }
284
285
    /**
286
     * Set the request accept type.
287
     *
288
     * @param  string  $type
289
     * @return $this
290
     */
291 8
    public function accept($type)
292
    {
293 8
        return $this->header('Accept', $type);
294
    }
295
296
    /**
297
     * Set the request accept type to "application/json".
298
     *
299
     * @return $this
300
     */
301 4
    public function acceptJson()
302
    {
303 4
        return $this->accept('application/json');
304
    }
305
306
    /**
307
     * Set user agent for the request.
308
     *
309
     * @param  string  $value
310
     * @return $this
311
     */
312 4
    public function userAgent($value)
313
    {
314 4
        return $this->header('User-Agent', $value);
315
    }
316
317
    /**
318
     * Set the request content type.
319
     *
320
     * @param  string  $type
321
     * @return $this
322
     */
323 4
    public function contentType($type)
324
    {
325 4
        return $this->header('Content-Type', $type);
326
    }
327
328
    /**
329
     * Specify where the body of the response will be saved.
330
     * Set the "sink" option.
331
     *
332
     * @param  string|resource|\Psr\Http\Message\StreamInterface  $dest
333
     * @return $this
334
     */
335 4
    public function saveTo($dest)
336
    {
337 4
        return $this->removeOption('save_to')->option('sink', $dest);
338
    }
339
340
    /**
341
     * Get the Guzzle response instance.
342
     *
343
     * @return \GuzzleHttp\Psr7\Response|null
344
     */
345 16
    public function getResponse()
346
    {
347 16
        return $this->response;
348
    }
349
350
    /**
351
     * Get data from the response.
352
     *
353
     * @param  string|\Closure  $callback
354
     * @param  mixed  $parameters
355
     * @param  mixed  $default
356
     * @return mixed
357
     */
358 24
    public function getResponseData($callback, $parameters = [], $default = null)
359
    {
360 24
        if ($this->response) {
361 12
            return $callback instanceof Closure
362 14
                ? $callback($this->response, ...(array) $parameters)
363 24
                : $this->response->$callback(...(array) $parameters);
364
        }
365
366 4
        return $default;
367
    }
368
369
    /**
370
     * Get the response content.
371
     *
372
     * @return string
373
     */
374 16
    public function getContent()
375
    {
376 16
        return (string) $this->getBody();
377
    }
378
379
    /**
380
     * Get the JSON-decoded response content.
381
     *
382
     * @param  bool  $assoc
383
     * @return mixed
384
     */
385 8
    public function getJson($assoc = true)
386
    {
387 8
        return json_decode($this->getContent(), $assoc);
388
    }
389
390
    /**
391
     * Make request to a URI.
392
     *
393
     * @param  string|\Psr\Http\Message\UriInterface  $uri
394
     * @param  string  $method
395
     * @param  array  $options
396
     * @return $this
397
     */
398 44
    public function request($uri = '', $method = 'GET', array $options = [])
399
    {
400 44
        $this->response = null;
401
402 44
        $method = strtoupper($method);
403 44
        $options = $this->getMergedOptions($this->options, $options);
404
405
        try {
406 44
            $this->response = $this->client->request($method, $uri, $options);
407 24
        } catch (Exception $e) {
408 4
            if (! $this->areExceptionsCaught()) {
409 4
                throw $e;
410
            }
411
        }
412
413 44
        return $this;
414
    }
415
416
    /**
417
     * Make request to a URI, expecting JSON content.
418
     *
419
     * @param  string|\Psr\Http\Message\UriInterface  $uri
420
     * @param  string  $method
421
     * @param  array  $options
422
     * @return $this
423
     */
424 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
425
    {
426 8
        Arr::set($options, 'headers.Accept', 'application/json');
427
428 8
        return $this->request($uri, $method, $options);
429
    }
430
431
    /**
432
     * Make asynchronous request to a URI.
433
     *
434
     * @param  string|\Psr\Http\Message\UriInterface  $uri
435
     * @param  string  $method
436
     * @param  array  $options
437
     * @return \GuzzleHttp\Promise\PromiseInterface
438
     */
439 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
440
    {
441 8
        return $this->client->requestAsync(
442 8
            strtoupper($method),
443 8
            $uri,
444 8
            $this->getMergedOptions($this->options, $options)
445 4
        );
446
    }
447
448
    /**
449
     * Request the URI and return the response content.
450
     *
451
     * @param  string|\Psr\Http\Message\UriInterface  $uri
452
     * @param  string  $method
453
     * @param  array  $options
454
     * @return string
455
     */
456 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
457
    {
458 4
        return $this->request($uri, $method, $options)->getContent();
459
    }
460
461
    /**
462
     * Request the URI and return the JSON-decoded response content.
463
     *
464
     * @param  string|\Psr\Http\Message\UriInterface  $uri
465
     * @param  string  $method
466
     * @param  array  $options
467
     * @return mixed
468
     */
469 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
470
    {
471 4
        return $this->requestJson($uri, $method, $options)->getJson();
472
    }
473
474
    /**
475
     * Get all allowed magic request methods.
476
     *
477
     * @return array
478
     */
479 36
    protected function getMagicRequestMethods()
480
    {
481
        return [
482 36
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
483 18
        ];
484
    }
485
486
    /**
487
     * Determine if the given method is a magic request method.
488
     *
489
     * @param  string  $method
490
     * @param  string  &$requestMethod
491
     * @param  string  &$httpMethod
492
     * @return bool
493
     */
494 36
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
495
    {
496 36
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
497 4
            $httpMethod = substr($method, 0, $pos);
498 4
            $requestMethod = 'requestAsync';
499 2
        } else {
500 36
            $httpMethod = $method;
501 36
            $requestMethod = 'request';
502
        }
503
504 36
        if (in_array($httpMethod, $this->getMagicRequestMethods())) {
505 8
            return true;
506
        }
507
508 28
        $httpMethod = $requestMethod = null;
509
510 28
        return false;
511
    }
512
513
    /**
514
     * Get parameters for $this->request() from the magic request call.
515
     *
516
     * @param  string  $method
517
     * @param  array  $parameters
518
     * @return array
519
     */
520 8
    protected function getRequestParameters($method, array $parameters)
521
    {
522 8
        if (empty($parameters)) {
523 4
            $parameters = ['', $method];
524 2
        } else {
525 8
            array_splice($parameters, 1, 0, $method);
526
        }
527
528 8
        return $parameters;
529
    }
530
531
    /**
532
     * Get all allowed magic response methods.
533
     *
534
     * @return array
535
     */
536 28
    protected function getMagicResponseMethods()
537
    {
538
        return [
539 28
            'getStatusCode', 'getReasonPhrase', 'getProtocolVersion',
540 14
            'getHeaders', 'hasHeader', 'getHeader', 'getHeaderLine', 'getBody',
541 14
        ];
542
    }
543
544
    /**
545
     * Determine if the given method is a magic response method.
546
     *
547
     * @param  string  $method
548
     * @return bool
549
     */
550 28
    protected function isMagicResponseMethod($method)
551
    {
552 28
        return in_array($method, $this->getMagicResponseMethods());
553
    }
554
555
    /**
556
     * Get all allowed magic option methods.
557
     *
558
     * @return array
559
     */
560 8
    protected function getMagicOptionMethods()
561
    {
562 8
        static $optionMethods = null;
563
564 8
        if (is_null($optionMethods)) {
565 4
            $reflector = new ReflectionClass(RequestOptions::class);
566 4
            $optionMethods = array_map(
567 4
                [Str::class, 'camel'],
568 4
                array_values($reflector->getConstants())
569 2
            );
570 2
        }
571
572 8
        return $optionMethods;
573
    }
574
575
    /**
576
     * Determine if the given method is a magic option method.
577
     *
578
     * @param  string  $method
579
     * @return bool
580
     */
581 8
    protected function isMagicOptionMethod($method, &$option)
582
    {
583 8
        $option = in_array($method, $this->getMagicOptionMethods())
584 8
            ? Str::snake($method) : null;
585
586 8
        return (bool) $option;
587
    }
588
589
    /**
590
     * Handle magic method to send request, get response data, or set
591
     * request options.
592
     *
593
     * @param  string  $method
594
     * @param  array  $parameters
595
     * @return mixed
596
     *
597
     * @throws \InvalidArgumentException
598
     * @throws \BadMethodCallException
599
     */
600 36
    public function __call($method, $parameters)
601
    {
602 36
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
603 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
604
        }
605
606 28
        if ($this->isMagicResponseMethod($method)) {
607 20
            return $this->getResponseData($method, $parameters);
608
        }
609
610 8
        if ($this->isMagicOptionMethod($method, $option)) {
611 4
            if (empty($parameters)) {
612 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
613
            }
614
615 4
            return $this->option($option, $parameters[0]);
616
        }
617
618 4
        throw new BadMethodCallException("Method [$method] does not exist.");
619
    }
620
}
621