Completed
Push — master ( be16cb...a97d9c )
by Elf
02:23
created

HttpClient::setOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace ElfSundae;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use Illuminate\Support\Arr;
8
use Illuminate\Support\Str;
9
use InvalidArgumentException;
10
use Psr\Http\Message\UriInterface;
11
12
class HttpClient
13
{
14
    /**
15
     * The default request options.
16
     *
17
     * @var array
18
     */
19
    protected static $defaultOptions = [
20
        'connect_timeout' => 5,
21
        'timeout' => 25,
22
    ];
23
24
    /**
25
     * The Guzzle client.
26
     *
27
     * @var \GuzzleHttp\Client
28
     */
29
    protected $client;
30
31
    /**
32
     * The Guzzle response.
33
     *
34
     * @var \GuzzleHttp\Psr7\Response
35
     */
36
    protected $response;
37
38
    /**
39
     * The request options.
40
     *
41
     * @var array
42
     */
43
    protected $options = [];
44
45
    /**
46
     * Indicate whether to catch Guzzle exceptions.
47
     *
48
     * @var bool
49
     */
50
    protected $catchExceptions = true;
51
52
    /**
53
     * Get the default request options.
54
     *
55
     * @return array
56
     */
57 24
    public static function defaultOptions()
58
    {
59 24
        return static::$defaultOptions;
60
    }
61
62
    /**
63
     * Set the default request options.
64
     *
65
     * @param  array  $options
66
     * @return void
67
     */
68 1
    public static function setDefaultOptions(array $options)
69
    {
70 1
        static::$defaultOptions = $options;
71 1
    }
72
73
    /**
74
     * Create a http client instance.
75
     *
76
     * @param  array|string|\Psr\Http\Message\UriInterface  $config  base URI or any request options
77
     */
78 23
    public function __construct($config = [])
79
    {
80 23
        if (is_string($config) || $config instanceof UriInterface) {
81 1
            $config = ['base_uri' => $config];
82 23
        } elseif (! is_array($config)) {
83
            throw new InvalidArgumentException('config must be a string, UriInterface, or an array');
84
        }
85
86 23
        $this->client = new Client(
87 23
            $this->options = $config + static::defaultOptions()
88 23
        );
89 23
    }
90
91
    /**
92
     * Get the Guzzle client instance.
93
     *
94
     * @return \GuzzleHttp\Client
95
     */
96 2
    public function getClient()
97
    {
98 2
        return $this->client;
99
    }
100
101
    /**
102
     * Get whether to catch Guzzle exceptions or not.
103
     *
104
     * @return bool
105
     */
106
    public function areExceptionsCaught()
107
    {
108
        return $this->catchExceptions;
109
    }
110
111
    /**
112
     * Set whether to catch Guzzle exceptions or not.
113
     *
114
     * @param  bool  $catch
115
     * @return $this
116
     */
117
    public function catchExceptions($catch)
118
    {
119
        $this->catchExceptions = (bool) $catch;
120
121
        return $this;
122
    }
123
124
    /**
125
     * Get the request options.
126
     *
127
     * @return array
128
     */
129 9
    public function getOptions()
130
    {
131 9
        return $this->options;
132
    }
133
134
    /**
135
     * Merge the request options.
136
     *
137
     * @param  array  $options
138
     * @return $this
139
     */
140 2
    public function options(array $options)
141
    {
142 2
        $this->options = $options + $this->options;
143
144 2
        return $this;
145
    }
146
147
    /**
148
     * Remove one or many options using "dot" notation.
149
     *
150
     * @param  string|array|null $key
151
     * @return $this
152
     */
153 16
    public function removeOptions($key = null)
154
    {
155 16
        if (is_null($key)) {
156 16
            $this->options = [];
157 16
        } else {
158 1
            Arr::forget($this->options, is_array($key) ? $key : func_get_args());
159
        }
160
161 16
        return $this;
162
    }
163
164
    /**
165
     * Set a request option using "dot" notation.
166
     *
167
     * @param  string|array  $key
168
     * @param  mixed  $value
169
     * @return $this
170
     */
171 8
    public function option($key, $value = null)
172
    {
173 8
        $keys = is_array($key) ? $key : [$key => $value];
174
175 8
        foreach ($keys as $key => $value) {
176 8
            Arr::set($this->options, $key, $value);
177 8
        }
178
179 8
        return $this;
180
    }
181
182
    /**
183
     * Get a request option using "dot" notation.
184
     *
185
     * @param  string $key
186
     * @return mixed
187
     */
188 3
    public function getOption($key)
189
    {
190 3
        return Arr::get($this->options, $key);
191
    }
192
193
    /**
194
     * Set the request header.
195
     *
196
     * @param  string  $name
197
     * @param  mixed  $value
198
     * @return $this
199
     */
200 4
    public function header($name, $value)
201
    {
202 4
        return $this->option('headers.'.$name, $value);
203
    }
204
205
    /**
206
     * Set the request content type.
207
     *
208
     * @param  string  $type
209
     * @return $this
210
     */
211 1
    public function contentType($type)
212
    {
213 1
        return $this->header('Content-Type', $type);
214
    }
215
216
    /**
217
     * Set the request accept type.
218
     *
219
     * @param  string  $type
220
     * @return $this
221
     */
222 2
    public function accept($type)
223
    {
224 2
        return $this->header('Accept', $type);
225
    }
226
227
    /**
228
     * Set the request accept type to JSON.
229
     *
230
     * @return $this
231
     */
232 1
    public function acceptJson()
233
    {
234 1
        return $this->accept('application/json');
235
    }
236
237
    /**
238
     * Specify where the body of a response will be saved.
239
     * Set the "sink" option.
240
     *
241
     * @param  mixed  $value
242
     * @return $this
243
     */
244 1
    public function saveTo($value)
245
    {
246 1
        return $this->option('sink', $value);
247
    }
248
249
    /**
250
     * Get the Guzzle response instance.
251
     *
252
     * @return \GuzzleHttp\Psr7\Response|null
253
     */
254 8
    public function getResponse()
255
    {
256 8
        return $this->response;
257
    }
258
259
    /**
260
     * Get the status code of response.
261
     *
262
     * @return int
263
     */
264
    public function getStatusCode()
265
    {
266
        if ($this->response) {
267
            return $this->response->getStatusCode();
268
        }
269
    }
270
271
    /**
272
     * Get the response header value.
273
     *
274
     * @param  string  $name
275
     * @return mixed
276
     */
277
    public function getHeader($name)
278
    {
279
        if ($this->response) {
280
            return $this->response->getHeaderLine($name);
281
        }
282
    }
283
284
    /**
285
     * Get all response headers values.
286
     *
287
     * @return array
288
     */
289
    public function getHeaders()
290
    {
291
        return $this->response ? $this->response->getHeaders() : [];
292
    }
293
294
    /**
295
     * Get response body.
296
     *
297
     * @return \GuzzleHttp\Psr7\Stream|null
298
     */
299 2
    public function getBody()
300
    {
301 2
        if ($this->response) {
302 2
            return $this->response->getBody();
303
        }
304
    }
305
306
    /**
307
     * Get response content.
308
     *
309
     * @return string|null
310
     */
311 2
    public function getContent()
312
    {
313 2
        if ($this->response) {
314 2
            return (string) $this->getBody();
315
        }
316
    }
317
318
    /**
319
     * Get JSON decoded response content.
320
     *
321
     * @param  bool  $assoc
322
     * @return mixed
323
     */
324 1
    public function getJson($assoc = true)
325
    {
326 1
        if ($this->response) {
327 1
            return json_decode($this->getContent(), $assoc);
328
        }
329
    }
330
331
    /**
332
     * Make request to a URI.
333
     *
334
     * @param  string  $uri
335
     * @param  string  $method
336
     * @param  array  $options
337
     * @return $this
338
     */
339 9
    public function request($uri, $method = 'GET', array $options = [])
340
    {
341
        try {
342 9
            $this->response = $this->client->request(
343 9
                $method, $uri, $options += $this->options
344 9
            );
345 9
        } catch (Exception $e) {
346 1
            if (! $this->catchExceptions) {
347
                throw $e;
348
            }
349
        }
350
351 9
        return $this;
352
    }
353
354
    /**
355
     * Make request to a URI, expecting JSON content.
356
     *
357
     * @param  string  $uri
358
     * @param  string  $method
359
     * @param  array  $options
360
     * @return $this
361
     */
362 3
    public function requestJson($uri, $method = 'GET', array $options = [])
363
    {
364 3
        Arr::set($options, 'headers.Accept', 'application/json');
365
366 3
        return $this->request($uri, $method, $options);
367
    }
368
369
    /**
370
     * Request the URI and return the response content.
371
     *
372
     * @param  string  $uri
373
     * @param  string  $method
374
     * @param  array  $options
375
     * @return string|null
376
     */
377 1
    public function fetchContent($uri, $method = 'GET', array $options = [])
378
    {
379 1
        return $this->request($uri, $method, $options)->getContent();
380
    }
381
382
    /**
383
     * Request the URI and return the JSON decoded response content.
384
     *
385
     * @param  string  $uri
386
     * @param  string  $method
387
     * @param  array  $options
388
     * @param  bool  $assoc
389
     * @return mixed
390
     */
391 1
    public function fetchJson($uri, $method = 'GET', array $options = [], $assoc = true)
392
    {
393 1
        return $this->requestJson($uri, $method, $options)->getJson($assoc);
394
    }
395
396
    /**
397
     * Dynamically methods to set request option, send request, or get
398
     * response properties.
399
     *
400
     * @param  string  $method
401
     * @param  array  $args
402
     * @return mixed
403
     */
404 4
    public function __call($method, $args)
405
    {
406
        // Handle magic request methods
407 4
        if (in_array($method, ['get', 'head', 'put', 'post', 'patch', 'delete'])) {
408 2
            if (count($args) < 1) {
409
                throw new InvalidArgumentException('Magic request methods require an URI and optional options array');
410
            }
411
412 2
            $url = $args[0];
413 2
            $options = isset($args[1]) ? $args[1] : [];
414
415 2
            return $this->request($url, $method, $options);
416
        }
417
418
        // Handle setting request options
419 2
        return $this->option(Str::snake($method), $args[0]);
420
    }
421
}
422