1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the overtrue/http. |
5
|
|
|
* |
6
|
|
|
* (c) overtrue <[email protected]> |
7
|
|
|
* |
8
|
|
|
* This source file is subject to the MIT license that is bundled |
9
|
|
|
* with this source code in the file LICENSE. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Overtrue\Http\Traits; |
13
|
|
|
|
14
|
|
|
use GuzzleHttp\Client; |
15
|
|
|
use GuzzleHttp\ClientInterface; |
16
|
|
|
use Psr\Http\Message\ResponseInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Trait HasHttpRequests. |
20
|
|
|
*/ |
21
|
|
|
trait HasHttpRequests |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var \GuzzleHttp\ClientInterface |
25
|
|
|
*/ |
26
|
|
|
protected $httpClient; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var array |
30
|
|
|
*/ |
31
|
|
|
protected static $defaults = [ |
32
|
|
|
'curl' => [ |
33
|
|
|
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, |
34
|
|
|
], |
35
|
|
|
]; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Set guzzle default settings. |
39
|
|
|
* |
40
|
|
|
* @param array $defaults |
41
|
|
|
*/ |
42
|
|
|
public static function setDefaultOptions($defaults = []) |
43
|
|
|
{ |
44
|
|
|
self::$defaults = $defaults; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Return current guzzle default settings. |
49
|
|
|
* |
50
|
|
|
* @return array |
51
|
|
|
*/ |
52
|
|
|
public static function getDefaultOptions(): array |
53
|
|
|
{ |
54
|
|
|
return self::$defaults; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Set GuzzleHttp\Client. |
59
|
|
|
* |
60
|
|
|
* @param \GuzzleHttp\ClientInterface $httpClient |
61
|
|
|
* |
62
|
|
|
* @return $this |
63
|
|
|
*/ |
64
|
|
|
public function setHttpClient(ClientInterface $httpClient) |
65
|
|
|
{ |
66
|
|
|
$this->httpClient = $httpClient; |
67
|
|
|
|
68
|
|
|
return $this; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Return GuzzleHttp\Client instance. |
73
|
|
|
* |
74
|
|
|
* @return \GuzzleHttp\ClientInterface |
75
|
|
|
*/ |
76
|
|
|
public function getHttpClient(): ClientInterface |
77
|
|
|
{ |
78
|
|
|
if (!$this->httpClient) { |
79
|
|
|
$this->httpClient = new Client(['handler' => $this->getHandlerStack()]); |
|
|
|
|
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $this->httpClient; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* Make a request. |
87
|
|
|
* |
88
|
|
|
* @param string $uri |
89
|
|
|
* @param string $method |
90
|
|
|
* @param array $options |
91
|
|
|
* @param bool $async |
92
|
|
|
* |
93
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
94
|
|
|
*/ |
95
|
|
|
public function request($uri, $method = 'GET', $options = [], bool $async = false): ResponseInterface |
96
|
|
|
{ |
97
|
|
|
return $this->getHttpClient()->{ $async ? 'requestAsync' : 'request' }(strtoupper($method), $uri, array_merge(self::$defaults, $options)); |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|