HttpClient::fetchContent()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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