Passed
Push — master ( ea4788...9637e0 )
by Elf
02:12
created

HttpClient::isMagicRequestMethod()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 3
dl 0
loc 15
ccs 11
cts 11
cp 1
crap 4
rs 9.2
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 68
    public function getOption($key = null, $default = null)
160
    {
161 68
        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 52
    public function option($key, $value = null)
172
    {
173 52
        $keys = is_array($key) ? $key : [$key => $value];
174
175 52
        foreach ($keys as $key => $value) {
176 52
            Arr::set($this->options, $key, $value);
177 26
        }
178
179 52
        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 4
            $this->option('headers', Arr::except($headers, $names));
231 2
        }
232
233 4
        return $this;
234
    }
235
236
    /**
237
     * Set the request accept type.
238
     *
239
     * @param  string  $type
240
     * @return $this
241
     */
242 8
    public function accept($type)
243
    {
244 8
        return $this->header('Accept', $type);
245
    }
246
247
    /**
248
     * Set the request accept type to "application/json".
249
     *
250
     * @return $this
251
     */
252 4
    public function acceptJson()
253
    {
254 4
        return $this->accept('application/json');
255
    }
256
257
    /**
258
     * Set user agent for the request.
259
     *
260
     * @param  string  $value
261
     * @return $this
262
     */
263 4
    public function userAgent($value)
264
    {
265 4
        return $this->header('User-Agent', $value);
266
    }
267
268
    /**
269
     * Set the request content type.
270
     *
271
     * @param  string  $type
272
     * @return $this
273
     */
274 4
    public function contentType($type)
275
    {
276 4
        return $this->header('Content-Type', $type);
277
    }
278
279
    /**
280
     * Specify where the body of the response will be saved.
281
     * Set the "sink" option.
282
     *
283
     * @param  string|resource|\Psr\Http\Message\StreamInterface  $dest
284
     * @return $this
285
     */
286 4
    public function saveTo($dest)
287
    {
288 4
        return $this->option('sink', $dest);
289
    }
290
291
    /**
292
     * Set the body of the request to a multipart/form-data form.
293
     *
294
     * @param  array  $data
295
     * @return $this
296
     */
297 4
    public function multipart(array $data)
298
    {
299 4
        $multipart = [];
300
301 4
        foreach ($data as $key => $value) {
302 4
            if (! is_array($value)) {
303 4
                $value = ['contents' => $value];
304 2
            }
305
306 4
            if (! is_int($key)) {
307 4
                $value['name'] = $key;
308 2
            }
309
310 4
            $multipart[] = $value;
311 2
        }
312
313 4
        return $this->option('multipart', $multipart);
314
    }
315
316
    /**
317
     * Determine whether to catch Guzzle exceptions.
318
     *
319
     * @return bool
320
     */
321 8
    public function areExceptionsCaught()
322
    {
323 8
        return $this->getOption('catch_exceptions', false);
324
    }
325
326
    /**
327
     * Set whether to catch Guzzle exceptions or not.
328
     *
329
     * @param  bool  $catch
330
     * @return $this
331
     */
332 8
    public function catchExceptions($catch)
333
    {
334 8
        return $this->option('catch_exceptions', (bool) $catch);
335
    }
336
337
    /**
338
     * Send request to a URI.
339
     *
340
     * @param  string|\Psr\Http\Message\UriInterface  $uri
341
     * @param  string  $method
342
     * @param  array  $options
343
     * @return \Psr\Http\Message\ResponseInterface|null
344
     */
345 28
    public function request($uri = '', $method = 'GET', array $options = [])
346
    {
347 28
        $response = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
348
349
        try {
350 28
            $response = $this->client->request(
351 28
                strtoupper($method), $uri, $this->getRequestOptions($options)
352 14
            );
353 16
        } catch (Exception $e) {
354 4
            if (! $this->areExceptionsCaught()) {
355 4
                throw $e;
356
            }
357
        }
358
359 28
        return $response;
360
    }
361
362
    /**
363
     * Send request to a URI, expecting JSON content.
364
     *
365
     * @param  string|\Psr\Http\Message\UriInterface  $uri
366
     * @param  string  $method
367
     * @param  array  $options
368
     * @return \Psr\Http\Message\ResponseInterface|null
369
     */
370 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
371
    {
372 8
        Arr::set($options, 'headers.Accept', 'application/json');
373
374 8
        return $this->request($uri, $method, $options);
375
    }
376
377
    /**
378
     * Send asynchronous request to a URI.
379
     *
380
     * @param  string|\Psr\Http\Message\UriInterface  $uri
381
     * @param  string  $method
382
     * @param  array  $options
383
     * @return \GuzzleHttp\Promise\PromiseInterface
384
     */
