-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathBaiduHttpClient.php
317 lines (282 loc) · 9.99 KB
/
BaiduHttpClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
<?php
namespace BaiduMiniProgram\Client;
use Http\Client\Exception;
use Http\Client\HttpClient;
use Http\Message\Builder\ResponseBuilder;
use Http\Message\MessageFactory;
use Http\Message\MessageFactory\GuzzleMessageFactory;
use Http\Message\StreamFactory;
use Http\Message\StreamFactory\GuzzleStreamFactory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @link https://github.com/php-http/curl-client/blob/master/src/Client.php
*/
class BaiduHttpClient implements HttpClient
{
/**
* cURL options.
*
* @var array
*/
private $options;
/**
* PSR-7 message factory.
*
* @var MessageFactory
*/
private $messageFactory;
/**
* PSR-7 stream factory.
*
* @var StreamFactory
*/
private $streamFactory;
/**
* cURL synchronous requests handle.
*
* @var resource|null
*/
private $handle = null;
/**
* Create new client.
*
* @param array $options cURL options {@link http://php.net/curl_setopt}
*/
public function __construct(array $options = [])
{
$this->messageFactory = new GuzzleMessageFactory();
$this->streamFactory = new GuzzleStreamFactory();
$this->options = $options;
}
/**
* Release resources if still active.
*/
public function __destruct()
{
if (is_resource($this->handle)) {
curl_close($this->handle);
}
}
/**
* Sends a PSR-7 request.
*
* @param RequestInterface $request
*
* @throws \Http\Client\Exception\NetworkException In case of network problems
* @throws \Http\Client\Exception\RequestException On invalid request
* @throws \InvalidArgumentException For invalid header names or values
* @throws \RuntimeException If creating the body stream fails
*
* @return ResponseInterface
*/
public function sendRequest(RequestInterface $request)
{
$responseBuilder = $this->createResponseBuilder();
$options = $this->createCurlOptions($request, $responseBuilder);
if (is_resource($this->handle)) {
if (function_exists('curl_reset')) {
curl_reset($this->handle);
} else {
curl_close($this->handle);
$this->handle = curl_init();
}
} else {
$this->handle = curl_init();
}
curl_setopt_array($this->handle, $options);
curl_exec($this->handle);
$errno = curl_errno($this->handle);
switch ($errno) {
case CURLE_OK:
// All OK, no actions needed.
break;
case CURLE_COULDNT_RESOLVE_PROXY:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_COULDNT_CONNECT:
case CURLE_OPERATION_TIMEOUTED:
case CURLE_SSL_CONNECT_ERROR:
throw new Exception\NetworkException(curl_error($this->handle), $request);
default:
throw new Exception\RequestException(curl_error($this->handle), $request);
}
$response = $responseBuilder->getResponse();
$response->getBody()->seek(0);
return $response;
}
/**
* Generates cURL options.
*
* @param RequestInterface $request
* @param ResponseBuilder $responseBuilder
*
* @throws \Http\Client\Exception\RequestException On invalid request
* @throws \InvalidArgumentException For invalid header names or values
* @throws \RuntimeException If can not read body
*
* @return array
*/
private function createCurlOptions(RequestInterface $request, ResponseBuilder $responseBuilder)
{
$options = $this->options;
$options[CURLOPT_HEADER] = false;
$options[CURLOPT_RETURNTRANSFER] = false;
$options[CURLOPT_FOLLOWLOCATION] = false;
try {
$options[CURLOPT_HTTP_VERSION]
= $this->getProtocolVersion($request->getProtocolVersion());
} catch (\UnexpectedValueException $e) {
throw new Exception\RequestException($e->getMessage(), $request);
}
$options[CURLOPT_URL] = (string) $request->getUri();
$options = $this->addRequestBodyOptions($request, $options);
$options[CURLOPT_HTTPHEADER] = $this->createHeaders($request, $options);
if ($request->getUri()->getUserInfo()) {
$options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
}
$options[CURLOPT_HEADERFUNCTION] = function ($ch, $data) use ($responseBuilder) {
$str = trim($data);
if ('' !== $str) {
if (strpos(strtolower($str), 'http/') === 0) {
$responseBuilder->setStatus($str)->getResponse();
} else {
$responseBuilder->addHeader($str);
}
}
return strlen($data);
};
$options[CURLOPT_WRITEFUNCTION] = function ($ch, $data) use ($responseBuilder) {
return $responseBuilder->getResponse()->getBody()->write($data);
};
return $options;
}
/**
* Return cURL constant for specified HTTP version.
*
* @param string $requestVersion
*
* @throws \UnexpectedValueException If unsupported version requested
*
* @return int
*/
private function getProtocolVersion($requestVersion)
{
switch ($requestVersion) {
case '1.0':
return CURL_HTTP_VERSION_1_0;
case '1.1':
return CURL_HTTP_VERSION_1_1;
case '2.0':
if (defined('CURL_HTTP_VERSION_2_0')) {
return CURL_HTTP_VERSION_2_0;
}
throw new \UnexpectedValueException('libcurl 7.33 needed for HTTP 2.0 support');
}
return CURL_HTTP_VERSION_NONE;
}
/**
* Add request body related cURL options.
*
* @param RequestInterface $request
* @param array $options
*
* @return array
*/
private function addRequestBodyOptions(RequestInterface $request, array $options)
{
/*
* Some HTTP methods cannot have payload:
*
* - GET — cURL will automatically change method to PUT or POST if we set CURLOPT_UPLOAD or
* CURLOPT_POSTFIELDS.
* - HEAD — cURL treats HEAD as GET request with a same restrictions.
* - TRACE — According to RFC7231: a client MUST NOT send a message body in a TRACE request.
*/
if (!in_array($request->getMethod(), ['GET', 'HEAD', 'TRACE'], true)) {
$body = $request->getBody();
$bodySize = $body->getSize();
if ($bodySize !== 0) {
if ($body->isSeekable()) {
$body->rewind();
}
// Message has non empty body.
if (null === $bodySize || $bodySize > 1024 * 1024) {
// Avoid full loading large or unknown size body into memory
$options[CURLOPT_UPLOAD] = true;
if (null !== $bodySize) {
$options[CURLOPT_INFILESIZE] = $bodySize;
}
$options[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
return $body->read($length);
};
} else {
// Small body can be loaded into memory
$options[CURLOPT_POSTFIELDS] = (string) $body;
}
}
}
if ($request->getMethod() === 'HEAD') {
// This will set HTTP method to "HEAD".
$options[CURLOPT_NOBODY] = true;
} elseif ($request->getMethod() !== 'GET') {
// GET is a default method. Other methods should be specified explicitly.
$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
}
return $options;
}
/**
* Create headers array for CURLOPT_HTTPHEADER.
*
* @param RequestInterface $request
* @param array $options cURL options
*
* @return string[]
*/
private function createHeaders(RequestInterface $request, array $options)
{
$curlHeaders = [];
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
$header = strtolower($name);
if ('expect' === $header) {
// curl-client does not support "Expect-Continue", so dropping "expect" headers
continue;
}
if ('content-length' === $header) {
if (array_key_exists(CURLOPT_POSTFIELDS, $options)) {
// Small body content length can be calculated here.
$values = [strlen($options[CURLOPT_POSTFIELDS])];
} elseif (!array_key_exists(CURLOPT_READFUNCTION, $options)) {
// Else if there is no body, forcing "Content-length" to 0
$values = [0];
}
}
foreach ($values as $value) {
$curlHeaders[] = $name.': '.$value;
}
}
/*
* curl-client does not support "Expect-Continue", but cURL adds "Expect" header by default.
* We can not suppress it, but we can set it to empty.
*/
$curlHeaders[] = 'Expect:';
return $curlHeaders;
}
/**
* Create new ResponseBuilder instance.
*
* @throws \RuntimeException If creating the stream from $body fails
*
* @return ResponseBuilder
*/
private function createResponseBuilder()
{
try {
$body = $this->streamFactory->createStream(fopen('php://temp', 'w+b'));
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException('Can not create "php://temp" stream.');
}
$response = $this->messageFactory->createResponse(200, null, [], $body);
return new ResponseBuilder($response);
}
}