Completed
Push — master ( 84e9e0...fe9d5b )
by Elf
01:52
created

HttpClient::setDefaultOptions()   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 1
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 Exception;
6
use ReflectionClass;
7
use GuzzleHttp\Client;
8
use BadMethodCallException;
9
use Illuminate\Support\Arr;
10
use Illuminate\Support\Str;
11
use InvalidArgumentException;
12
use GuzzleHttp\RequestOptions;
13
use Psr\Http\Message\UriInterface;
14
15
/**
16
 * @method \Psr\Http\Message\ResponseInterface|null get(string|UriInterface $uri = '', array $options = [])
17
 * @method \Psr\Http\Message\ResponseInterface|null head(string|UriInterface $uri = '', array $options = [])
18
 * @method \Psr\Http\Message\ResponseInterface|null post(string|UriInterface $uri = '', array $options = [])
19
 * @method \Psr\Http\Message\ResponseInterface|null put(string|UriInterface $uri = '', array $options = [])
20
 * @method \Psr\Http\Message\ResponseInterface|null patch(string|UriInterface $uri = '', array $options = [])
21
 * @method \Psr\Http\Message\ResponseInterface|null delete(string|UriInterface $uri = '', array $options = [])
22
 * @method \Psr\Http\Message\ResponseInterface|null options(string|UriInterface $uri = '', array $options = [])
23
 * @method \GuzzleHttp\Promise\PromiseInterface getAsync(string|UriInterface $uri = '', array $options = [])
24
 * @method \GuzzleHttp\Promise\PromiseInterface headAsync(string|UriInterface $uri = '', array $options = [])
25
 * @method \GuzzleHttp\Promise\PromiseInterface postAsync(string|UriInterface $uri = '', array $options = [])
26
 * @method \GuzzleHttp\Promise\PromiseInterface putAsync(string|UriInterface $uri = '', array $options = [])
27
 * @method \GuzzleHttp\Promise\PromiseInterface patchAsync(string|UriInterface $uri = '', array $options = [])
28
 * @method \GuzzleHttp\Promise\PromiseInterface deleteAsync(string|UriInterface $uri = '', array $options = [])
29
 * @method \GuzzleHttp\Promise\PromiseInterface optionsAsync(string|UriInterface $uri = '', array $options = [])
30
 * @method $this allowRedirects(bool|array $value)
31
 * @method $this auth(array|string|null $value)
32
 * @method $this body(string|resource|\Psr\Http\Message\StreamInterface $value)
33
 * @method $this cert(string|array $value)
34
 * @method $this cookies(bool|\GuzzleHttp\Cookie\CookieJarInterface $value)
35
 * @method $this connectTimeout(float $value)
36
 * @method $this debug(bool|resource $value)
37
 * @method $this decodeContent(string|bool $value)
38
 * @method $this delay(int|float $value)
39
 * @method $this expect(bool|int $value)
40
 * @method $this forceIpResolve(string $value)
41
 * @method $this formParams(array $value)
42
 * @method $this headers(array $value)
43
 * @method $this httpErrors(bool $value)
44
 * @method $this json(mixed $value)
45
 * @method $this onHeaders(callable $value)
46
 * @method $this onStats(callable $value)
47
 * @method $this progress(callable $value)
48
 * @method $this proxy(string|array $value)
49
 * @method $this query(array|string $value)
50
 * @method $this readTimeout(float $value)
51
 * @method $this sink(string|resource|\Psr\Http\Message\StreamInterface $value)
52
 * @method $this sslKey(string|array $value)
53
 * @method $this stream(bool $value)
54
 * @method $this verify(bool|string $value)
55
 * @method $this timeout(float $value)
56
 * @method $this version(float|string $value)
57
 *
58
 * @see http://docs.guzzlephp.org/en/stable/request-options.html Request Options
59
 */
