Http   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 242
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 70.67%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 8
dl 0
loc 242
ccs 53
cts 75
cp 0.7067
rs 10
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setClient() 0 6 1
A getClient() 0 15 2
A buildUri() 0 4 1
A request() 0 20 2
A get() 0 4 1
A post() 0 6 2
A delete() 0 4 1
A put() 0 4 1
A upload() 0 17 3
A parseJSON() 0 17 4
A addMiddleware() 0 6 1
A clearMiddlewares() 0 6 1
A getHandler() 0 10 2
1
<?php
2
3
/*
4
 * This file is part of the light/easemob.
5
 *
6
 * (c) lichunqiang <[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 light\Easemob\Core;
13
14
use GuzzleHttp\Client as HttpClient;
15
use GuzzleHttp\Exception\RequestException;
16
use GuzzleHttp\HandlerStack;
17
use GuzzleHttp\Psr7;
18
use GuzzleHttp\Psr7\Request;
19
use light\Easemob\Exception\HttpException;
20
use light\Easemob\Support\Log;
21
use Psr\Http\Message\ResponseInterface;
22
23
class Http
24
{
25
    /**
26
     * @var string The base request url.
27
     */
28
    protected $baseUri;
29
    /**
30
     * @var \GuzzleHttp\Client
31
     */
32
    protected $client;
33
    /**
34
     * @var array The middlewares.
35
     */
36
    protected $middlewares = [];
37
38 4
    public function __construct($baseUri)
39
    {
40 4
        $this->baseUri = $baseUri;
41 4
    }
42
43
    /**
44
     * Set http client.
45
     *
46
     * @param HttpClient $client
47
     *
48
     * @return $this
49
     */
50
    public function setClient(HttpClient $client)
51
    {
52
        $this->client = $client;
53
54
        return $this;
55
    }
56
57
    /**
58
     * Get http client.
59
     *
60
     * @return \GuzzleHttp\Client
61
     */
62 4
    public function getClient()
63
    {
64 4
        if (!($this->client instanceof HttpClient)) {
65 4
            $this->client = new HttpClient([
66 4
                'base_uri' => $this->baseUri,
67 4
                'verify' => false,
68
                'headers' => [
69 4
                    'Content-Type' => 'application/json',
70 4
                    'Accept' => 'application/json',
71 4
                ],
72 4
            ]);
73 4
        }
74
75 4
        return $this->client;
76
    }
77
78
    /**
79
     * @param string $path
80
     *
81
     * @return \Psr\Http\Message\UriInterface
82
     */
83
    public function buildUri($path)
84
    {
85
        return Psr7\Uri::resolve(Psr7\uri_for($this->baseUri), $path);
86
    }
87
88
    /**
89
     * Make request.
90
     *
91
     * @param string $url
92
     * @param string $method
93
     * @param array  $options
94
     *
95
     * @return mixed
96
     */
97 4
    public function request($url, $method = 'GET', $options = [])
98
    {
99 4
        $method = strtoupper($method);
100
101 4
        $options['handler'] = $this->getHandler();
102
103
        try {
104 4
            $response = $this->getClient()->request($method, $url, $options);
105 4
        } catch (RequestException $e) {
106 3
            $response = $e->getResponse();
107 3
            Log::error('Http Exception', [
108 3
                'uri' => $url,
109 3
                'method' => $method,
110 3
                'response' => (string) $response->getBody(),
111 3
                'request' => (string) $e->getRequest()->getUri(),
112 3
            ]);
113
        }
114
115 4
        return $response;
116
    }
117
118
    /**
119
     * Send a get request.
120
     *
121
     * @param string $url
122
     * @param array  $options
123
     *
124
     * @return mixed
125
     */
126 3
    public function get($url, array $options = [])
127
    {
128 3
        return $this->request($url, 'GET', ['query' => $options]);
129
    }
130
131
    /**
132
     * Send a post request.
133
     *
134
     * @param string $url
135
     * @param array  $options
136
     *
137
     * @return mixed
138
     */
139 3
    public function post($url, $options = [])
140
    {
141 3
        $options = is_array($options) ? json_encode($options, JSON_UNESCAPED_UNICODE) : $options;
142
143 3
        return $this->request($url, 'POST', ['body' => $options]);
144
    }
145
146
    /**
147
     * Send a delete request.
148
     *
149
     * @param string $url
150
     * @param array  $options
151
     *
152
     * @return mixed
153
     */
154 3
    public function delete($url, $options = [])
155
    {
156 3
        return $this->request($url, 'DELETE', $options);
157
    }
158
159
    /**
160
     * Send a put request.
161
     *
162
     * @param string $url
163
     * @param array  $options
164
     *
165
     * @return mixed
166
     */
167
    public function put($url, $options = [])
168
    {
169
        return $this->request($url, 'PUT', $options);
170
    }
171
172
    /**
173
     * Upload file.
174
     *
175
     * @param string $url
176
     * @param array  $files
177
     * @param array  $form
178
     * @param array  $queries
179
     *
180
     * @return ResponseInterface
181
     */
182
    public function upload($url, array $files = [], array $form = [], array $queries = [])
183
    {
184
        $multipart = [];
185
186
        foreach ($files as $name => $path) {
187
            $multipart[] = [
188
                'name' => $name,
189
                'contents' => fopen($path, 'r'),
190
            ];
191
        }
192
193
        foreach ($form as $name => $contents) {
194
            $multipart[] = compact('name', 'contents');
195
        }
196
197
        return $this->request($url, 'POST', ['query' => $queries, 'multipart' => $multipart]);
198
    }
199
200
    /**
201
     * Parse json data.
202
     *
203
     * @param string|ResponseInterface $body
204
     * @param bool                     $throws
205
     *
206
     * @throws HttpException
207
     *
208
     * @return array
209
     */
210 3
    public function parseJSON($body, $throws = true)
211
    {
212 3
        if ($body instanceof ResponseInterface) {
213 2
            $body = $body->getBody();
214 2
        }
215
216 3
        $contents = json_decode($body, true);
217
218 3
        if (JSON_ERROR_NONE !== json_last_error()) {
219
            Log::error('Failed to parse JSON.', ['body' => $body]);
220
            if ($throws) {
221
                throw new HttpException('Failed to parse JSON.', json_last_error());
222
            }
223
        }
224
225 3
        return $contents;
226
    }
227
228
    /**
229
     * Add a middleware.
230
     *
231
     * @param callable $middleware
232
     *
233
     * @return $this
234
     */
235 3
    public function addMiddleware(callable $middleware)
236
    {
237 3
        array_push($this->middlewares, $middleware);
238
239 3
        return $this;
240
    }
241
242 1
    public function clearMiddlewares()
243
    {
244 1
        $this->middlewares = [];
245
246 1
        return $this;
247
    }
248
249
    /**
250
     * Build a handler.
251
     *
252
     * @return HandlerStack
253
     */
254 4
    protected function getHandler()
255
    {
256 4
        $stack = HandlerStack::create();
257
258 4
        foreach ($this->middlewares as $middleware) {
259 3
            $stack->push($middleware);
260 4
        }
261
262 4
        return $stack;
263
    }
264
}
265