Completed
Push — master ( 96210f...e8c731 )
by Elf
01:21
created

HttpClient::contentType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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 22
        } 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
        );
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
     * Set whether to catch Guzzle exceptions or not.
103
     *
104
     * @param  bool  $catch
105
     * @return $this
106
     */
107
    public function catchExceptions($catch)
108
    {
109
        $this->catchExceptions = (bool) $catch;
110
111
        return $this;
112
    }
113
114
    /**
115
     * Get the request options.
116
     *
117
     * @return array
118
     */
119 9
    public function getOptions()
120
    {
121 9
        return $this->options;
122
    }
123
124
    /**
125
     * Set the request options.
126
     *
127
     * @param  array  $options
128
     * @return $this
129
     */
130 2
    public function setOptions(array $options)
131
    {
132 2
        $this->options = $options;
133
134 2
        return $this;
135
    }
136
137
    /**
138
     * Merge the request options.
139
     *
140
     * @param  array  $options
141
     * @return $this
142
     */
143 2
    public function options(array $options)
144
    {
145 2
        return $this->setOptions($options + $this->options);
146
    }
147
148
    /**
149
     * Remove one or many options using "dot" notation.
150
     *
151
     * @param  string|array|null $key
152
     * @return $this
153
     */
154 16
    public function removeOptions($key = null)
155
    {
156 16
        if (is_null($key)) {
157 16
            $this->options = [];
158
        } else {
159 1
            Arr::forget($this->options, is_array($key) ? $key : func_get_args());
160
        }
161
162 16
        return $this;
163
    }
164
165
    /**
166
     * Set a request option using "dot" notation.
167
     *
168
     * @param  string|array  $key
169
     * @param  mixed  $value
170
     * @return $this
171
     */
172 8
    public function option($key, $value = null)
173
    {
174 8
        $keys = is_array($key) ? $key : [$key => $value];
175
176 8
        foreach ($keys as $key => $value) {
177 8
            Arr::set($this->options, $key, $value);
178
        }
179
180 8
        return $this;
181
    }
182
183
    /**
184
     * Get a request option using "dot" notation.
185
     *
186
     * @param  string $key
187
     * @return mixed
188
     */
189 3
    public function getOption($key)
190
    {
191 3
        return Arr::get($this->options, $key);
192
    }
193
194
    /**
195
     * Set the request header.
196
     *
197
     * @param  string  $name
198
     * @param  mixed  $value
199
     * @return $this
200
     */
201 4
    public function header($name, $value)
202
    {
203 4
        return $this->option('headers.'.$name, $value);
204
    }
205
206
    /**
207
     * Set the request content type.
208
     *
209
     * @param  string  $type
210
     * @return $this
211
     */
212 1
    public function contentType($type)
213
    {
214 1
        return $this->header('Content-Type', $type);
215
    }
216
217
    /**
218
     * Set the request accept type.
219
     *
220
     * @param  string  $type
221
     * @return $this
222
     */
223 2
    public function accept($type)
224
    {
225 2
        return $this->header('Accept', $type);
226
    }
227
228
    /**
229
     * Set the request accept type to JSON.
230
     *
231
     * @return $this
232
     */
233 1
    public function acceptJson()
234
    {
235 1
        return $this->accept('application/json');
236
    }
237
238
    /**
239
     * Specify where the body of a response will be saved.
240
     * Set the "sink" option.
241
     *
242
     * @param  mixed  $value
243
     * @return $this
244
     */
245 1
    public function saveTo($value)
246
    {
247 1
        return $this->option('sink', $value);
248
    }
249
250
    /**
251
     * Get the Guzzle response instance.
252
     *
253
     * @return \GuzzleHttp\Psr7\Response|null
254
     */
255 8
    public function getResponse()
256
    {
257 8
        return $this->response;
258
    }
259
260
    /**
261
     * Get the status code of response.
262
     *
263
     * @return int
264
     */
265
    public function getStatusCode()
266
    {
267
        if ($this->response) {
268
            return $this->response->getStatusCode();
269
        }
270
    }