60
class HttpClient
61
{
62
    /**
63
     * The default request options.
64
     *
65
     * @var array
66
     */
67
    protected static $defaultOptions = [
68
        'catch_exceptions' => true,
69
        'http_errors' => false,
70
        'connect_timeout' => 5,
71
        'timeout' => 20,
72
    ];
73
74
    /**
75
     * The Guzzle client.
76
     *
77
     * @var \GuzzleHttp\Client
78
     */
79
    protected $client;
80
81
    /**
82
     * The request options.
83
     *
84
     * @var array
85
     */
86
    protected $options = [];
87
88
    /**
89
     * Get the default request options.
90
     *
91
     * @return array
92
     */
93 108
    public static function defaultOptions()
94
    {
95 108
        return static::$defaultOptions;
96
    }
97
98
    /**
99
     * Set the default request options.
100
     *
101
     * @param  array  $options
102
     * @return void
103
     */
104 112
    public static function setDefaultOptions(array $options)
105
    {
106 112
        static::$defaultOptions = $options;
107 112
    }
108
109
    /**
110
     * Create a new HTTP client instance.
111
     *
112
     * @param  array|string|\Psr\Http\Message\UriInterface  $options  base URI or any request options
113
     * @return static
114
     */
115 8
    public static function create($options = [])
116
    {
117 8
        return new static($options);
118
    }
119
120
    /**
121
     * Create a new HTTP client instance.
122
     *
123
     * @param  array|string|\Psr\Http\Message\UriInterface  $options  base URI or any request options
124
     *
125
     * @throws \InvalidArgumentException
126
     */
127 112
    public function __construct($options = [])
128
    {
129 112
        if (is_string($options) || $options instanceof UriInterface) {
130 6
            $options = ['base_uri' => $options];
131 110
        } elseif (! is_array($options)) {
132 4
            throw new InvalidArgumentException('Options must be a string, UriInterface, or an array');
133
        }
134
135 108
        $this->client = new Client(
136 108
            array_replace_recursive(static::defaultOptions(), $options)
137 54
        );
138
139 108
        $this->options = $this->client->getConfig();
140 108
    }
141
142
    /**
143
     * Get the Guzzle client instance.
144
     *
145
     * @return \GuzzleHttp\Client
146
     */
147 20
    public function getClient()
148
    {
149 20
        return $this->client;
150
    }
151
152
    /**
153
     * Get the request options using "dot" notation.
154
     *
155
     * @param  string|null  $key
156
     * @param  mixed  $default
157
     * @return mixed
158
     */
159 76
    public function getOption($key = null, $default = null)
160
    {
161 76
        return Arr::get($this->options, $key, $default);
162
    }
163
164
    /**
165
     * Set the request options using "dot" notation.
166
     *
167
     * @param  string|array  $key
168
     * @param  mixed  $value
169
     * @return $this
170
     */
171 60
    public function option($key, $value = null)
172
    {
173 60
        $keys = is_array($key) ? $key : [$key => $value];
174
175 60
        foreach ($keys as $key => $value) {
176 60
            Arr::set($this->options, $key, $value);
177 30
        }
178
179 60
        return $this;
180
    }
181
182
    /**
183
     * Merge the given options to the request options.
184
     *
185
     * @param  array  $options
186
     * @return $this
187
     */
188 4
    public function mergeOptions(array $options)
189
    {
190 4
        $this->options = array_replace_recursive($this->options, $options);
191
192 4
        return $this;
193
    }
194
195
    /**
196
     * Remove one or many request options using "dot" notation.
197
     *
198
     * @param  array|string  $keys
199
     * @return $this
200
     */
201 36
    public function removeOption($keys)
202
    {
203 36
        Arr::forget($this->options, is_array($keys) ? $keys : func_get_args());
204
205 36
        return $this;
206
    }
207
208
    /**
209
     * Set a request header.
210
     *
211
     * @param  string  $name
212
     * @param  mixed  $value
213
     * @return $this
214
     */
215 20
    public function header($name, $value)
216
    {
217 20
        return $this->option('headers.'.$name, $value);
218
    }
219
220
    /**
221
     * Remove one or many request headers.
222
     *
223
     * @param  array|string  $names
224
     * @return $this
225
     */
226 4
    public function removeHeader($names)
227
    {
228 4
        if (is_array($headers = $this->getOption('headers'))) {
229 4
            $names = is_array($names) ? $names : func_get_args();
230
231 4
            $this->option('headers', Arr::except($headers, $names));
232 2
        }
233
234 4
        return $this;
235
    }
236
237
    /**
238
     * Set the request accept type.
239
     *
240
     * @param  string  $type
241
     * @return $this
242
     */
243 8
    public function accept($type)
244
    {
245 8
        return $this->header('Accept', $type);
246
    }
247
248
    /**
249
     * Set the request accept type to "application/json".
250
     *
251
     * @return $this
252
     */
253 4
    public function acceptJson()
254
    {
255 4
        return $this->accept('application/json');
256
    }
257
258
    /**
259
     * Set user agent for the request.
260
     *
261
     * @param  string  $value
262
     * @return $this
263
     */
264 4
    public function userAgent($value)
265
    {
266 4
        return $this->header('User-Agent', $value);
267
    }
268
269
    /**
270
     * Set the request content type.
271
     *
272
     * @param  string  $type
273
     * @return $this
274
     */
275 4
    public function contentType($type)
276
    {
277 4
        return $this->header('Content-Type', $type);
278
    }
279
280
    /**
281
     * Specify where the body of the response will be saved.
282
     * Set the "sink" option.
283
     *
284
     * @param  string|resource|\Psr\Http\Message\StreamInterface  $dest
285
     * @return $this
286
     */
287 4
    public function saveTo($dest)
288
    {
289 4
        return $this->option('sink', $dest);
290
    }
291
292
    /**
293
     * Set the body of the request to a multipart/form-data form.
294
     *
295
     * @param  array  $data
296
     * @return $this
297
     */
298 4
    public function multipart(array $data)
299
    {
300 4
        $multipart = [];
301
302 4
        foreach ($data as $key => $value) {
303 4
            if (! is_array($value)) {
304 4
                $value = ['contents' => $value];
305 2
            }
306
307 4
            if (! is_int($key)) {
308 4
                $value['name'] = $key;
309 2
            }
310
311 4
            $multipart[] = $value;
312 2
        }
313
314 4
        return $this->option('multipart', $multipart);
315
    }
316
317
    /**
318
     * Determine whether to catch Guzzle exceptions.
319
     *
320
     * @return bool
321
     */
322 16
    public function areExceptionsCaught()
323
    {
324 16
        return $this->getOption('catch_exceptions', false);
325
    }
326
327
    /**
328
     * Set whether to catch Guzzle exceptions or not.
329
     *
330
     * @param  bool  $catch
331
     * @return $this
332
     */
333 16
    public function catchExceptions($catch)
334
    {
335 16
        return $this->option('catch_exceptions', (bool) $catch);
336
    }
337
338
    /**
339
     * Send request to a URI.
340
     *
341
     * @param  string|\Psr\Http\Message\UriInterface  $uri
342
     * @param  string  $method
343
     * @param  array  $options
344
     * @return \Psr\Http\Message\ResponseInterface|null
345
     */
346 28
    public function request($uri = '', $method = 'GET', array $options = [])
347
    {
348
        try {
349 28
            return $this->client->request(
350 28
                $method, $uri, $this->getRequestOptions($options)
351 14
            );
352 12
        } catch (Exception $e) {
353 12
            if (! $this->areExceptionsCaught()) {
354 12
                throw $e;
355
            }
356
        }
357 12
    }
358
359
    /**
360
     * Send request to a URI, expecting JSON content.
361
     *
362
     * @param  string|\Psr\Http\Message\UriInterface  $uri
363
     * @param  string  $method
364
     * @param  array  $options
365
     * @return \Psr\Http\Message\ResponseInterface|null
366
     */
367 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
368
    {
369 8
        Arr::set($options, 'headers.Accept', 'application/json');
370
371 8
        return $this->request($uri, $method, $options);
372
    }
373
374
    /**
375
     * Send asynchronous request to a URI.
376
     *
377
     * @param  string|\Psr\Http\Message\UriInterface  $uri
378
     * @param  string  $method
379
     * @param  array  $options
380
     * @return \GuzzleHttp\Promise\PromiseInterface
381
     */
382 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
383
    {
384 8
        return $this->client->requestAsync(
385 8
            $method, $uri, $this->getRequestOptions($options)
386 4
        );
387
    }
388
389
    /**
390
     * Get options for the Guzzle request method.
391
     *
392
     * @param  array  $options
393
     * @return array
394
     */
395 32
    protected function getRequestOptions(array $options = [])
396
    {
397 32
        $options = array_replace_recursive($this->options, $options);
398
399 32
        $this->removeOption([
400 32
            'body', 'form_params', 'multipart', 'json', 'query',
401 16
            'sink', 'save_to', 'stream',
402 16
            'on_headers', 'on_stats', 'progress',
403 16
            'headers.Content-Type',
404 16
        ]);
405
406 32
        return $options;
407
    }
408
409
    /**
410
     * Request the URI and return the response content.
411
     *
412
     * @param  string|\Psr\Http\Message\UriInterface  $uri
413
     * @param  string  $method
414
     * @param  array  $options
415
     * @return string|null
416
     */
417 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
418
    {
419 4
        if ($response = $this->request($uri, $method, $options)) {
420 4
            return (string) $response->getBody();
421
        }
422 4
    }
423
424
    /**
425
     * Request the URI and return the JSON-decoded response content.
426
     *
427
     * @param  string|\Psr\Http\Message\UriInterface  $uri
428
     * @param  string  $method
429
     * @param  array  $options
430
     * @return mixed|null
431
     */
432 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
433
    {
434 4
        if ($response = $this->requestJson($uri, $method, $options)) {
435 4
            return json_decode($response->getBody(), true);
436
        }
437 4
    }
438
439
    /**
440
     * Get all allowed magic request methods.
441
     *
442
     * @return array
443
     */
444 16
    protected function getMagicRequestMethods()
445
    {
446
        return [
447 16
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
448 8
        ];
449
    }
450
451
    /**
452
     * Determine if the given method is a magic request method.
453
     *
454
     * @param  string  $method
455
     * @param  string  &$requestMethod
456
     * @param  string  &$httpMethod
457
     * @return bool
458
     */
459 16
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
460
    {
461 16
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
462 4
            $httpMethod = substr($method, 0, $pos);
463 4
            $requestMethod = 'requestAsync';
464 2
        } else {
465 16
            $httpMethod = $method;
466 16
            $requestMethod = 'request';
467
        }
468
469 16
        if (! in_array($httpMethod, $this->getMagicRequestMethods())) {
470 8
            $httpMethod = $requestMethod = null;
471 4
        }
472
473 16
        return (bool) $httpMethod;
474
    }
