Completed
Push — master ( 82a3db...f89c27 )
by Elf
08:26 queued 56s
created

HttpClient::fetchJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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 120
    public static function defaultOptions()
111
    {
112 120
        return static::$defaultOptions;
113
    }
114
115
    /**
116
     * Set the default request options.
117
     *
118
     * @param  array  $options
119
     * @return void
120
     */
121 120
    public static function setDefaultOptions(array $options)
122
    {
123 120
        static::$defaultOptions = $options;
124 120
    }
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 124
    public function __construct($options = [])
145
    {
146 124
        if (is_string($options) || $options instanceof UriInterface) {
147 8
            $options = ['base_uri' => $options];
148 122
        } elseif (! is_array($options)) {
149 4
            throw new InvalidArgumentException('Options must be a string, UriInterface, or an array');
150
        }
151
152 120
        $this->client = new Client(
153 120
            $this->getMergedOptions(static::defaultOptions(), $options)
154 60
        );
155
156 120
        $this->options = $this->client->getConfig();
157 120
    }
158
159
    /**
160
     * Get the Guzzle client instance.
161
     *
162
     * @return \GuzzleHttp\Client
163
     */
164 24
    public function getClient()
165
    {
166 24
        return $this->client;
167
    }
168
169
    /**
170
     * Get the request options using "dot" notation.
171
     *
172
     * @param  string|null  $key
173
     * @param  mixed  $default
174
     * @return mixed
175
     */
176 56
    public function getOption($key = null, $default = null)
177
    {
178 56
        return Arr::get($this->options, $key, $default);
179
    }
180
181
    /**
182
     * Set the request options using "dot" notation.
183
     *
184
     * @param  string|array  $key
185
     * @param  mixed  $value
186
     * @return $this
187
     */
188 40
    public function option($key, $value = null)
189
    {
190 40
        $keys = is_array($key) ? $key : [$key => $value];
191
192 40
        foreach ($keys as $key => $value) {
193 40
            Arr::set($this->options, $key, $value);
194 20
        }
195
196 40
        return $this;
197
    }
198
199
    /**
200
     * Merge the given options to the request options.
201
     *
202
     * @param  array  $options
203
     * @return $this
204
     */
205 4
    public function mergeOptions(array $options)
206
    {
207 4
        $this->options = $this->getMergedOptions($this->options, $options);
208
209 4
        return $this;
210
    }
211
212
    /**
213
     * Get merged given request options.
214
     *
215
     * @param  array  ...$options
216
     * @return array
217
     */
218 120
    protected function getMergedOptions(...$options)
