HasHttpRequests::pushMiddleware()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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