Debian Codegraph @

vendor/clue/buzz-react/src/Io/Transaction.php

raw
1 <?php
2
3 namespace Clue\React\Buzz\Io;
4
5 use Clue\React\Buzz\Message\ResponseException;
6 use Clue\React\Buzz\Message\MessageFactory;
7 use Psr\Http\Message\RequestInterface;
8 use Psr\Http\Message\ResponseInterface;
9 use Psr\Http\Message\UriInterface;
10 use React\EventLoop\LoopInterface;
11 use React\Promise\Deferred;
12 use React\Promise\PromiseInterface;
13 use React\Stream\ReadableStreamInterface;
14
15 /**
16 * @internal
17 */
18 class Transaction
19 {
20 private $sender;
21 private $messageFactory;
22 private $loop;
23
24 // context: http.timeout (ini_get('default_socket_timeout'): 60)
25 private $timeout;
26
27 // context: http.follow_location (true)
28 private $followRedirects = true;
29
30 // context: http.max_redirects (10)
31 private $maxRedirects = 10;
32
33 // context: http.ignore_errors (false)
34 private $obeySuccessCode = true;
35
36 private $streaming = false;
37
38 public function __construct(Sender $sender, MessageFactory $messageFactory, LoopInterface $loop)
39 {
40 $this->sender = $sender;
41 $this->messageFactory = $messageFactory;
42 $this->loop = $loop;
43 }
44
45 /**
46 * @param array $options
47 * @return self returns new instance, without modifying existing instance
48 */
49 public function withOptions(array $options)
50 {
51 $transaction = clone $this;
52 foreach ($options as $name => $value) {
53 if (property_exists($transaction, $name)) {
54 // restore default value if null is given
55 if ($value === null) {
56 $default = new self($this->sender, $this->messageFactory, $this->loop);
57 $value = $default->$name;
58 }
59
60 $transaction->$name = $value;
61 }
62 }
63
64 return $transaction;
65 }
66
67 public function send(RequestInterface $request)
68 {
69 $deferred = new Deferred(function () use (&$deferred) {
70 if (isset($deferred->pending)) {
71 $deferred->pending->cancel();
72 unset($deferred->pending);
73 }
74 });
75
76 $deferred->numRequests = 0;
77
78 $this->next($request, $deferred)->then(
79 array($deferred, 'resolve'),
80 array($deferred, 'reject')
81 );
82
83 // use timeout from options or default to PHP's default_socket_timeout (60)
84 $timeout = (float)($this->timeout !== null ? $this->timeout : ini_get("default_socket_timeout"));
85 if ($timeout < 0) {
86 return $deferred->promise();
87 }
88
89 $body = $request->getBody();
90 if ($body instanceof ReadableStreamInterface && $body->isReadable()) {
91 $that = $this;
92 $body->on('close', function () use ($that, $deferred, $timeout) {
93 $that->applyTimeout($deferred, $timeout);
94 });
95 } else {
96 $this->applyTimeout($deferred, $timeout);
97 }
98
99 return $deferred->promise();
100 }
101
102 /**
103 * @internal
104 * @param Deferred $deferred
105 * @param number $timeout
106 * @return void
107 */
108 public function applyTimeout(Deferred $deferred, $timeout)
109 {
110 $timer = $this->loop->addTimer($timeout, function () use ($timeout, $deferred) {
111 $deferred->reject(new \RuntimeException(
112 'Request timed out after ' . $timeout . ' seconds'
113 ));
114 if (isset($deferred->pending)) {
115 $deferred->pending->cancel();
116 unset($deferred->pending);
117 }
118 });
119
120 $loop = $this->loop;
121 $deferred->promise()->then(function () use ($loop, $timer){
122 $loop->cancelTimer($timer);
123 }, function () use ($loop, $timer) {
124 $loop->cancelTimer($timer);
125 });
126 }
127
128 private function next(RequestInterface $request, Deferred $deferred)
129 {
130 $this->progress('request', array($request));
131
132 $that = $this;
133 ++$deferred->numRequests;
134
135 $promise = $this->sender->send($request);
136
137 if (!$this->streaming) {
138 $promise = $promise->then(function ($response) use ($deferred, $that) {
139 return $that->bufferResponse($response, $deferred);
140 });
141 }
142
143 $deferred->pending = $promise;
144
145 return $promise->then(
146 function (ResponseInterface $response) use ($request, $that, $deferred) {
147 return $that->onResponse($response, $request, $deferred);
148 }
149 );
150 }
151
152 /**
153 * @internal
154 * @param ResponseInterface $response
155 * @return PromiseInterface Promise<ResponseInterface, Exception>
156 */
157 public function bufferResponse(ResponseInterface $response, $deferred)
158 {
159 $stream = $response->getBody();
160
161 // body is not streaming => already buffered
162 if (!$stream instanceof ReadableStreamInterface) {
163 return \React\Promise\resolve($response);
164 }
165
166 // buffer stream and resolve with buffered body
167 $messageFactory = $this->messageFactory;
168 $promise = \React\Promise\Stream\buffer($stream)->then(
169 function ($body) use ($response, $messageFactory) {
170 return $response->withBody($messageFactory->body($body));
171 },
172 function ($e) use ($stream) {
173 // try to close stream if buffering fails (or is cancelled)
174 $stream->close();
175
176 throw $e;
177 }
178 );
179
180 $deferred->pending = $promise;
181
182 return $promise;
183 }
184
185 /**
186 * @internal
187 * @param ResponseInterface $response
188 * @param RequestInterface $request
189 * @throws ResponseException
190 * @return ResponseInterface|PromiseInterface
191 */
192 public function onResponse(ResponseInterface $response, RequestInterface $request, $deferred)
193 {
194 $this->progress('response', array($response, $request));
195
196 // follow 3xx (Redirection) response status codes if Location header is present and not explicitly disabled
197 // @link https://tools.ietf.org/html/rfc7231#section-6.4
198 if ($this->followRedirects && ($response->getStatusCode() >= 300 && $response->getStatusCode() < 400) && $response->hasHeader('Location')) {
199 return $this->onResponseRedirect($response, $request, $deferred);
200 }
201
202 // only status codes 200-399 are considered to be valid, reject otherwise
203 if ($this->obeySuccessCode && ($response->getStatusCode() < 200 || $response->getStatusCode() >= 400)) {
204 throw new ResponseException($response);
205 }
206
207 // resolve our initial promise
208 return $response;
209 }
210
211 /**
212 * @param ResponseInterface $response
213 * @param RequestInterface $request
214 * @return PromiseInterface
215 * @throws \RuntimeException
216 */
217 private function onResponseRedirect(ResponseInterface $response, RequestInterface $request, Deferred $deferred)
218 {
219 // resolve location relative to last request URI
220 $location = $this->messageFactory->uriRelative($request->getUri(), $response->getHeaderLine('Location'));
221
222 $request = $this->makeRedirectRequest($request, $location);
223 $this->progress('redirect', array($request));
224
225 if ($deferred->numRequests >= $this->maxRedirects) {
226 throw new \RuntimeException('Maximum number of redirects (' . $this->maxRedirects . ') exceeded');
227 }
228
229 return $this->next($request, $deferred);
230 }
231
232 /**
233 * @param RequestInterface $request
234 * @param UriInterface $location
235 * @return RequestInterface
236 */
237 private function makeRedirectRequest(RequestInterface $request, UriInterface $location)
238 {
239 $originalHost = $request->getUri()->getHost();
240 $request = $request
241 ->withoutHeader('Host')
242 ->withoutHeader('Content-Type')
243 ->withoutHeader('Content-Length');
244
245 // Remove authorization if changing hostnames (but not if just changing ports or protocols).
246 if ($location->getHost() !== $originalHost) {
247 $request = $request->withoutHeader('Authorization');
248 }
249
250 // naïve approach..
251 $method = ($request->getMethod() === 'HEAD') ? 'HEAD' : 'GET';
252
253 return $this->messageFactory->request($method, $location, $request->getHeaders());
254 }
255
256 private function progress($name, array $args = array())
257 {
258 return;
259
260 echo $name;
261
262 foreach ($args as $arg) {
263 echo ' ';
264 if ($arg instanceof ResponseInterface) {
265 echo 'HTTP/' . $arg->getProtocolVersion() . ' ' . $arg->getStatusCode() . ' ' . $arg->getReasonPhrase();
266 } elseif ($arg instanceof RequestInterface) {
267 echo $arg->getMethod() . ' ' . $arg->getRequestTarget() . ' HTTP/' . $arg->getProtocolVersion();
268 } else {
269 echo $arg;
270 }
271 }
272
273 echo PHP_EOL;
274 }
275 }