219
    {
220 120
        return array_replace_recursive(...$options);
0 ignored issues
show
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

220
        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...
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

220
        return array_replace_recursive(/** @scrutinizer ignore-type */ ...$options);
Loading history...
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
     * Set the request accept type.
271
     *
272
     * @param  string  $type
273
     * @return $this
274
     */
275 8
    public function accept($type)
276
    {
277 8
        return $this->header('Accept', $type);
278
    }
279
280
    /**
281
     * Set the request accept type to "application/json".
282
     *
283
     * @return $this
284
     */
285 4
    public function acceptJson()
286
    {
287 4
        return $this->accept('application/json');
288
    }
289
290
    /**
291
     * Set user agent for the request.
292
     *
293
     * @param  string  $value
294
     * @return $this
295
     */
296 4
    public function userAgent($value)
297
    {
298 4
        return $this->header('User-Agent', $value);
299
    }
300
301
    /**
302
     * Set the request content type.
303
     *
304
     * @param  string  $type
305
     * @return $this
306
     */
307 4
    public function contentType($type)
308
    {
309 4
        return $this->header('Content-Type', $type);
310
    }
311
312
    /**
313
     * Specify where the body of the response will be saved.
314
     * Set the "sink" option.
315
     *
316
     * @param  string|resource|\Psr\Http\Message\StreamInterface  $dest
317
     * @return $this
318
     */
319 4
    public function saveTo($dest)
320
    {
321 4
        return $this->removeOption('save_to')->option('sink', $dest);
322
    }
323
324
    /**
325
     * Get the Guzzle response instance.
326
     *
327
     * @return \GuzzleHttp\Psr7\Response|null
328
     */
329 16
    public function getResponse()
330
    {
331 16
        return $this->response;
332
    }
333
334
    /**
335
     * Get data from the response.
336
     *
337
     * @param  string|\Closure  $callback
338
     * @param  mixed  $parameters
339
     * @param  mixed  $default
340
     * @return mixed
341
     */
342 24
    public function getResponseData($callback, $parameters = [], $default = null)
343
    {
344 24
        if ($this->response) {
345 12
            return $callback instanceof Closure
346 14
                ? $callback($this->response, ...(array) $parameters)
347 24
                : $this->response->$callback(...(array) $parameters);
348
        }
349
350 4
        return $default;
351
    }
352
353
    /**
354
     * Get the response content.
355
     *
356
     * @return string
357
     */
358 16
    public function getContent()
359
    {
360 16
        return (string) $this->getBody();
361
    }
362
363
    /**
364
     * Get the JSON-decoded response content.
365
     *
366
     * @param  bool  $assoc
367
     * @return mixed
368
     */
369 8
    public function getJson($assoc = true)
370
    {
371 8
        return json_decode($this->getContent(), $assoc);
372
    }
373
374
    /**
375
     * Make request to a URI.
376
     *
377
     * @param  string|\Psr\Http\Message\UriInterface  $uri
378
     * @param  string  $method
379
     * @param  array  $options
380
     * @return $this
381
     */
382 44
    public function request($uri = '', $method = 'GET', array $options = [])
383
    {
384 44
        $this->response = null;
385
386 44
        $method = strtoupper($method);
387 44
        $options = $this->getMergedOptions($this->options, $options);
388
389
        try {
390 44
            $this->response = $this->client->request($method, $uri, $options);
391 24
        } catch (Exception $e) {
392 4
            if (! $this->areExceptionsCaught()) {
393 4
                throw $e;
394
            }
395
        }
396
397 44
        return $this;
398
    }
399
400
    /**
401
     * Make request to a URI, expecting JSON content.
402
     *
403
     * @param  string|\Psr\Http\Message\UriInterface  $uri
404
     * @param  string  $method
405
     * @param  array  $options
406
     * @return $this
407
     */
408 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
409
    {
410 8
        Arr::set($options, 'headers.Accept', 'application/json');
411
412 8
        return $this->request($uri, $method, $options);
413
    }
414
415
    /**
416
     * Make asynchronous request to a URI.
417
     *
418
     * @param  string|\Psr\Http\Message\UriInterface  $uri
419
     * @param  string  $method
420
     * @param  array  $options
421
     * @return \GuzzleHttp\Promise\PromiseInterface
422
     */
423 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
424
    {
425 8
        return $this->client->requestAsync(
426 8
            strtoupper($method),
427 8
            $uri,
428 8
            $this->getMergedOptions($this->options, $options)
429 4
        );
430
    }
431
432
    /**
433
     * Request the URI and return the response content.
434
     *
435
     * @param  string|\Psr\Http\Message\UriInterface  $uri
436
     * @param  string  $method
437
     * @param  array  $options
438
     * @return string
439
     */
440 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
441
    {
442 4
        return $this->request($uri, $method, $options)->getContent();
443
    }
444
445
    /**
446
     * Request the URI and return the JSON-decoded response content.
447
     *
448
     * @param  string|\Psr\Http\Message\UriInterface  $uri
449
     * @param  string  $method
450
     * @param  array  $options
451
     * @return mixed
452
     */
453 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
454
    {
455 4
        return $this->requestJson($uri, $method, $options)->getJson();
456
    }
457
458
    /**
459
     * Get all allowed magic request methods.
460
     *
461
     * @return array
462
     */
463 36
    protected function getMagicRequestMethods()
464
    {
465
        return [
466 36
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
467 18
        ];
468
    }
469
470
    /**
471
     * Determine if the given method is a magic request method.
472
     *
473
     * @param  string  $method
474
     * @param  string  &$requestMethod
475
     * @param  string  &$httpMethod
476
     * @return bool
477
     */
478 36
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
479
    {
480 36
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
481 4
            $httpMethod = substr($method, 0, $pos);
482 4
            $requestMethod = 'requestAsync';
483 2
        } else {
484 36
            $httpMethod = $method;
485 36
            $requestMethod = 'request';
486
        }
487
488 36
        if (in_array($httpMethod, $this->getMagicRequestMethods())) {
489 8
            return true;
490
        }
491
492 28
        $httpMethod = $requestMethod = null;
493
494 28
        return false;
495
    }
