forked from yiisoft/yii2-httpclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StreamTransport.php
94 lines (81 loc) · 2.76 KB
/
StreamTransport.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
<?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\Inflector;
use Yii;
/**
* StreamTransport sends HTTP messages using [Streams](http://php.net/manual/en/book.stream.php)
*
* For this transport, you may setup request options using [Context Options](http://php.net/manual/en/context.php)
*
* @author Paul Klimov <[email protected]>
* @since 2.0
*/
class StreamTransport extends Transport
{
/**
* @inheritdoc
*/
public function send($request)
{
$request->prepare();
$url = $request->getUrl();
$method = strtoupper($request->getMethod());
$contextOptions = [
'http' => [
'method' => $method,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => false,
],
];
$content = $request->getContent();
if ($content !== null) {
$contextOptions['http']['content'] = $content;
}
$headers = $request->composeHeaderLines();
$contextOptions['http']['header'] = $headers;
$contextOptions = ArrayHelper::merge($contextOptions, $this->composeContextOptions($request->getOptions()));
$token = $request->client->createRequestLogToken($method, $url, $headers, $content);
Yii::info($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
try {
$context = stream_context_create($contextOptions);
$stream = fopen($url, 'rb', false, $context);
$responseContent = stream_get_contents($stream);
$metaData = stream_get_meta_data($stream);
fclose($stream);
} catch (\Exception $exception) {
Yii::endProfile($token, __METHOD__);
throw $exception;
}
Yii::endProfile($token, __METHOD__);
$responseHeaders = isset($metaData['wrapper_data']) ? $metaData['wrapper_data'] : [];
return $request->client->createResponse($responseContent, $responseHeaders);
}
/**
* Composes stream context options from raw request options.
* @param array $options raw request options.
* @return array stream context options.
*/
private function composeContextOptions(array $options)
{
$contextOptions = [];
foreach ($options as $key => $value) {
$section = 'http';
if (strpos($key, 'ssl') === 0) {
$section = 'ssl';
$key = substr($key, 3);
}
$key = Inflector::underscore($key);
$contextOptions[$section][$key] = $value;
}
return $contextOptions;
}
}