Completed
Push — master ( 500e34...ae7810 )
by Elf
16:06 queued 14:33
created

HttpClient::removeBodyOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A HttpClient::header() 0 3 1
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(string|resource|\Psr\Http\Message\StreamInterface $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(string|bool $value)
47
 * @method $this delay(int|float $value)
48
 * @method $this expect(bool|int $value)
49
 * @method $this forceIpResolve(string $value)
50
 * @method $this formParams(array $value)
51
 * @method $this headers(array $value)
52
 * @method $this httpErrors(bool $value)
53
 * @method $this json(mixed $value)
54
 * @method $this multipart(array $value)
55
 * @method $this onHeaders(callable $value)
56
 * @method $this onStats(callable $value)
57
 * @method $this progress(callable $value)
58
 * @method $this proxy(string|array $value)
59
 * @method $this query(array|string $value)
60
 * @method $this readTimeout(float $value)
61
 * @method $this sink(string|resource|\Psr\Http\Message\StreamInterface $value)
62
 * @method $this sslKey(string|array $value)
63
 * @method $this stream(bool $value)
64
 * @method $this verify(bool|string $value)
65
 * @method $this timeout(float $value)
66
 * @method $this version(float|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 128
    public static function defaultOptions()
111
    {
112 128
        return static::$defaultOptions;
113
    }
114
115
    /**
116
     * Set the default request options.
117
     *
118
     * @param  array  $options
119
     * @return void
120
     */
121 128
    public static function setDefaultOptions(array $options)
122
    {
123 128
        static::$defaultOptions = $options;
124 128
    }
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 132
    public function __construct($options = [])
145
    {
146 132
        if (is_string($options) || $options instanceof UriInterface) {
147 8
            $options = ['base_uri' => $options];
148 130
        } elseif (! is_array($options)) {
149 4
            throw new InvalidArgumentException('Options must be a string, UriInterface, or an array');
150
        }
151
152 128
        $this->client = new Client(
153 128
            array_replace_recursive(static::defaultOptions(), $options)
154 64
        );
155
156 128
        $this->options = $this->client->getConfig();
157 128
    }
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 64
    public function getOption($key = null, $default = null)
177
    {
178 64
        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 48
    public function option($key, $value = null)
189
    {
190 48
        $keys = is_array($key) ? $key : [$key => $value];
191
192 48
        foreach ($keys as $key => $value) {
193 48
            Arr::set($this->options, $key, $value);
194 24
        }
195
196 48
        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 = array_replace_recursive($this->options, $options);
208
209 4
        return $this;
210
    }
211
212
    /**
213
     * Remove one or many request options using "dot" notation.
214
     *
215
     * @param  array|string  $keys
216
     * @return $this
217
     */
218 60
    public function removeOption($keys)
219
    {
220 60
        Arr::forget($this->options, is_array($keys) ? $keys : func_get_args());
221
222 60
        return $this;
223
    }
224
225
    /**
226
     * Set a request header.
227
     *
228
     * @param  string  $name
229
     * @param  mixed  $value
230
     * @return $this
231
     */
232 20
    public function header($name, $value)
233
    {
234 20
        return $this->option('headers.'.$name, $value);
235
    }
236
237
    /**
238
     * Remove one or many request headers.
239
     *
240
     * @param  array|string  $names
241
     * @return $this
242
     */
243 4
    public function removeHeader($names)
244
    {
245 4
        if (is_array($headers = $this->getOption('headers'))) {
246 4
            $names = is_array($names) ? $names : func_get_args();
247 4
            $this->option('headers', Arr::except($headers, $names));
248 2
        }
249
250 4
        return $this;
251
    }
252
253
    /**
254
     * Set the request accept type.
255
     *
256
     * @param  string  $type
257
     * @return $this
258
     */
259 8
    public function accept($type)
260
    {
261 8
        return $this->header('Accept', $type);
262
    }
263
264
    /**
265
     * Set the request accept type to "application/json".
266
     *
267
     * @return $this
268
     */
269 4
    public function acceptJson()
270
    {
271 4
        return $this->accept('application/json');
272
    }
273
274
    /**
275
     * Set user agent for the request.
276
     *
277
     * @param  string  $value
278
     * @return $this
279
     */
280 4
    public function userAgent($value)
281
    {
282 4
        return $this->header('User-Agent', $value);
283
    }
284
285
    /**
286
     * Set the request content type.
287
     *
288
     * @param  string  $type
289
     * @return $this
290
     */
291 4
    public function contentType($type)
292
    {
293 4
        return $this->header('Content-Type', $type);
294
    }
295
296
    /**
297
     * Specify where the body of the response will be saved.
298
     * Set the "sink" option.
299
     *
300
     * @param  string|resource|\Psr\Http\Message\StreamInterface  $dest
301
     * @return $this
302
     */
303 4
    public function saveTo($dest)
304
    {
305 4
        return $this->removeOption('save_to')->option('sink', $dest);
306
    }
307
308
    /**
309
     * Determine whether to catch Guzzle exceptions.
310
     *
311
     * @return bool
312
     */
313 8
    public function areExceptionsCaught()
314
    {
315 8
        return $this->getOption('catch_exceptions', false);
316
    }
317
318
    /**
319
     * Set whether to catch Guzzle exceptions or not.
320
     *
321
     * @param  bool  $catch
322
     * @return $this
323
     */
324 8
    public function catchExceptions($catch)
325
    {
326 8
        return $this->option('catch_exceptions', (bool) $catch);
327
    }
328
329
    /**
330
     * Get the Guzzle response instance.
331
     *
332
     * @return \GuzzleHttp\Psr7\Response|null
333
     */
334 20
    public function getResponse()
335
    {
336 20
        return $this->response;
337
    }
338
339
    /**
340
     * Get data from the response.
341
     *
342
     * @param  string|\Closure  $callback
343
     * @param  mixed  $parameters
344
     * @param  mixed  $default
345
     * @return mixed
346
     */
347 24
    public function getResponseData($callback, $parameters = [], $default = null)
348
    {
349 24
        if ($this->response) {
350 12
            return $callback instanceof Closure
351 14
                ? $callback($this->response, ...(array) $parameters)
352 24
                : $this->response->$callback(...(array) $parameters);
353
        }
354
355 4
        return $default;
356
    }
357
358
    /**
359
     * Get the response content.
360
     *
361
     * @return string
362
     */
363 16
    public function getContent()
364
    {
365 16
        return (string) $this->getBody();
366
    }
367
368
    /**
369
     * Get the JSON-decoded response content.
370
     *
371
     * @param  bool  $assoc
372
     * @return mixed
373
     */
374 8
    public function getJson($assoc = true)
375
    {
376 8
        return json_decode($this->getContent(), $assoc);
377
    }
378
379
    /**
380
     * Send request to a URI.
381
     *
382
     * @param  string|\Psr\Http\Message\UriInterface  $uri
383
     * @param  string  $method
384
     * @param  array  $options
385
     * @return $this
386
     */
387 48
    public function request($uri = '', $method = 'GET', array $options = [])
388
    {
389 48
        $this->response = null;
390
391
        try {
392 48
            $this->response = $this->client->request(
393 48
                strtoupper($method), $uri, $this->getRequestOptions($options)
394 24
            );
395 26
        } catch (Exception $e) {
396 4
            if (! $this->areExceptionsCaught()) {
397 4
                throw $e;
398
            }
399
        }
400
401 48
        return $this;
402
    }
403
404
    /**
405
     * Get options for the Guzzle request method.
406
     *
407
     * @param  array  $options
408
     * @return array
409
     */
410 52
    protected function getRequestOptions(array $options = [])
411
    {
412 52
        $options = array_replace_recursive($this->options, $options);
413
414 52
        $this->removeOption([
415 52
            'body', 'form_params', 'multipart', 'json', 'query',
416 26
            'sink', 'save_to', 'stream',
417 26
            'on_headers', 'on_stats', 'progress',
418 26
            'headers.Content-Type',
419 26
        ]);
420
421 52
        return $options;
422
    }
423
424
    /**
425
     * Send request to a URI, expecting JSON content.
426
     *
427
     * @param  string|\Psr\Http\Message\UriInterface  $uri
428
     * @param  string  $method
429
     * @param  array  $options
430
     * @return $this
431
     */
432 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
433
    {
434 8
        Arr::set($options, 'headers.Accept', 'application/json');
435
436 8
        return $this->request($uri, $method, $options);
437
    }
438
439
    /**
440
     * Send asynchronous request to a URI.
441
     *
442
     * @param  string|\Psr\Http\Message\UriInterface  $uri
443
     * @param  string  $method
444
     * @param  array  $options
445
     * @return \GuzzleHttp\Promise\PromiseInterface
446
     */
447 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
448
    {
449 8
        return $this->client->requestAsync(
450 8
            strtoupper($method), $uri, $this->getRequestOptions($options)
451 4
        );
452
    }
453
454
    /**
455
     * Request the URI and return the response content.
456
     *
457
     * @param  string|\Psr\Http\Message\UriInterface  $uri
458
     * @param  string  $method
459
     * @param  array  $options
460
     * @return string
461
     */
462 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
463
    {
464 4
        return $this->request($uri, $method, $options)->getContent();
465
    }
466
467
    /**
468
     * Request the URI and return the JSON-decoded response content.
469
     *
470
     * @param  string|\Psr\Http\Message\UriInterface  $uri
471
     * @param  string  $method
472
     * @param  array  $options
473
     * @return mixed
474
     */
475 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
476
    {
477 4
        return $this->requestJson($uri, $method, $options)->getJson();
478
    }
479
480
    /**
481
     * Get all allowed magic request methods.
482
     *
483
     * @return array
484
     */
485 36
    protected function getMagicRequestMethods()
486
    {
487
        return [
488 36
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
489 18
        ];
490
    }
491
492
    /**
493
     * Determine if the given method is a magic request method.
494
     *
495
     * @param  string  $method
496
     * @param  string  &$requestMethod
497
     * @param  string  &$httpMethod
498
     * @return bool
499
     */
500 36
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
501
    {
502 36
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
503 4
            $httpMethod = substr($method, 0, $pos);
504 4
            $requestMethod = 'requestAsync';
505 2
        } else {
506 36
            $httpMethod = $method;
507 36
            $requestMethod = 'request';
508
        }
509
510 36
        if (! in_array($httpMethod, $this->getMagicRequestMethods())) {
511 28
            $httpMethod = $requestMethod = null;
512 14
        }
513
514 36
        return (bool) $httpMethod;
515
    }
516
517
    /**
518
     * Get parameters for the request() method 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