Completed
Push — master ( 42b611...b70ab3 )
by light
02:44
created

Http::put()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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