overtrue /
http
| 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 | |||
| 17 | /** |
||
| 18 | * Trait HasHttpRequests. |
||
| 19 | */ |
||
| 20 | trait HasHttpRequests |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * @var \GuzzleHttp\ClientInterface |
||
| 24 | */ |
||
| 25 | protected $httpClient; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var array |
||
| 29 | */ |
||
| 30 | protected static $defaults = [ |
||
| 31 | 'curl' => [ |
||
| 32 | CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, |
||
| 33 | ], |
||
| 34 | ]; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Set guzzle default settings. |
||
| 38 | * |
||
| 39 | * @param array $defaults |
||
| 40 | */ |
||
| 41 | public static function setDefaultOptions($defaults = []) |
||
| 42 | { |
||
| 43 | self::$defaults = $defaults; |
||
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * Return current guzzle default settings. |
||
| 48 | * |
||
| 49 | * @return array |
||
| 50 | */ |
||
| 51 | public static function getDefaultOptions(): array |
||
| 52 | { |
||
| 53 | return self::$defaults; |
||
| 54 | } |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Set GuzzleHttp\Client. |
||
| 58 | * |
||
| 59 | * @param \GuzzleHttp\ClientInterface $httpClient |
||
| 60 | * |
||
| 61 | * @return $this |
||
| 62 | */ |
||
| 63 | public function setHttpClient(ClientInterface $httpClient) |
||
| 64 | { |
||
| 65 | $this->httpClient = $httpClient; |
||
| 66 | |||
| 67 | return $this; |
||
| 68 | } |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Return GuzzleHttp\Client instance. |
||
| 72 | * |
||
| 73 | * @return \GuzzleHttp\ClientInterface |
||
| 74 | */ |
||
| 75 | public function getHttpClient(): ClientInterface |
||
| 76 | { |
||
| 77 | if (!$this->httpClient) { |
||
| 78 | $this->httpClient = new Client(['handler' => $this->getHandlerStack()]); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 79 | } |
||
| 80 | |||
| 81 | return $this->httpClient; |
||
| 82 | } |
||
| 83 | |||
| 84 | /** |
||
| 85 | * Make a request. |
||
| 86 | * |
||
| 87 | * @param string $uri |
||
| 88 | * @param string $method |
||
| 89 | * @param array $options |
||
| 90 | * @param bool $async |
||
| 91 | * |
||
| 92 | * @return \Psr\Http\Message\ResponseInterface|\GuzzleHttp\Promise\Promise |
||
| 93 | */ |
||
| 94 | public function request($uri, $method = 'GET', $options = [], bool $async = false) |
||
| 95 | { |
||
| 96 | return $this->getHttpClient()->{ $async ? 'requestAsync' : 'request' }(strtoupper($method), $uri, array_merge(self::$defaults, $options)); |
||
| 97 | } |
||
| 98 | } |
||
| 99 |