475
476
    /**
477
     * Get parameters for the request() method from the magic request call.
478
     *
479
     * @param  string  $method
480
     * @param  array  $parameters
481
     * @return array
482
     */
483 8
    protected function getRequestParameters($method, array $parameters)
484
    {
485 8
        if (empty($parameters)) {
486 4
            $parameters = ['', $method];
487 2
        } else {
488 8
            array_splice($parameters, 1, 0, $method);
489
        }
490
491 8
        return $parameters;
492
    }
493
494
    /**
495
     * Get all allowed magic option methods.
496
     *
497
     * @return array
498
     */
499 8
    protected function getMagicOptionMethods()
500
    {
501 8
        static $optionMethods = null;
502
503 8
        if (is_null($optionMethods)) {
504 4
            $reflector = new ReflectionClass(RequestOptions::class);
505 4
            $optionMethods = array_map(
506 4
                [Str::class, 'camel'],
507 4
                array_values($reflector->getConstants())
508 2
            );
509 2
        }
510
511 8
        return $optionMethods;
512
    }
513
514
    /**
515
     * Determine if the given method is a magic option method.
516
     *
517
     * @param  string  $method
518
     * @return bool
519
     */
520 8
    protected function isMagicOptionMethod($method, &$option)
521
    {
522 8
        $option = in_array($method, $this->getMagicOptionMethods())
523 8
            ? Str::snake($method) : null;
524
525 8
        return (bool) $option;
526
    }
527
528
    /**
529
     * Handle magic option/request methods.
530
     *
531
     * @param  string  $method
532
     * @param  array  $parameters
533
     * @return mixed
534
     *
535
     * @throws \InvalidArgumentException
536
     * @throws \BadMethodCallException
537
     */
538 16
    public function __call($method, $parameters)
539
    {
540 16
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
541 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
542
        }
543
544 8
        if ($this->isMagicOptionMethod($method, $option)) {
545 4
            if (empty($parameters)) {
546 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
547
            }
548
549 4
            return $this->option($option, $parameters[0]);
550
        }
551
552 4
        throw new BadMethodCallException("Method [$method] does not exist.");
553
    }
554
}
555