Completed
Push — master ( 779a6e...a3d82a )
by Elf
13:58
created

HttpClient::multipart()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 5
nop 1
dl 0
loc 17
ccs 12
cts 12
cp 1
crap 4
rs 9.2
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(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 132
    public static function defaultOptions()
111
    {
112 132
        return static::$defaultOptions;
113
    }
114
115
    /**
116
     * Set the default request options.
117
     *
118
     * @param  array  $options
119
     * @return void
120
     */
121 132
    public static function setDefaultOptions(array $options)
122
    {
123 132
        static::$defaultOptions = $options;
124 132
    }
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 136
    public function __construct($options = [])
145
    {
146 136
        if (is_string($options) || $options instanceof UriInterface) {
147 8
            $options = ['base_uri' => $options];
148 134
        } elseif (! is_array($options)) {
149 4
            throw new InvalidArgumentException('Options must be a string, UriInterface, or an array');
150
        }
151
152 132
        $this->client = new Client(
153 132
            array_replace_recursive(static::defaultOptions(), $options)
154 66
        );
155
156 132
        $this->options = $this->client->getConfig();
157 132
    }
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 68
    public function getOption($key = null, $default = null)
177
    {
178 68
        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 52
    public function option($key, $value = null)
189
    {
190 52
        $keys = is_array($key) ? $key : [$key => $value];
191
192 52
        foreach ($keys as $key => $value) {
193 52
            Arr::set($this->options, $key, $value);
194 26
        }
195
196 52
        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 56
    public function removeOption($keys)
219
    {
220 56
        Arr::forget($this->options, is_array($keys) ? $keys : func_get_args());
221
222 56
        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->option('sink', $dest);
306
    }
307
308
    /**
309
     * Set the body of the request to a multipart/form-data form.
310
     *
311
     * @param  array  $data
312
     * @return $this
313
     */
314 4
    public function multipart(array $data)
315
    {
316 4
        $multipart = [];
317
318 4
        foreach ($data as $key => $value) {
319 4
            if (! is_array($value)) {
320 4
                $value = ['contents' => $value];
321 2
            }
322
323 4
            if (! is_int($key)) {
324 4
                $value['name'] = $key;
325 2
            }
326
327 4
            $multipart[] = $value;
328 2
        }
329
330 4
        return $this->option('multipart', $multipart);
331
    }
332
333
    /**
334
     * Determine whether to catch Guzzle exceptions.
335
     *
336
     * @return bool
337
     */
338 8
    public function areExceptionsCaught()
339
    {
340 8
        return $this->getOption('catch_exceptions', false);
341
    }
342
343
    /**
344
     * Set whether to catch Guzzle exceptions or not.
345
     *
346
     * @param  bool  $catch
347
     * @return $this
348
     */
349 8
    public function catchExceptions($catch)
350
    {
351 8
        return $this->option('catch_exceptions', (bool) $catch);
352
    }
353
354
    /**
355
     * Get the Guzzle response instance.
356
     *
357
     * @return \GuzzleHttp\Psr7\Response|null
358
     */
359 20
    public function getResponse()
360
    {
361 20
        return $this->response;
362
    }
363
364
    /**
365
     * Get data from the response.
366
     *
367
     * @param  string|\Closure  $callback
368
     * @param  mixed  $parameters
369
     * @param  mixed  $default
370
     * @return mixed
371
     */
372 24
    public function getResponseData($callback, $parameters = [], $default = null)
373
    {
374 24
        if ($this->response) {
375 12
            return $callback instanceof Closure
376 14
                ? $callback($this->response, ...(array) $parameters)
377 24
                : $this->response->$callback(...(array) $parameters);
378
        }
379
380 4
        return $default;
381
    }
382
383
    /**
384
     * Get the response content.
385
     *
386
     * @return string
387
     */
388 16
    public function getContent()
389
    {
390 16
        return (string) $this->getBody();
391
    }
392
393
    /**
394
     * Get the JSON-decoded response content.
395
     *
396
     * @param  bool  $assoc
397
     * @return mixed
398
     */
399 8
    public function getJson($assoc = true)
400
    {
401 8
        return json_decode($this->getContent(), $assoc);
402
    }
403
404
    /**
405
     * Send request to a URI.
406
     *
407
     * @param  string|\Psr\Http\Message\UriInterface  $uri
408
     * @param  string  $method
409
     * @param  array  $options
410
     * @return $this
411
     */
412 48
    public function request($uri = '', $method = 'GET', array $options = [])
413
    {
414 48
        $this->response = null;
415
416
        try {
417 48
            $this->response = $this->client->request(
418 48
                strtoupper($method), $uri, $this->getRequestOptions($options)
419 24
            );
420 26
        } catch (Exception $e) {
421 4
            if (! $this->areExceptionsCaught()) {
422 4
                throw $e;
423
            }
424
        }
425
426 48
        return $this;
427
    }
428
429
    /**
430
     * Send request to a URI, expecting JSON content.
431
     *
432
     * @param  string|\Psr\Http\Message\UriInterface  $uri
433
     * @param  string  $method
434
     * @param  array  $options
435
     * @return $this
436
     */
437 8
    public function requestJson($uri = '', $method = 'GET', array $options = [])
438
    {
439 8
        Arr::set($options, 'headers.Accept', 'application/json');
440
441 8
        return $this->request($uri, $method, $options);
442
    }
443
444
    /**
445
     * Send asynchronous request to a URI.
446
     *
447
     * @param  string|\Psr\Http\Message\UriInterface  $uri
448
     * @param  string  $method
449
     * @param  array  $options
450
     * @return \GuzzleHttp\Promise\PromiseInterface
451
     */
452 8
    public function requestAsync($uri = '', $method = 'GET', array $options = [])
453
    {
454 8
        return $this->client->requestAsync(
455 8
            strtoupper($method), $uri, $this->getRequestOptions($options)
456 4
        );
457
    }
458
459
    /**
460
     * Get options for the Guzzle request method.
461
     *
462
     * @param  array  $options
463
     * @return array
464
     */
465 52
    protected function getRequestOptions(array $options = [])
466
    {
467 52
        $options = array_replace_recursive($this->options, $options);
468
469 52
        $this->removeOption([
470 52
            'body', 'form_params', 'multipart', 'json', 'query',
471 26
            'sink', 'save_to', 'stream',
472 26
            'on_headers', 'on_stats', 'progress',
473 26
            'headers.Content-Type',
474 26
        ]);
475
476 52
        return $options;
477
    }
478
479
    /**
480
     * Request the URI and return the response content.
481
     *
482
     * @param  string|\Psr\Http\Message\UriInterface  $uri
483
     * @param  string  $method
484
     * @param  array  $options
485
     * @return string
486
     */
487 4
    public function fetchContent($uri = '', $method = 'GET', array $options = [])
488
    {
489 4
        return $this->request($uri, $method, $options)->getContent();
490
    }
491
492
    /**
493
     * Request the URI and return the JSON-decoded response content.
494
     *
495
     * @param  string|\Psr\Http\Message\UriInterface  $uri
496
     * @param  string  $method
497
     * @param  array  $options
498
     * @return mixed
499
     */
500 4
    public function fetchJson($uri = '', $method = 'GET', array $options = [])
501
    {
502 4
        return $this->requestJson($uri, $method, $options)->getJson();
503
    }
504
505
    /**
506
     * Get all allowed magic request methods.
507
     *
508
     * @return array
509
     */
510 36
    protected function getMagicRequestMethods()
511
    {
512
        return [
513 36
            'get', 'head', 'post', 'put', 'patch', 'delete', 'options',
514 18
        ];
515
    }
516
517
    /**
518
     * Determine if the given method is a magic request method.
519
     *
520
     * @param  string  $method
521
     * @param  string  &$requestMethod
522
     * @param  string  &$httpMethod
523
     * @return bool
524
     */
525 36
    protected function isMagicRequestMethod($method, &$requestMethod, &$httpMethod)
526
    {
527 36
        if (strlen($method) > 5 && $pos = strrpos($method, 'Async', -5)) {
528 4
            $httpMethod = substr($method, 0, $pos);
529 4
            $requestMethod = 'requestAsync';
530 2
        } else {
531 36
            $httpMethod = $method;
532 36
            $requestMethod = 'request';
533
        }
534
535 36
        if (! in_array($httpMethod, $this->getMagicRequestMethods())) {
536 28
            $httpMethod = $requestMethod = null;
537 14
        }
538
539 36
        return (bool) $httpMethod;
540
    }
541
542
    /**
543
     * Get parameters for the request() method from the magic request call.
544
     *
545
     * @param  string  $method
546
     * @param  array  $parameters
547
     * @return array
548
     */
549 8
    protected function getRequestParameters($method, array $parameters)
550
    {
551 8
        if (empty($parameters)) {
552 4
            $parameters = ['', $method];
553 2
        } else {
554 8
            array_splice($parameters, 1, 0, $method);
555
        }
556
557 8
        return $parameters;
558
    }
559
560
    /**
561
     * Get all allowed magic response methods.
562
     *
563
     * @return array
564
     */
565 28
    protected function getMagicResponseMethods()
566
    {
567
        return [
568 28
            'getStatusCode', 'getReasonPhrase', 'getProtocolVersion',
569 14
            'getHeaders', 'hasHeader', 'getHeader', 'getHeaderLine', 'getBody',
570 14
        ];
571
    }
572
573
    /**
574
     * Determine if the given method is a magic response method.
575
     *
576
     * @param  string  $method
577
     * @return bool
578
     */
579 28
    protected function isMagicResponseMethod($method)
580
    {
581 28
        return in_array($method, $this->getMagicResponseMethods());
582
    }
583
584
    /**
585
     * Get all allowed magic option methods.
586
     *
587
     * @return array
588
     */
589 8
    protected function getMagicOptionMethods()
590
    {
591 8
        static $optionMethods = null;
592
593 8
        if (is_null($optionMethods)) {
594 4
            $reflector = new ReflectionClass(RequestOptions::class);
595 4
            $optionMethods = array_map(
596 4
                [Str::class, 'camel'],
597 4
                array_values($reflector->getConstants())
598 2
            );
599 2
        }
600
601 8
        return $optionMethods;
602
    }
603
604
    /**
605
     * Determine if the given method is a magic option method.
606
     *
607
     * @param  string  $method
608
     * @return bool
609
     */
610 8
    protected function isMagicOptionMethod($method, &$option)
611
    {
612 8
        $option = in_array($method, $this->getMagicOptionMethods())
613 8
            ? Str::snake($method) : null;
614
615 8
        return (bool) $option;
616
    }
617
618
    /**
619
     * Handle magic method to send request, get response data, or set
620
     * request options.
621
     *
622
     * @param  string  $method
623
     * @param  array  $parameters
624
     * @return mixed
625
     *
626
     * @throws \InvalidArgumentException
627
     * @throws \BadMethodCallException
628
     */
629 36
    public function __call($method, $parameters)
630
    {
631 36
        if ($this->isMagicRequestMethod($method, $requestMethod, $httpMethod)) {
632 8
            return $this->$requestMethod(...$this->getRequestParameters($httpMethod, $parameters));
633
        }
634
635 28
        if ($this->isMagicResponseMethod($method)) {
636 20
            return $this->getResponseData($method, $parameters);
637
        }
638
639 8
        if ($this->isMagicOptionMethod($method, $option)) {
640 4
            if (empty($parameters)) {
641 4
                throw new InvalidArgumentException("Method [$method] needs one argument.");
642
            }
643
644 4
            return $this->option($option, $parameters[0]);
645
        }
646
647 4
        throw new BadMethodCallException("Method [$method] does not exist.");
648
    }
649
}
650