GuzzleHandler.php
5.75 KB
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
<?php
namespace Aws\Handler\GuzzleV5;
use Aws\Sdk;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Event\EndEvent;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\ResponseInterface as GuzzleResponse;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7\Response as Psr7Response;
use Psr\Http\Message\RequestInterface as Psr7Request;
use Psr\Http\Message\StreamInterface as Psr7StreamInterface;
/**
* A request handler that sends PSR-7-compatible requests with Guzzle 5.
*
* The handler accepts a PSR-7 Request object and an array of transfer options
* and returns a Guzzle 6 Promise. The promise is either resolved with a
* PSR-7 Response object or rejected with an array of error data.
*
* @codeCoverageIgnore
*/
class GuzzleHandler
{
private static $validOptions = [
'proxy' => true,
'verify' => true,
'timeout' => true,
'debug' => true,
'connect_timeout' => true,
'stream' => true,
'delay' => true,
'sink' => true,
];
/** @var ClientInterface */
private $client;
/**
* @param ClientInterface $client
*/
public function __construct(ClientInterface $client = null)
{
$this->client = $client ?: new Client();
}
/**
* @param Psr7Request $request
* @param array $options
*
* @return Promise\Promise
*/
public function __invoke(Psr7Request $request, array $options = [])
{
// Create and send a Guzzle 5 request
$guzzlePromise = $this->client->send(
$this->createGuzzleRequest($request, $options)
);
$promise = new Promise\Promise(
function () use ($guzzlePromise) {
try {
$guzzlePromise->wait();
} catch (\Exception $e) {
// The promise is already delivered when the exception is
// thrown, so don't rethrow it.
}
},
[$guzzlePromise, 'cancel']
);
$guzzlePromise->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise->then(
function (GuzzleResponse $response) {
// Adapt the Guzzle 5 Future to a Guzzle 6 ResponsePromise.
return $this->createPsr7Response($response);
},
function (Exception $exception) {
// Reject with information about the error.
return new Promise\RejectedPromise($this->prepareErrorData($exception));
}
);
}
private function createGuzzleRequest(Psr7Request $psrRequest, array $options)
{
$ringConfig = [];
$statsCallback = isset($options['http_stats_receiver'])
? $options['http_stats_receiver']
: null;
unset($options['http_stats_receiver']);
// Remove unsupported options.
foreach (array_keys($options) as $key) {
if (!isset(self::$validOptions[$key])) {
unset($options[$key]);
}
}
// Handle delay option.
if (isset($options['delay'])) {
$ringConfig['delay'] = $options['delay'];
unset($options['delay']);
}
// Prepare sink option.
if (isset($options['sink'])) {
$ringConfig['save_to'] = ($options['sink'] instanceof Psr7StreamInterface)
? new GuzzleStream($options['sink'])
: $options['sink'];
unset($options['sink']);
}
// Ensure that all requests are async and lazy like Guzzle 6.
$options['future'] = 'lazy';
// Create the Guzzle 5 request from the provided PSR7 request.
$request = $this->client->createRequest(
$psrRequest->getMethod(),
$psrRequest->getUri(),
$options
);
if (is_callable($statsCallback)) {
$request->getEmitter()->on(
'end',
function (EndEvent $event) use ($statsCallback) {
$statsCallback($event->getTransferInfo());
}
);
}
// For the request body, adapt the PSR stream to a Guzzle stream.
$body = $psrRequest->getBody();
if ($body->getSize() === 0) {
$request->setBody(null);
} else {
$request->setBody(new GuzzleStream($body));
}
$request->setHeaders($psrRequest->getHeaders());
$request->setHeader(
'User-Agent',
$request->getHeader('User-Agent')
. ' ' . Client::getDefaultUserAgent()
);
// Make sure the delay is configured, if provided.
if ($ringConfig) {
foreach ($ringConfig as $k => $v) {
$request->getConfig()->set($k, $v);
}
}
return $request;
}
private function createPsr7Response(GuzzleResponse $response)
{
if ($body = $response->getBody()) {
$body = new PsrStream($body);
}
return new Psr7Response(
$response->getStatusCode(),
$response->getHeaders(),
$body,
$response->getReasonPhrase()
);
}
private function prepareErrorData(Exception $e)
{
$error = [
'exception' => $e,
'connection_error' => false,
'response' => null,
];
if ($e instanceof ConnectException) {
$error['connection_error'] = true;
}
if ($e instanceof RequestException && $e->getResponse()) {
$error['response'] = $this->createPsr7Response($e->getResponse());
}
return $error;
}
}