HasHttpRequests::fixJsonIssue()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 16
rs 9.6111
cc 5
nc 3
nop 1
1
<?php
2
3
namespace CloudyCity\KuaishouMarketingSDK\Kernel\Traits;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
use GuzzleHttp\HandlerStack;
8
9
trait HasHttpRequests
10
{
11
    use ResponseCastable;
12
13
    /**
14
     * @var \GuzzleHttp\ClientInterface
15
     */
16
    protected $httpClient;
17
18
    /**
19
     * @var array
20
     */
21
    protected $middlewares = [];
22
23
    /**
24
     * @var \GuzzleHttp\HandlerStack
25
     */
26
    protected $handlerStack;
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()
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\ClientInterface instance.
73
     *
74
     * @return ClientInterface
75
     */
76
    public function getHttpClient()
77
    {
78
        if (!$this->httpClient) {
79
            $this->httpClient = new Client(['handler' => HandlerStack::create($this->getGuzzleHandler())]);
80
        }
81
82
        return $this->httpClient;
83
    }
84
85
    /**
86
     * Add a middleware.
87
     *
88
     * @param callable $middleware
89
     * @param string   $name
90
     *
91
     * @return $this
92
     */
93
    public function pushMiddleware(callable $middleware, $name = null)
94
    {
95
        if (!is_null($name)) {
96
            $this->middlewares[$name] = $middleware;
97
        } else {
98
            array_push($this->middlewares, $middleware);
99
        }
100
101
        return $this;
102
    }
103
104
    /**
105
     * Return all middlewares.
106
     *
107
     * @return array
108
     */
109
    public function getMiddlewares()
110
    {
111
        return $this->middlewares;
112
    }
113
114
    /**
115
     * Make a request.
116
     *
117
     * @param string $url
118
     * @param string $method
119
     * @param array  $options
120
     *
121
     * @throws \GuzzleHttp\Exception\GuzzleException
122
     *
123
     * @return \Psr\Http\Message\ResponseInterface
124
     */
125
    public function request($url, $method = 'GET', array $options = [])
126
    {
127
        $method = strtoupper($method);
128
        $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]);
129
        $options = $this->fixJsonIssue($options);
130
        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
131
            $options['base_uri'] = $this->baseUri;
132
        }
133
        $response = $this->getHttpClient()->request($method, $url, $options);
134
        $response->getBody()->rewind();
135
136
        return $response;
137
    }
138
139
    /**
140
     * @param \GuzzleHttp\HandlerStack $handlerStack
141
     *
142
     * @return $this
143
     */
144
    public function setHandlerStack(HandlerStack $handlerStack)
145
    {
146
        $this->handlerStack = $handlerStack;
147
148
        return $this;
149
    }
150
151
    /**
152
     * Build a handler stack.
153
     *
154
     * @return \GuzzleHttp\HandlerStack
155
     */
156
    public function getHandlerStack()
157
    {
158
        if ($this->handlerStack) {
159
            return $this->handlerStack;
160
        }
161
        $this->handlerStack = HandlerStack::create($this->getGuzzleHandler());
162
        foreach ($this->middlewares as $name => $middleware) {
163
            $this->handlerStack->push($middleware, $name);
164
        }
165
166
        return $this->handlerStack;
167
    }
168
169
    /**
170
     * @param array $options
171
     *
172
     * @return array
173
     */
174
    protected function fixJsonIssue(array $options)
175
    {
176
        if (isset($options['json']) && is_array($options['json'])) {
177
            $options['headers'] = array_merge(
178
                isset($options['headers']) ? $options['headers'] : [],
179
                ['Content-Type' => 'application/json']
180
            );
181
            if (empty($options['json'])) {
182
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_FORCE_OBJECT);
183
            } else {
184
                $options['body'] = \GuzzleHttp\json_encode($options['json'], JSON_UNESCAPED_UNICODE);
185
            }
186
            unset($options['json']);
187
        }
188
189
        return $options;
190
    }
191
192
    /**
193
     * Get guzzle handler.
194
     *
195
     * @return callable
196
     */
197
    protected function getGuzzleHandler()
198
    {
199
        return \GuzzleHttp\choose_handler();
200
    }
201
}
202