Issues (31)

src/Kernel/Traits/HasHttpRequests.php (2 issues)

1
<?php
2
3
namespace EasyIM\Kernel\Traits;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
use GuzzleHttp\HandlerStack;
8
use Psr\Http\Message\ResponseInterface;
9
10
/**
11
 * Trait HasHttpRequests.
12
 */
13
trait HasHttpRequests
14
{
15
    use ResponseCastable;
16
17
    /**
18
     * @var \GuzzleHttp\ClientInterface
19
     */
20
    protected $httpClient;
21
22
    /**
23
     * @var array
24
     */
25
    protected $middlewares = [];
26
27
    /**
28
     * @var \GuzzleHttp\HandlerStack
29
     */
30
    protected $handlerStack;
31
32
    /**
33
     * @var array
34
     */
35
    protected static $defaults = [
36
        'curl' => [
37
            CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
38
        ],
39
    ];
40
41
    /**
42
     * Set guzzle default settings.
43
     *
44
     * @param array $defaults
45
     */
46 1
    public static function setDefaultOptions($defaults = [])
47
    {
48 1
        self::$defaults = $defaults;
49 1
    }
50
51
    /**
52
     * Return current guzzle default settings.
53
     *
54
     * @return array
55
     */
56 1
    public static function getDefaultOptions(): array
57
    {
58 1
        return self::$defaults;
59
    }
60
61
    /**
62
     * Set GuzzleHttp\Client.
63
     *
64
     * @param \GuzzleHttp\ClientInterface $httpClient
65
     *
66
     * @return $this
67
     */
68 3
    public function setHttpClient(ClientInterface $httpClient)
69
    {
70 3
        $this->httpClient = $httpClient;
71
72 3
        return $this;
73
    }
74
75
    /**
76
     * Return GuzzleHttp\ClientInterface instance.
77
     *
78
     * @return ClientInterface
79
     */
80 4
    public function getHttpClient(): ClientInterface
81
    {
82 4
        if (!($this->httpClient instanceof ClientInterface)) {
0 ignored issues
show
$this->httpClient is always a sub-type of GuzzleHttp\ClientInterface.
Loading history...
83 2
            if (property_exists($this, 'app') && $this->app['http_client']) {
84 1
                $this->httpClient = $this->app['http_client'];
85
            } else {
86 1
                $this->httpClient = new Client(['handler' => HandlerStack::create($this->getGuzzleHandler())]);
87
            }
88
        }
89
90 4
        return $this->httpClient;
91
    }
92
93
    /**
94
     * Add a middleware.
95
     *
96
     * @param callable $middleware
97
     * @param string   $name
98
     *
99
     * @return $this
100
     */
101 2
    public function pushMiddleware(callable $middleware, string $name = null)
102
    {
103 2
        if (!is_null($name)) {
104 2
            $this->middlewares[$name] = $middleware;
105
        } else {
106 1
            array_push($this->middlewares, $middleware);
107
        }
108
109 2
        return $this;
110
    }
111
112
    /**
113
     * Return all middlewares.
114
     *
115
     * @return array
116
     */
117 1
    public function getMiddlewares(): array
118
    {
119 1
        return $this->middlewares;
120
    }
121
122
    /**
123
     * Make a request.
124
     *
125
     * @param string $url
126
     * @param string $method
127
     * @param array  $options
128
     *
129
     * @return \Psr\Http\Message\ResponseInterface
130
     *
131
     * @throws \GuzzleHttp\Exception\GuzzleException
132
     */
133 2
    public function request($url, $method = 'GET', $options = []): ResponseInterface
134
    {
135 2
        $method = strtoupper($method);
136
137 2
        $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]);
138
139 2
        $options = $this->fixJsonIssue($options);
140
141 2
        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
142 2
            $options['base_uri'] = $this->baseUri;
143
        }
144
145 2
        $response = $this->getHttpClient()->request($method, $url, $options);
146 2
        $response->getBody()->rewind();
147
148 2
        return $response;
149
    }
150
151
    /**
152
     * @param \GuzzleHttp\HandlerStack $handlerStack
153
     *
154
     * @return $this
155
     */
156 1
    public function setHandlerStack(HandlerStack $handlerStack)
157
    {
158 1
        $this->handlerStack = $handlerStack;
159
160 1
        return $this;
161
    }
162
163
    /**
164
     * Build a handler stack.
165
     *
166
     * @return \GuzzleHttp\HandlerStack
167
     */
168 1
    public function getHandlerStack(): HandlerStack
169
    {
170 1
        if ($this->handlerStack) {
171 1
            return $this->handlerStack;
172
        }
173
174 1
        $this->handlerStack = HandlerStack::create($this->getGuzzleHandler());
175
176 1
        foreach ($this->middlewares as $name => $middleware) {
177 1
            $this->handlerStack->push($middleware, $name);
178
        }
179
180 1
        return $this->handlerStack;
181
    }
182
183
    /**
184
     * @param array $options
185
     *
186
     * @return array
187
     */
188 2
    protected function fixJsonIssue(array $options): array
189
    {
190 2
        if (isset($options['json']) && is_array($options['json'])) {
191 1
            $options['headers'] = array_merge($options['headers'] ?? [], ['Content-Type' => 'application/json']);
192
193 1
            if (empty($options['json'])) {
194 1
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_FORCE_OBJECT);
195
            } else {
196 1
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_UNESCAPED_UNICODE);
197
            }
198
199 1
            unset($options['json']);
200
        }
201
202 2
        return $options;
203
    }
204
205
    /**
206
     * Get guzzle handler.
207
     *
208
     * @return callable
209
     */
210 2
    protected function getGuzzleHandler()
211
    {
212 2
        if (property_exists($this, 'app') && isset($this->app['guzzle_handler'])) {
213
            return is_string($handler = $this->app->raw('guzzle_handler'))
0 ignored issues
show
Bug Best Practice introduced by
The expression return is_string($handle...w $handler() : $handler also could return the type object which is incompatible with the documented return type callable.
Loading history...
214
                        ? new $handler()
215
                        : $handler;
216
        }
217
218 2
        return \GuzzleHttp\choose_handler();
219
    }
220
}
221