Completed
Push — master ( 0139dd...82a3db )
by Elf
14:18 queued 03:03
created

HttpClient::fetchContent()   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 44
    public function option($key, $value = null)
189
    {
190 44
        $keys = is_array($key) ? $key : [$key => $value];
191
192 44
        foreach ($keys as $key => $value) {
193 44
            Arr::set($this->options, $key, $value);
194 22
        }
195
196 44
        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 24
    public function header($name, $value)
265
    {
266 24
        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 12
    public function accept($type)
276
    {
277 12
        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
        $options = $this->addAcceptableJsonType(
411 8
            $this->getMergedOptions($this->options, $options)
412 4
        );
413
414 8
        return $this->request($uri, $method, $options);
415
    }
416
417
    /**
418
     * Add JSON type to the "Accept" header for the request options.
419
     *
420
     * @param  array  $options
421
     * @return array
422
     */
423 8
    protected function addAcceptableJsonType(array $options)
424
    {
425 8
        $accept = Arr::get($options, 'headers.Accept', '');
426
427 8
        if (! Str::contains($accept, ['/json', '+json'])) {
0 ignored issues
show
Bug introduced by
It seems like $accept can also be of type array; however, parameter $haystack of Illuminate\Support\Str::contains() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

427
        if (! Str::contains(/** @scrutinizer ignore-type */ $accept, ['/json', '+json'])) {
Loading history...
428 8
            $accept = rtrim('application/json,'.$accept, ',');
0 ignored issues
show
Bug introduced by
Are you sure $accept of type mixed|string|array can be used in concatenation? ( Ignorable by Annotation )

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

428
            $accept = rtrim('application/json,'./** @scrutinizer ignore-type */ $accept, ',');
Loading history...
429 8
            Arr::set($options, 'headers.Accept', $accept);
430 4
        }
431
432 8
        return $options;
433
    }
434
435
    /**
436
     * Make asynchronous request to a URI.
437
     *
438
     * @param  string|\Psr\Http\Message\UriInterface  $uri
439
     * @param  string  $method
440
     * @param  array  $options
441
     * @return \GuzzleHttp\Promise\PromiseInterface
442
     */
443 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
444
    {
445 8
        return $this->client->requestAsync(
446 8
            strtoupper($method),
447 8
            $uri,
448 8
            $this->getMergedOptions($this->options, $options)
449 4
        );
450
    }
451
452
    /**
453
     * Request the URI and return the response content.
454
     *
455
     * @param  string|\Psr\Http\Message\UriInterface  $uri
456
     * @param  string  $method
457
     * @param  array  $options
458
     * @return string
459
     */
460 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
461
    {
462 4
        return $this->request($uri, $method, $options)->getContent();
463
    }
464
465
    /**
466
     * Request the URI and return the JSON-decoded response content.
467
     *
468
     * @param  string|\Psr\Http\Message\UriInterface  $uri
469
     * @param  string  $method
470
     * @param  array  $options
471
     * @return mixed
472
     */
473 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
474
    {
475 4
        return $this->requestJson($uri, $method, $options)->getJson();
476
    }
477
478
    /**
479
     * Get all allowed magic request methods.
480
     *
481
     * @return array
482
     */
483 36
    protected function getMagicRequestMethods()
484
    {
485
        return [
486 36
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
487 18
        ];
488
    }
489
490
    /**
491
     * Determine if the given method is a magic request method.
492
     *
493
     * @param  string  $method
494
     * @param  string  &$requestMethod
495
     * @param  string  &$httpMethod
496
     * @return bool
497
     */
498 36
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
499
    {
500 36
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
501 4
            $httpMethod = substr($method, 0, $pos);
502 4
            $requestMethod = 'requestAsync';
503 2
        } else {
504 36
            $httpMethod = $method;
505 36
            $requestMethod = 'request';
506
        }
507
508 36
        if (in_array($httpMethod, $this->getMagicRequestMethods())) {
509 8
            return true;
510
        }
511
512 28
        $httpMethod = $requestMethod = null;
513
514 28
        return false;
515
    }
516
517
    /**
518
     * Get parameters for $this->request() from the magic request call.
519
     *
520
     * @param  string  $method
521
     * @param  array  $parameters
522
     * @return array
523
     */
524 8
    protected function getRequestParameters($method, array $parameters)
525
    {
526 8
        if (empty($parameters)) {
527 4
            $parameters = ['', $method];
528 2
        } else {
529 8
            array_splice($parameters, 1, 0, $method);
530
        }
531
532 8
        return $parameters;
533
    }
534
535
    /**
536
     * Get all allowed magic response methods.
537
     *
538
     * @return array
539
     */
540 28
    protected function getMagicResponseMethods()
541
    {
542
        return [
543 28
            'getStatusCode', 'getReasonPhrase', 'getProtocolVersion',
544 14
            'getHeaders', 'hasHeader', 'getHeader', 'getHeaderLine', 'getBody',
545 14
        ];
546
    }
547
548
    /**
549
     * Determine if the given method is a magic response method.
550
     *
551
     * @param  string  $method
552
     * @return bool
553
     */
554 28
    protected function isMagicResponseMethod($method)
555
    {
556 28
        return in_array($method, $this->getMagicResponseMethods());
557
    }
558
559
    /**
560
     * Get all allowed magic option methods.
561
     *
562
     * @return array
563
     */
564 8
    protected function getMagicOptionMethods()
565
    {
566 8
        static $optionMethods = null;
567
568 8
        if (is_null($optionMethods)) {
569 4
            $reflector = new ReflectionClass(RequestOptions::class);
570 4
            $optionMethods = array_map(
571 4
                [Str::class, 'camel'],
572 4
                array_values($reflector->getConstants())
573 2
            );
574 2
        }
575
576 8
        return $optionMethods;
577
    }
578
579
    /**
580
     * Determine if the given method is a magic option method.
581
     *
582
     * @param  string  $method
583
     * @return bool
584
     */
585 8
    protected function isMagicOptionMethod($method, &$option)
586
    {
587 8
        $option = in_array($method, $this->getMagicOptionMethods())
588 8
            ? Str::snake($method) : null;
589
590 8
        return (bool) $option;
591
    }
592
593
    /**
594
     * Handle magic method to send request, get response data, or set
595
     * request options.
596
     *
597
     * @param  string  $method
598
     * @param  array  $parameters
599
     * @return mixed
600
     *
601
     * @throws \InvalidArgumentException
602
     * @throws \BadMethodCallException
603
     */
604 36
    public function __call($method, $parameters)
605
    {
606 36
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
607 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
608
        }
609
610 28
        if ($this->isMagicResponseMethod($method)) {
611 20
            return $this->getResponseData($method, $parameters);
612
        }
613
614 8
        if ($this->isMagicOptionMethod($method, $option)) {
615 4
            if (empty($parameters)) {
616 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
617
            }
618
619 4
            return $this->option($option, $parameters[0]);
620
        }
621
622 4
        throw new BadMethodCallException("Method [$method] does not exist.");
623
    }
624
}
625