forked from yiisoft/yii2-httpclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.php
409 lines (377 loc) · 13.4 KB
/
Client.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\httpclient;
use yii\base\Component;
use Yii;
use yii\base\InvalidParamException;
use yii\helpers\StringHelper;
/**
* Client provide high level interface for HTTP requests execution.
*
* @property Transport $transport HTTP message transport instance. Note that the type of this property differs
* in getter and setter. See [[getTransport()]] and [[setTransport()]] for details.
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 2.0
*/
class Client extends Component
{
/**
* @event RequestEvent an event raised right before sending request.
*/
const EVENT_BEFORE_SEND = 'beforeSend';
/**
* @event RequestEvent an event raised right after request has been sent.
*/
const EVENT_AFTER_SEND = 'afterSend';
/**
* JSON format
*/
const FORMAT_JSON = 'json';
/**
* urlencoded by RFC1738 query string, like name1=value1&name2=value2
* @see http://php.net/manual/en/function.urlencode.php
*/
const FORMAT_URLENCODED = 'urlencoded';
/**
* urlencoded by PHP_QUERY_RFC3986 query string, like name1=value1&name2=value2
* @see http://php.net/manual/en/function.rawurlencode.php
*/
const FORMAT_RAW_URLENCODED = 'raw-urlencoded';
/**
* XML format
*/
const FORMAT_XML = 'xml';
/**
* @var string base request URL.
*/
public $baseUrl;
/**
* @var array the formatters for converting data into the content of the specified [[format]].
* The array keys are the format names, and the array values are the corresponding configurations
* for creating the formatter objects.
*/
public $formatters = [];
/**
* @var array the parsers for converting content of the specified [[format]] into the data.
* The array keys are the format names, and the array values are the corresponding configurations
* for creating the parser objects.
*/
public $parsers = [];
/**
* @var array request object configuration.
*/
public $requestConfig = [];
/**
* @var array response config configuration.
*/
public $responseConfig = [];
/**
* @var int maximum symbols count of the request content, which should be taken to compose a
* log and profile messages. Exceeding content will be truncated.
* @see createRequestLogToken()
*/
public $contentLoggingMaxSize = 2000;
/**
* @var Transport|array|string|callable HTTP message transport.
*/
private $_transport = 'yii\httpclient\StreamTransport';
/**
* Sets the HTTP message transport. It can be specified in one of the following forms:
*
* - an instance of `Transport`: actual transport object to be used
* - a string: representing the class name of the object to be created
* - a configuration array: the array must contain a `class` element which is treated as the object class,
* and the rest of the name-value pairs will be used to initialize the corresponding object properties
* - a PHP callable: either an anonymous function or an array representing a class method (`[$class or $object, $method]`).
* The callable should return a new instance of the object being created.
* @param Transport|array|string $transport HTTP message transport
*/
public function setTransport($transport)
{
$this->_transport = $transport;
}
/**
* @return Transport HTTP message transport instance.
*/
public function getTransport()
{
if (!is_object($this->_transport)) {
$this->_transport = Yii::createObject($this->_transport);
}
return $this->_transport;
}
/**
* Returns HTTP message formatter instance for the specified format.
* @param string $format format name.
* @return FormatterInterface formatter instance.
* @throws InvalidParamException on invalid format name.
*/
public function getFormatter($format)
{
static $defaultFormatters = [
self::FORMAT_JSON => 'yii\httpclient\JsonFormatter',
self::FORMAT_URLENCODED => [
'class' => 'yii\httpclient\UrlEncodedFormatter',
'encodingType' => PHP_QUERY_RFC1738
],
self::FORMAT_RAW_URLENCODED => [
'class' => 'yii\httpclient\UrlEncodedFormatter',
'encodingType' => PHP_QUERY_RFC3986
],
self::FORMAT_XML => 'yii\httpclient\XmlFormatter',
];
if (!isset($this->formatters[$format])) {
if (!isset($defaultFormatters[$format])) {
throw new InvalidParamException("Unrecognized format '{$format}'");
}
$this->formatters[$format] = $defaultFormatters[$format];
}
if (!is_object($this->formatters[$format])) {
$this->formatters[$format] = Yii::createObject($this->formatters[$format]);
}
return $this->formatters[$format];
}
/**
* Returns HTTP message parser instance for the specified format.
* @param string $format format name
* @return ParserInterface parser instance.
* @throws InvalidParamException on invalid format name.
*/
public function getParser($format)
{
static $defaultParsers = [
self::FORMAT_JSON => 'yii\httpclient\JsonParser',
self::FORMAT_URLENCODED => 'yii\httpclient\UrlEncodedParser',
self::FORMAT_RAW_URLENCODED => 'yii\httpclient\UrlEncodedParser',
self::FORMAT_XML => 'yii\httpclient\XmlParser',
];
if (!isset($this->parsers[$format])) {
if (!isset($defaultParsers[$format])) {
throw new InvalidParamException("Unrecognized format '{$format}'");
}
$this->parsers[$format] = $defaultParsers[$format];
}
if (!is_object($this->parsers[$format])) {
$this->parsers[$format] = Yii::createObject($this->parsers[$format]);
}
return $this->parsers[$format];
}
/**
* @return Request request instance.
*/
public function createRequest()
{
$config = $this->requestConfig;
if (!isset($config['class'])) {
$config['class'] = Request::className();
}
$config['client'] = $this;
return Yii::createObject($config);
}
/**
* Creates a response instance.
* @param string $content raw content
* @param array $headers headers list.
* @return Response request instance.
*/
public function createResponse($content = null, array $headers = [])
{
$config = $this->responseConfig;
if (!isset($config['class'])) {
$config['class'] = Response::className();
}
$config['client'] = $this;
$response = Yii::createObject($config);
$response->setContent($content);
$response->setHeaders($headers);
return $response;
}
/**
* Performs given request.
* @param Request $request request to be sent.
* @return Response response instance.
* @throws Exception on failure.
*/
public function send($request)
{
return $this->getTransport()->send($request);
}
/**
* Performs multiple HTTP requests in parallel.
* This method accepts an array of the [[Request]] objects and returns an array of the [[Response]] objects.
* Keys of the response array correspond the ones from request array.
*
* ```php
* $client = new Client();
* $requests = [
* 'news' => $client->get('http://domain.com/news'),
* 'friends' => $client->get('http://domain.com/user/friends', ['userId' => 12]),
* ];
* $responses = $client->batchSend($requests);
* var_dump($responses['news']->isOk);
* var_dump($responses['friends']->isOk);
* ```
*
* @param Request[] $requests requests to perform.
* @return Response[] responses list.
*/
public function batchSend(array $requests)
{
return $this->getTransport()->batchSend($requests);
}
/**
* Composes the log/profiling message token for the given HTTP request parameters.
* This method should be used by transports during request sending logging.
* @param string $method request method name.
* @param string $url request URL.
* @param array $headers request headers.
* @param string $content request content.
* @return string log token.
*/
public function createRequestLogToken($method, $url, $headers, $content)
{
$token = strtoupper($method) . ' ' . $url;
if (!empty($headers)) {
$token .= "\n" . implode("\n", $headers);
}
if ($content !== null) {
$token .= "\n\n" . StringHelper::truncate($content, $this->contentLoggingMaxSize);
}
return $token;
}
// Create request shortcut methods :
/**
* Creates 'GET' request.
* @param string $url target URL.
* @param array|string $data if array - request data, otherwise - request content.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function get($url, $data = null, $headers = [], $options = [])
{
return $this->createRequestShortcut('get', $url, $data, $headers, $options);
}
/**
* Creates 'POST' request.
* @param string $url target URL.
* @param array|string $data if array - request data, otherwise - request content.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function post($url, $data = null, $headers = [], $options = [])
{
return $this->createRequestShortcut('post', $url, $data, $headers, $options);
}
/**
* Creates 'PUT' request.
* @param string $url target URL.
* @param array|string $data if array - request data, otherwise - request content.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function put($url, $data = null, $headers = [], $options = [])
{
return $this->createRequestShortcut('put', $url, $data, $headers, $options);
}
/**
* Creates 'PATCH' request.
* @param string $url target URL.
* @param array|string $data if array - request data, otherwise - request content.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function patch($url, $data = null, $headers = [], $options = [])
{
return $this->createRequestShortcut('patch', $url, $data, $headers, $options);
}
/**
* Creates 'DELETE' request.
* @param string $url target URL.
* @param array|string $data if array - request data, otherwise - request content.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function delete($url, $data = null, $headers = [], $options = [])
{
return $this->createRequestShortcut('delete', $url, $data, $headers, $options);
}
/**
* Creates 'HEAD' request.
* @param string $url target URL.
* @param array $headers request headers.
* @param array $options request options.
* @return Request request instance.
*/
public function head($url, $headers = [], $options = [])
{
return $this->createRequestShortcut('head', $url, null, $headers, $options);
}
/**
* Creates 'OPTIONS' request.
* @param string $url target URL.
* @param array $options request options.
* @return Request request instance.
*/
public function options($url, $options = [])
{
return $this->createRequestShortcut('options', $url, null, [], $options);
}
/**
* This method is invoked right before request is sent.
* The method will trigger the [[EVENT_BEFORE_SEND]] event.
* @param Request $request request instance.
* @since 2.0.1
*/
public function beforeSend($request)
{
$event = new RequestEvent();
$event->request = $request;
$this->trigger(self::EVENT_BEFORE_SEND, $event);
}
/**
* This method is invoked right after request is sent.
* The method will trigger the [[EVENT_AFTER_SEND]] event.
* @param Request $request request instance.
* @param Response $response received response instance.
* @since 2.0.1
*/
public function afterSend($request, $response)
{
$event = new RequestEvent();
$event->request = $request;
$event->response = $response;
$this->trigger(self::EVENT_AFTER_SEND, $event);
}
/**
* @param string $method
* @param string $url
* @param array|string $data
* @param array $headers
* @param array $options
* @return Request request instance.
*/
private function createRequestShortcut($method, $url, $data, $headers, $options)
{
$request = $this->createRequest()
->setMethod($method)
->setUrl($url)
->addHeaders($headers)
->addOptions($options);
if (is_array($data)) {
$request->setData($data);
} else {
$request->setContent($data);
}
return $request;
}
}