HasHttpRequests::getGuzzleHandler()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 2
nop 0
dl 0
loc 10
ccs 0
cts 8
cp 0
crap 20
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Kaylyu\Alipay\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
    public static function setDefaultOptions($defaults = [])
47
    {
48
        self::$defaults = $defaults;
49
    }
50
51
    /**
52
     * Return current guzzle default settings.
53
     *
54
     * @return array
55
     */
56
    public static function getDefaultOptions(): array
57
    {
58
        return self::$defaults;
59
    }
60
61
    /**
62
     * Set GuzzleHttp\Product.
63
     *
64
     * @param \GuzzleHttp\ClientInterface $httpClient
65
     *
66
     * @return $this
67
     */
68
    public function setHttpClient(ClientInterface $httpClient)
69
    {
70
        $this->httpClient = $httpClient;
71
72
        return $this;
73
    }
74
75
    /**
76
     * Return GuzzleHttp\ClientInterface instance.
77
     *
78
     * @return ClientInterface
79
     */
80
    public function getHttpClient(): ClientInterface
81
    {
82
        if (!($this->httpClient instanceof ClientInterface)) {
83
            if (property_exists($this, 'app') && $this->app['http_client']) {
84
                $this->httpClient = $this->app['http_client'];
0 ignored issues
show
Bug introduced by
The property app does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
85
            } else {
86
                $this->httpClient = new Client(['handler' => HandlerStack::create($this->getGuzzleHandler())]);
87
            }
88
        }
89
90
        return $this->httpClient;
91
    }
92
93
    /**
94
     * Add a middleware.
95
     *
96
     * @param callable    $middleware
97
     * @param string|null $name
98
     *
99
     * @return $this
100
     */
101
    public function pushMiddleware(callable $middleware, string $name = null)
102
    {
103
        if (!is_null($name)) {
104
            $this->middlewares[$name] = $middleware;
105
        } else {
106
            array_push($this->middlewares, $middleware);
107
        }
108
109
        return $this;
110
    }
111
112
    /**
113
     * Return all middlewares.
114
     *
115
     * @return array
116
     */
117
    public function getMiddlewares(): array
118
    {
119
        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|\Kaylyu\Alipay\Kernel\Support\Collection|array|object|string
130
     */
131
    public function request($url, $method = 'GET', $options = []): ResponseInterface
132
    {
133
        $method = strtoupper($method);
134
135
        $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]);
136
137
        $options = $this->fixJsonIssue($options);
138
139
        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
140
            $options['base_uri'] = $this->baseUri;
0 ignored issues
show
Bug introduced by
The property baseUri does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
141
        }
142
143
        $response = $this->getHttpClient()->request($method, $url, $options);
144
        $response->getBody()->rewind();
145
146
        return $response;
147
    }
148
149
    /**
150
     * @param \GuzzleHttp\HandlerStack $handlerStack
151
     *
152
     * @return $this
153
     */
154
    public function setHandlerStack(HandlerStack $handlerStack)
155
    {
156
        $this->handlerStack = $handlerStack;
157
158
        return $this;
159
    }
160
161
    /**
162
     * Build a handler stack.
163
     *
164
     * @return \GuzzleHttp\HandlerStack
165
     */
166
    public function getHandlerStack(): HandlerStack
167
    {
168
        if ($this->handlerStack) {
169
            return $this->handlerStack;
170
        }
171
172
        $this->handlerStack = HandlerStack::create($this->getGuzzleHandler());
173
174
        foreach ($this->middlewares as $name => $middleware) {
175
            $this->handlerStack->push($middleware, $name);
176
        }
177
178
        return $this->handlerStack;
179
    }
180
181
    /**
182
     * @param array $options
183
     *
184
     * @return array
185
     */
186
    protected function fixJsonIssue(array $options): array
187
    {
188
        if (isset($options['json']) && is_array($options['json'])) {
189
            $options['headers'] = array_merge($options['headers'] ?? [], ['Content-Type' => 'application/json']);
190
191
            if (empty($options['json'])) {
192
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_FORCE_OBJECT);
193
            } else {
194
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_UNESCAPED_UNICODE);
195
            }
196
197
            unset($options['json']);
198
        }
199
200
        return $options;
201
    }
202
203
    /**
204
     * Get guzzle handler.
205
     *
206
     * @return callable
207
     */
208
    protected function getGuzzleHandler()
209
    {
210
        if (property_exists($this, 'app') && isset($this->app['guzzle_handler']) && is_string($this->app['guzzle_handler'])) {
211
            $handler = $this->app['guzzle_handler'];
212
213
            return new $handler();
214
        }
215
216
        return \GuzzleHttp\choose_handler();
217
    }
218
}
219