Completed
Push — master ( bc6bdd...4b3d21 )
by Elf
01:31
created

HttpClient::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.0312

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 8
cp 0.875
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 1
crap 4.0312
1
<?php
2
3
namespace ElfSundae;
4
5
use Closure;
6
use Exception;
7
use GuzzleHttp\Client;
8
use Illuminate\Support\Arr;
9
use Illuminate\Support\Str;
10
use InvalidArgumentException;
11
use Psr\Http\Message\UriInterface;
12
13
class HttpClient
14
{
15
    /**
16
     * The default request options.
17
     *
18
     * @var array
19
     */
20
    protected static $defaultOptions = [
21
        'connect_timeout' => 5,
22
        'timeout' => 25,
23
    ];
24
25
    /**
26
     * The Guzzle client.
27
     *
28
     * @var \GuzzleHttp\Client
29
     */
30
    protected $client;
31
32
    /**
33
     * The Guzzle response.
34
     *
35
     * @var \GuzzleHttp\Psr7\Response
36
     */
37
    protected $response;
38
39
    /**
40
     * The request options.
41
     *
42
     * @var array
43
     */
44
    protected $options = [];
45
46
    /**
47
     * Indicate whether to catch Guzzle exceptions.
48
     *
49
     * @var bool
50
     */
51
    protected $catchExceptions = true;
52
53
    /**
54
     * Get the default request options.
55
     *
56
     * @return array
57
     */
58 24
    public static function defaultOptions()
59
    {
60 24
        return static::$defaultOptions;
61
    }
62
63
    /**
64
     * Set the default request options.
65
     *
66
     * @param  array  $options
67
     * @return void
68
     */
69 1
    public static function setDefaultOptions(array $options)
70
    {
71 1
        static::$defaultOptions = $options;
72 1
    }
73
74
    /**
75
     * Create a http client instance.
76
     *
77
     * @param  array|string|\Psr\Http\Message\UriInterface  $options  base URI or any request options
78
     *
79
     * @throws \InvalidArgumentException
80
     */
81 23
    public function __construct($options = [])
82
    {
83 23
        if (is_string($options) || $options instanceof UriInterface) {
84 1
            $options = ['base_uri' => $options];
85 22
        } elseif (! is_array($options)) {
86
            throw new InvalidArgumentException('config must be a string, UriInterface, or an array');
87
        }
88
89 23
        $this->client = new Client(
90 23
            $this->options = $options + static::defaultOptions()
91
        );
92 23
    }
93
94
    /**
95
     * Get the Guzzle client instance.
96
     *
97
     * @return \GuzzleHttp\Client
98
     */
99 2
    public function getClient()
100
    {
101 2
        return $this->client;
102
    }
103
104
    /**
105
     * Get whether to catch Guzzle exceptions or not.
106
     *
107
     * @return bool
108
     */
109
    public function areExceptionsCaught()
110
    {
111
        return $this->catchExceptions;
112
    }
113
114
    /**
115
     * Set whether to catch Guzzle exceptions or not.
116
     *
117
     * @param  bool  $catch
118
     * @return $this
119
     */
120
    public function catchExceptions($catch)
121
    {
122
        $this->catchExceptions = (bool) $catch;
123
124
        return $this;
125
    }
126
127
    /**
128
     * Get the request options.
129
     *
130
     * @return array
131
     */
132 9
    public function getOptions()
133
    {
134 9
        return $this->options;
135
    }
136
137
    /**
138
     * Set the request options.
139
     *
140
     * @param  array  $options
141
     * @return $this
142
     */
143
    public function setOptions(array $options)
144
    {
145
        $this->options = $options;
146
147
        return $this;
148
    }
149
150
    /**
151
     * Merge the given options to the request options.
152
     *
153
     * @param  array  $options
154
     * @return $this
155
     */
156
    public function mergeOptions(array $options)
157
    {
158
        return $this->setOptions($options + $this->options);
159
    }
160
161
    /**
162
     * Remove request options using "dot" notation.
163
     *
164
     * @param  string|array|null $key
165
     * @return $this
166
     */
167 16
    public function removeOptions($key = null)
168
    {
169 16
        if (is_null($key)) {
170 16
            $this->options = [];
171
        } else {
172 1
            Arr::forget($this->options, is_array($key) ? $key : func_get_args());
173
        }
174
175 16
        return $this;
176
    }
177
178
    /**
179
     * Get a request option using "dot" notation.
180
     *
181
     * @param  string $key
182
     * @return mixed
183
     */
184 3
    public function getOption($key)
185
    {
186 3
        return Arr::get($this->options, $key);
187
    }
188
189
    /**
190
     * Set a request option using "dot" notation.
191
     *
192
     * @param  string|array  $key
193
     * @param  mixed  $value
194
     * @return $this
195
     */
196 11
    public function option($key, $value = null)
197
    {
198 11
        $keys = is_array($key) ? $key : [$key => $value];
199
200 11
        foreach ($keys as $key => $value) {
201 11
            Arr::set($this->options, $key, $value);
202
        }
203
204 11
        return $this;
205
    }
206
207
    /**
208
     * Set the request header.
209
     *
210
     * @param  string  $name
211
     * @param  mixed  $value
212
     * @return $this
213
     */
214 4
    public function header($name, $value)
215
    {
216 4
        return $this->option('headers.'.$name, $value);
217
    }
218
219
    /**
220
     * Set the request content type.
221
     *
222
     * @param  string  $type
223
     * @return $this
224
     */
225 1
    public function contentType($type)
226
    {
227 1
        return $this->header('Content-Type', $type);
228
    }
229
230
    /**
231
     * Set the request accept type.
232
     *
233
     * @param  string  $type
234
     * @return $this
235
     */
236 2
    public function accept($type)
237
    {
238 2
        return $this->header('Accept', $type);
239
    }
240
241
    /**
242
     * Set the request accept type to JSON.
243
     *
244
     * @return $this
245
     */
246 1
    public function acceptJson()
247
    {
248 1
        return $this->accept('application/json');
249
    }
250
251
    /**
252
     * Specify where the body of a response will be saved.
253
     * Set the "sink" option.
254
     *
255
     * @param  mixed  $dest
256
     * @return $this
257
     */
258 1
    public function saveTo($dest)
259
    {
260 1
        return $this->removeOptions('save_to')->option('sink', $dest);
261
    }
262
263
    /**
264
     * Get the Guzzle response instance.
265
     *
266
     * @return \GuzzleHttp\Psr7\Response|null
267
     */
268 8
    public function getResponse()
269
    {
270 8
        return $this->response;
271
    }
272
273
    /**
274
     * Get data from the response.
275
     *
276
     * @param  string|\Closure  $callback
277
     * @param  array  $parameters
278
     * @param  mixed  $default
279
     * @return mixed
280
     */
281 1
    protected function getResponseData($callback, array $parameters = [], $default = null)
282
    {
283 1
        if ($this->response) {
284 1
            return $callback instanceof Closure
285
                ? $callback($this->response, ...$parameters)
286 1
                : $this->response->$callback(...$parameters);
287
        }
288
289
        return $default;
290
    }
291
292
    /**
293
     * Get the response content.
294
     *
295
     * @return string
296
     */
297 1
    public function getContent()
298
    {
299 1
        return (string) $this->getBody();
0 ignored issues
show
Documentation Bug introduced by
The method getBody does not exist on object<ElfSundae\HttpClient>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
300
    }
301
302
    /**
303
     * Get the decoded JSON response.
304
     *
305
     * @param  bool  $assoc
306
     * @return mixed
307
     */
308
    public function json($assoc = true)
309
    {
310
        if ($this->response) {
311
            return json_decode($this->getContent(), $assoc);
312
        }
313
    }
314
315
    /**
316
     * Make request to a URI.
317
     *
318
     * @param  string  $uri
319
     * @param  string  $method
320
     * @param  array  $options
321
     * @return $this
322
     */
323 9
    public function request($uri, $method = 'GET', array $options = [])
324
    {
325 9
        $options += $this->options;
326
327 9
        $this->response = null;
328
329
        try {
330 9
            $this->response = $this->client->request($method, $uri, $options);
331 1
        } catch (Exception $e) {
332 1
            if (! $this->catchExceptions) {
333
                throw $e;
334
            }
335
        }
336
337 9
        return $this;
338
    }
339
340
    /**
341
     * Make request to a URI, expecting JSON content.
342
     *
343
     * @param  string  $uri
344
     * @param  string  $method
345
     * @param  array  $options
346
     * @return $this
347
     */
348 3
    public function requestJson($uri, $method = 'GET', array $options = [])
349
    {
350 3
        $options = $this->addAcceptableJsonType($options + $this->options);
351
352 3
        return $this->request($uri, $method, $options);
353
    }
354
355
    /**
356
     * Add JSON type to the "Accept" header for the request options.
357
     *
358
     * @param  array  $options
359
     * @return array
360
     */
361 3
    protected function addAcceptableJsonType(array $options)
362
    {
363 3
        $accept = Arr::get($options, 'headers.Accept', '');
364
365 3
        if (! Str::contains($accept, ['/json', '+json'])) {
366 3
            $accept = rtrim('application/json, '.$accept, ', ');
367
368 3
            Arr::set($options, 'headers.Accept', $accept);
369
        }
370
371 3
        return $options;
372
    }
373
374
    /**
375
     * Request the URI and return the response content.
376
     *
377
     * @param  string  $uri
378
     * @param  string  $method
379
     * @param  array  $options
380
     * @return string|null
381
     */
382 1
    public function fetchContent($uri, $method = 'GET', array $options = [])
383
    {
384 1
        return $this->request($uri, $method, $options)->getContent();
385
    }
386
387
    /**
388
     * Request the URI and return the JSON decoded response content.
389
     *
390
     * @param  string  $uri
391
     * @param  string  $method
392
     * @param  array  $options
393
     * @param  bool  $assoc
394
     * @return mixed
395
     */
396 1
    public function fetchJson($uri, $method = 'GET', array $options = [], $assoc = true)
397
    {
398 1
        return $this->requestJson($uri, $method, $options)->getJson($assoc);
0 ignored issues
show
Documentation Bug introduced by
The method getJson does not exist on object<ElfSundae\HttpClient>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
399
    }
400
401
    /**
402
     * Get the dynamic response methods.
403
     *
404
     * @return array
405
     */
406 6
    protected function getDynamicResponseMethods()
407
    {
408
        return [
409 6
            'getStatusCode', 'getReasonPhrase', 'getProtocolVersion',
410
            'getHeaders', 'hasHeader', 'getHeader', 'getHeaderLine', 'getBody',
411
        ];
412
    }
413
414
    /**
415
     * Dynamically methods to set request option, send request, or get
416
     * response properties.
417
     *
418
     * @param  string  $method
419
     * @param  array  $args
420
     * @return mixed
421
     */
422 8
    public function __call($method, $args)
423
    {
424
        // Handle magic request methods
425 8
        if (in_array($method, ['get', 'head', 'put', 'post', 'patch', 'delete'])) {
426 2
            if (count($args) < 1) {
427
                throw new InvalidArgumentException('Magic request methods require an URI and optional options array');
428
            }
429
430 2
            $url = $args[0];
431 2
            $options = isset($args[1]) ? $args[1] : [];
432
433 2
            return $this->request($url, $method, $options);
434
        }
435
436 6
        if (in_array($method, $this->getDynamicResponseMethods())) {
437 1
            return $this->getResponseData($method, $args);
438
        }
439
440
        // Handle setting request options
441 5
        return $this->option(Str::snake($method), $args[0]);
442
    }
443
}
444