496
497
    /**
498
     * Get parameters for $this->request() from the magic request call.
499
     *
500
     * @param  string  $method
501
     * @param  array  $parameters
502
     * @return array
503
     */
504 8
    protected function getRequestParameters($method, array $parameters)
505
    {
506 8
        if (empty($parameters)) {
507 4
            $parameters = ['', $method];
508 2
        } else {
509 8
            array_splice($parameters, 1, 0, $method);
510
        }
511
512 8
        return $parameters;
513
    }
514
515
    /**
516
     * Get all allowed magic response methods.
517
     *
518
     * @return array
519
     */
520 28
    protected function getMagicResponseMethods()
521
    {
522
        return [
523 28
            'getStatusCode', 'getReasonPhrase', 'getProtocolVersion',
524 14
            'getHeaders', 'hasHeader', 'getHeader', 'getHeaderLine', 'getBody',
525 14
        ];
526
    }
527
528
    /**
529
     * Determine if the given method is a magic response method.
530
     *
531
     * @param  string  $method
532
     * @return bool
533
     */
534 28
    protected function isMagicResponseMethod($method)
535
    {
536 28
        return in_array($method, $this->getMagicResponseMethods());
537
    }
538
539
    /**
540
     * Get all allowed magic option methods.
541
     *
542
     * @return array
543
     */
544 8
    protected function getMagicOptionMethods()
545
    {
546 8
        static $optionMethods = null;
547
548 8
        if (is_null($optionMethods)) {
549 4
            $reflector = new ReflectionClass(RequestOptions::class);
550 4
            $optionMethods = array_map(
551 4
                [Str::class, 'camel'],
552 4
                array_values($reflector->getConstants())
553 2
            );
554 2
        }
555
556 8
        return $optionMethods;
557
    }
558
559
    /**
560
     * Determine if the given method is a magic option method.
561
     *
562
     * @param  string  $method
563
     * @return bool
564
     */
565 8
    protected function isMagicOptionMethod($method, &$option)
566
    {
567 8
        $option = in_array($method, $this->getMagicOptionMethods())
568 8
            ? Str::snake($method) : null;
569
570 8
        return (bool) $option;
571
    }
572
573
    /**
574
     * Handle magic method to send request, get response data, or set
575
     * request options.
576
     *
577
     * @param  string  $method
578
     * @param  array  $parameters
579
     * @return mixed
580
     *
581
     * @throws \InvalidArgumentException
582
     * @throws \BadMethodCallException
583
     */
584 36
    public function __call($method, $parameters)
585
    {
586 36
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
587 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
588
        }
589
590 28
        if ($this->isMagicResponseMethod($method)) {
591 20
            return $this->getResponseData($method, $parameters);
592
        }
593
594 8
        if ($this->isMagicOptionMethod($method, $option)) {
595 4
            if (empty($parameters)) {
596 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
597
            }
598
599 4
            return $this->option($option, $parameters[0]);
600
        }
601
602 4
        throw new BadMethodCallException("Method [$method] does not exist.");
603
    }
604
}
605