271
272
    /**
273
     * Get the response header value.
274
     *
275
     * @param  string  $name
276
     * @return mixed
277
     */
278
    public function getHeader($name)
279
    {
280
        if ($this->response) {
281
            return $this->response->getHeaderLine($name);
282
        }
283
    }
284
285
    /**
286
     * Get all response headers values.
287
     *
288
     * @return array
289
     */
290
    public function getHeaders()
291
    {
292
        return $this->response ? $this->response->getHeaders() : [];
293
    }
294
295
    /**
296
     * Get response body.
297
     *
298
     * @return \GuzzleHttp\Psr7\Stream|null
299
     */
300 2
    public function getBody()
301
    {
302 2
        if ($this->response) {
303 2
            return $this->response->getBody();
304
        }
305
    }
306
307
    /**
308
     * Get response content.
309
     *
310
     * @return string|null
311
     */
312 2
    public function getContent()
313
    {
314 2
        if ($this->response) {
315 2
            return (string) $this->getBody();
316
        }
317
    }
318
319
    /**
320
     * Get JSON decoded response content.
321
     *
322
     * @param  bool  $assoc
323
     * @return mixed
324
     */
325 1
    public function getJson($assoc = true)
326
    {
327 1
        if ($this->response) {
328 1
            return json_decode($this->getContent(), $assoc);
329
        }
330
    }
331
332
    /**
333
     * Make request to a URI.
334
     *
335
     * @param  string  $uri
336
     * @param  string  $method
337
     * @param  array  $options
338
     * @return $this
339
     */
340 9
    public function request($uri, $method = 'GET', array $options = [])
341
    {
342
        try {
343 9
            $this->response = $this->client->request(
344 9
                $method, $uri, $options += $this->options
345
            );
346 1
        } catch (Exception $e) {
347 1
            if (! $this->catchExceptions) {
348
                throw $e;
349
            }
350
        }
351
352 9
        return $this;
353
    }
354
355
    /**
356
     * Make request to a URI, expecting JSON content.
357
     *
358
     * @param  string  $uri
359
     * @param  string  $method
360
     * @param  array  $options
361
     * @return $this
362
     */
363 3
    public function requestJson($uri, $method = 'GET', array $options = [])
364
    {
365 3
        Arr::set($options, 'headers.Accept', 'application/json');
366
367 3
        return $this->request($uri, $method, $options);
368
    }
369
370
    /**
371
     * Request the URI and return the response content.
372
     *
373
     * @param  string  $uri
374
     * @param  string  $method
375
     * @param  array  $options
376
     * @return string|null
377
     */
378 1
    public function fetchContent($uri, $method = 'GET', array $options = [])
379
    {
380 1
        return $this->request($uri, $method, $options)->getContent();
381
    }
382
383
    /**
384
     * Request the URI and return the JSON decoded response content.
385
     *
386
     * @param  string  $uri
387
     * @param  string  $method
388
     * @param  array  $options
389
     * @param  bool  $assoc
390
     * @return mixed
391
     */
392 1
    public function fetchJson($uri, $method = 'GET', array $options = [], $assoc = true)
393
    {
394 1
        return $this->requestJson($uri, $method, $options)->getJson($assoc);
395
    }
396
397
    /**
398
     * Dynamically methods to set request option, send request, or get
399
     * response properties.
400
     *
401
     * @param  string  $method
402
     * @param  array  $args
403
     * @return mixed
404
     */
405 4
    public function __call($method, $args)
406
    {
407
        // Handle magic request methods
408 4
        if (in_array($method, ['get', 'head', 'put', 'post', 'patch', 'delete'])) {
409 2
            if (count($args) < 1) {
410
                throw new InvalidArgumentException('Magic request methods require an URI and optional options array');
411
            }
412
413 2
            $url = $args[0];
414 2
            $options = isset($args[1]) ? $args[1] : [];
415
416 2
            return $this->request($url, $method, $options);
417
        }
418
419
        // Handle setting request options
420 2
        return $this->option(Str::snake($method), $args[0]);
421
    }
422
}
423