385 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
386
    {
387 8
        return $this->client->requestAsync(
388 8
            strtoupper($method), $uri, $this->getRequestOptions($options)
389 4
        );
390
    }
391
392
    /**
393
     * Get options for the Guzzle request method.
394
     *
395
     * @param  array  $options
396
     * @return array
397
     */
398 32
    protected function getRequestOptions(array $options = [])
399
    {
400 32
        $options = array_replace_recursive($this->options, $options);
401
402 32
        $this->removeOption([
403 32
            'body', 'form_params', 'multipart', 'json', 'query',
404 16
            'sink', 'save_to', 'stream',
405 16
            'on_headers', 'on_stats', 'progress',
406 16
            'headers.Content-Type',
407 16
        ]);
408
409 32
        return $options;
410
    }
411
412
    /**
413
     * Request the URI and return the response content.
414
     *
415
     * @param  string|\Psr\Http\Message\UriInterface  $uri
416
     * @param  string  $method
417
     * @param  array  $options
418
     * @return string
419
     */
420 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
421
    {
422 4
        if ($response = $this->request($uri, $method, $options)) {
423 4
            return (string) $response->getBody();
424
        }
425
426
        return '';
427
    }
428
429
    /**
430
     * Request the URI and return the JSON-decoded response content.
431
     *
432
     * @param  string|\Psr\Http\Message\UriInterface  $uri
433
     * @param  string  $method
434
     * @param  array  $options
435
     * @return mixed
436
     */
437 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
438
    {
439 4
        if ($response = $this->requestJson($uri, $method, $options)) {
440 4
            return json_decode($response->getBody(), true);
441
        }
442
    }
443
444
    /**
445
     * Get all allowed magic request methods.
446
     *
447
     * @return array
448
     */
449 16
    protected function getMagicRequestMethods()
450
    {
451
        return [
452 16
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
453 8
        ];
454
    }
455
456
    /**
457
     * Determine if the given method is a magic request method.
458
     *
459
     * @param  string  $method
460
     * @param  string  &$requestMethod
461
     * @param  string  &$httpMethod
462
     * @return bool
463
     */
464 16
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
465
    {
466 16
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
467 4
            $httpMethod = substr($method, 0, $pos);
468 4
            $requestMethod = 'requestAsync';
469 2
        } else {
470 16
            $httpMethod = $method;
471 16
            $requestMethod = 'request';
472
        }
473
474 16
        if (! in_array($httpMethod, $this->getMagicRequestMethods())) {
475 8
            $httpMethod = $requestMethod = null;
476 4
        }
477
478 16
        return (bool) $httpMethod;
479
    }
480
481
    /**
482
     * Get parameters for the request() method from the magic request call.
483
     *
484
     * @param  string  $method
485
     * @param  array  $parameters
486
     * @return array
487
     */
488 8
    protected function getRequestParameters($method, array $parameters)
489
    {
490 8
        if (empty($parameters)) {
491 4
            $parameters = ['', $method];
492 2
        } else {
493 8
            array_splice($parameters, 1, 0, $method);
494
        }
495
496 8
        return $parameters;
497
    }
498
499
    /**
500
     * Get all allowed magic option methods.
501
     *
502
     * @return array
503
     */
504 8
    protected function getMagicOptionMethods()
505
    {
506 8
        static $optionMethods = null;
507
508 8
        if (is_null($optionMethods)) {
509 4
            $reflector = new ReflectionClass(RequestOptions::class);
510 4
            $optionMethods = array_map(
511 4
                [Str::class, 'camel'],
512 4
                array_values($reflector->getConstants())
513 2
            );
514 2
        }
515
516 8
        return $optionMethods;
517
    }
518
519
    /**
520
     * Determine if the given method is a magic option method.
521
     *
522
     * @param  string  $method
523
     * @return bool
524
     */
525 8
    protected function isMagicOptionMethod($method, &$option)
526
    {
527 8
        $option = in_array($method, $this->getMagicOptionMethods())
528 8
            ? Str::snake($method) : null;
529
530 8
        return (bool) $option;
531
    }
532
533
    /**
534
     * Handle magic option/request methods.
535
     *
536
     * @param  string  $method
537
     * @param  array  $parameters
538
     * @return mixed
539
     *
540
     * @throws \InvalidArgumentException
541
     * @throws \BadMethodCallException
542
     */
543 16
    public function __call($method, $parameters)
544
    {
545 16
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
546 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
547
        }
548
549 8
        if ($this->isMagicOptionMethod($method, $option)) {
550 4
            if (empty($parameters)) {
551 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
552
            }
553
554 4
            return $this->option($option, $parameters[0]);
555
        }
556
557 4
        throw new BadMethodCallException("Method [$method] does not exist.");
558
    }
559
}
560