forked from yiisoft/yii2-httpclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequest.php
492 lines (443 loc) · 14.9 KB
/
Request.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\httpclient;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
/**
* Request represents HTTP request.
*
* @property string $fullUrl Full target URL.
* @property string $method Request method.
* @property array $options Request options. This property is read-only.
* @property string|array $url Target URL or URL parameters.
*
* @author Paul Klimov <[email protected]>
* @since 2.0
*/
class Request extends Message
{
/**
* @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';
/**
* @var string|array target URL.
*/
private $_url;
/**
* @var string|null full target URL.
*/
private $_fullUrl;
/**
* @var string request method.
*/
private $_method = 'get';
/**
* @var array request options.
*/
private $_options = [];
/**
* @var bool whether request object has been prepared for sending or not.
* @see prepare()
*/
private $isPrepared = false;
/**
* Sets target URL.
* @param string|array $url use a string to represent a URL (e.g. `http://some-domain.com`, `item/list`),
* or an array to represent a URL with query parameters (e.g. `['item/list', 'param1' => 'value1']`).
* @return $this self reference.
*/
public function setUrl($url)
{
$this->_url = $url;
$this->_fullUrl = null;
return $this;
}
/**
* Returns target URL.
* @return string|array target URL or URL parameters
*/
public function getUrl()
{
return $this->_url;
}
/**
* Sets full target URL.
* This method can be use during request formatting and preparation.
* Do not use it for the target URL specification, use [[setUrl()]] instead.
* @param string $fullUrl full target URL.
* @since 2.0.3
*/
public function setFullUrl($fullUrl)
{
$this->_fullUrl = $fullUrl;
}
/**
* Returns full target URL, including [[Client::baseUrl]] as a string.
* @return string full target URL.
*/
public function getFullUrl()
{
if ($this->_fullUrl === null) {
$this->_fullUrl = $this->createFullUrl($this->getUrl());
}
return $this->_fullUrl;
}
/**
* @param string $method request method
* @return $this self reference.
*/
public function setMethod($method)
{
$this->_method = $method;
return $this;
}
/**
* @return string request method
*/
public function getMethod()
{
return $this->_method;
}
/**
* Following options are supported:
* - timeout: int, the maximum number of seconds to allow request to be executed.
* - proxy: string, URI specifying address of proxy server. (e.g. tcp://proxy.example.com:5100).
* - userAgent: string, the contents of the "User-Agent: " header to be used in a HTTP request.
* - followLocation: bool, whether to follow any "Location: " header that the server sends as part of the HTTP header.
* - maxRedirects: int, the max number of redirects to follow.
* - protocolVersion: float|string, HTTP protocol version.
* - sslVerifyPeer: bool, whether verification of the peer's certificate should be performed.
* - sslCafile: string, location of Certificate Authority file on local filesystem which should be used with
* the 'sslVerifyPeer' option to authenticate the identity of the remote peer.
* - sslCapath: string, a directory that holds multiple CA certificates.
*
* You may set options using keys, which are specific to particular transport, like `[CURLOPT_VERBOSE => true]` in case
* there is a necessity for it.
*
* @param array $options request options.
* @return $this self reference.
*/
public function setOptions(array $options)
{
$this->_options = $options;
return $this;
}
/**
* @return array request options.
*/
public function getOptions()
{
return $this->_options;
}
/**
* Adds more options to already defined ones.
* Please refer to [[setOptions()]] on how to specify options.
* @param array $options additional options
* @return $this self reference.
*/
public function addOptions(array $options)
{
// `array_merge()` will produce invalid result for cURL options,
// while `ArrayHelper::merge()` is unable to override cURL options
foreach ($options as $key => $value) {
if (is_array($value) && isset($this->_options[$key])) {
$value = ArrayHelper::merge($this->_options[$key], $value);
}
$this->_options[$key] = $value;
}
return $this;
}
/**
* @inheritdoc
*/
public function setData($data)
{
if ($this->isPrepared) {
$this->setContent(null);
$this->isPrepared = false;
}
return parent::setData($data);
}
/**
* @inheritdoc
*/
public function addData($data)
{
if ($this->isPrepared) {
$this->setContent(null);
$this->isPrepared = false;
}
return parent::addData($data);
}
/**
* Adds a content part for multi-part content request.
* @param string $name part (form input) name.
* @param string $content content.
* @param array $options content part options, valid options are:
* - contentType - string, part content type
* - fileName - string, name of the uploading file
* - mimeType - string, part content type in case of file uploading
* @return $this self reference.
*/
public function addContent($name, $content, $options = [])
{
$multiPartContent = $this->getContent();
if (!is_array($multiPartContent)) {
$multiPartContent = [];
}
$options['content'] = $content;
$multiPartContent[$name] = $options;
$this->setContent($multiPartContent);
return $this;
}
/**
* Adds a file for upload as multi-part content.
* @see addContent()
* @param string $name part (form input) name
* @param string $fileName full name of the source file.
* @param array $options content part options, valid options are:
* - fileName - string, base name of the uploading file, if not set it base name of the source file will be used.
* - mimeType - string, file mime type, if not set it will be determine automatically from source file.
* @return $this
*/
public function addFile($name, $fileName, $options = [])
{
$content = file_get_contents($fileName);
if (!isset($options['mimeType'])) {
$options['mimeType'] = FileHelper::getMimeType($fileName);
}
if (!isset($options['fileName'])) {
$options['fileName'] = basename($fileName);
}
return $this->addContent($name, $content, $options);
}
/**
* Adds a string as a file upload.
* @see addContent()
* @param string $name part (form input) name
* @param string $content file content.
* @param array $options content part options, valid options are:
* - fileName - string, base name of the uploading file.
* - mimeType - string, file mime type, if not set it 'application/octet-stream' will be used.
* @return $this
*/
public function addFileContent($name, $content, $options = [])
{
if (!isset($options['mimeType'])) {
$options['mimeType'] = 'application/octet-stream';
}
if (!isset($options['fileName'])) {
$options['fileName'] = $name . '.dat';
}
return $this->addContent($name, $content, $options);
}
/**
* Prepares this request instance for sending.
* This method should be invoked by transport before sending a request.
* Do not call this method unless you know what you are doing.
* @return $this self reference.
*/
public function prepare()
{
$content = $this->getContent();
if ($content === null) {
$this->getFormatter()->format($this);
} elseif (is_array($content)) {
$this->prepareMultiPartContent($content);
}
$this->isPrepared = true;
return $this;
}
/**
* Normalizes given URL value, filling it with actual string URL value.
* @param array|string $url raw URL,
* @return string full URL
*/
private function createFullUrl($url)
{
if (is_array($url)) {
$params = $url;
if (isset($params[0])) {
$url = $params[0];
unset($params[0]);
} else {
$url = '';
}
}
if (!empty($this->client->baseUrl)) {
if (empty($url)) {
$url = $this->client->baseUrl;
} elseif (!preg_match('/^https?:\\/\\//i', $url)) {
$url = $this->client->baseUrl . '/' . $url;
}
}
if (!empty($params)) {
if (strpos($url, '?') === false) {
$url .= '?';
} else {
$url .= '&';
}
$url .= http_build_query($params);
}
return $url;
}
/**
* Prepares multi-part content.
* @param array $content multi part content.
* @see https://tools.ietf.org/html/rfc7578
* @see https://tools.ietf.org/html/rfc2616#section-19.5.1 for the Content-Disposition header
* @see https://tools.ietf.org/html/rfc6266 for more details on the Content-Disposition header
*/
private function prepareMultiPartContent(array $content)
{
static $disallowedChars = ["\0", '"', "\r", "\n"];
$contentParts = [];
$data = $this->getData();
if (!empty($data)) {
foreach ($this->composeFormInputs($data) as $name => $value) {
$name = str_replace($disallowedChars, '_', $name);
$contentDisposition = 'Content-Disposition: form-data; name="' . $name . '"';
$contentParts[] = implode("\r\n", [$contentDisposition, '', $value]);
}
}
// process content parts :
foreach ($content as $name => $contentParams) {
$headers = [];
$name = str_replace($disallowedChars, '_', $name);
$contentDisposition = 'Content-Disposition: form-data; name="' . $name . '"';
if (isset($contentParams['fileName'])) {
$fileName = str_replace($disallowedChars, '_', $contentParams['fileName']);
$contentDisposition .= '; filename="' . $fileName . '"';
}
$headers[] = $contentDisposition;
if (isset($contentParams['contentType'])) {
$headers[] = 'Content-Type: ' . $contentParams['contentType'];
} elseif (isset($contentParams['mimeType'])) {
$headers[] = 'Content-Type: ' . $contentParams['mimeType'];
}
$contentParts[] = implode("\r\n", [implode("\r\n", $headers), '', $contentParams['content']]);
}
// generate safe boundary :
do {
$boundary = '---------------------' . md5(mt_rand() . microtime());
} while (preg_grep("/{$boundary}/", $contentParts));
// add boundary for each part :
array_walk($contentParts, function (&$part) use ($boundary) {
$part = "--{$boundary}\r\n{$part}";
});
// add final boundary :
$contentParts[] = "--{$boundary}--";
$contentParts[] = '';
$this->getHeaders()->set('content-type', "multipart/form-data; boundary={$boundary}");
$this->setContent(implode("\r\n", $contentParts));
}
/**
* Composes given data as form inputs submitted values, taking in account nested arrays.
* Converts `['form' => ['name' => 'value']]` to `['form[name]' => 'value']`.
* @param array $data
* @param string $baseKey
* @return array
*/
private function composeFormInputs(array $data, $baseKey = '')
{
$result = [];
foreach ($data as $key => $value) {
if (!empty($baseKey)) {
$key = $baseKey . '[' . $key . ']';
}
if (is_array($value)) {
$result = array_merge($result, $this->composeFormInputs($value, $key));
} else {
$result[$key] = $value;
}
}
return $result;
}
/**
* @inheritdoc
*/
public function composeHeaderLines()
{
$headers = parent::composeHeaderLines();
if ($this->hasCookies()) {
$headers[] = $this->composeCookieHeader();
}
return $headers;
}
/**
* Sends this request.
* @return Response response instance.
*/
public function send()
{
return $this->client->send($this);
}
/**
* This method is invoked right before this request is sent.
* The method will invoke [[Client::beforeSend()]] and trigger the [[EVENT_BEFORE_SEND]] event.
* @since 2.0.1
*/
public function beforeSend()
{
$this->client->beforeSend($this);
$event = new RequestEvent();
$event->request = $this;
$this->trigger(self::EVENT_BEFORE_SEND, $event);
}
/**
* This method is invoked right after this request is sent.
* The method will invoke [[Client::afterSend()]] and trigger the [[EVENT_AFTER_SEND]] event.
* @param Response $response received response instance.
* @since 2.0.1
*/
public function afterSend($response)
{
$this->client->afterSend($this, $response);
$event = new RequestEvent();
$event->request = $this;
$event->response = $response;
$this->trigger(self::EVENT_AFTER_SEND, $event);
}
/**
* @inheritdoc
*/
public function toString()
{
if (!$this->isPrepared) {
$this->prepare();
}
$result = strtoupper($this->getMethod()) . ' ' . $this->getFullUrl();
$parentResult = parent::toString();
if ($parentResult !== '') {
$result .= "\n" . $parentResult;
}
return $result;
}
/**
* @return string cookie header value.
*/
private function composeCookieHeader()
{
$parts = [];
foreach ($this->getCookies() as $cookie) {
$parts[] = $cookie->name . '=' . urlencode($cookie->value);
}
return 'Cookie: ' . implode(';', $parts);
}
/**
* @return FormatterInterface message formatter instance.
*/
private function getFormatter()
{
return $this->client->getFormatter($this->getFormat());
}
}