Completed
Push — master ( d81dc0...216ea6 )
by Elf
01:18
created

HttpClient::getHeader()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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