Debian Codegraph @

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

raw
1 <?php
2
3 namespace Clue\React\Buzz\Io;
4
5 use Clue\React\Buzz\Message\MessageFactory;
6 use Psr\Http\Message\RequestInterface;
7 use React\EventLoop\LoopInterface;
8 use React\HttpClient\Client as HttpClient;
9 use React\HttpClient\Response as ResponseStream;
10 use React\Promise\PromiseInterface;
11 use React\Promise\Deferred;
12 use React\Socket\ConnectorInterface;
13 use React\Stream\ReadableStreamInterface;
14
15 /**
16 * [Internal] Sends requests and receives responses
17 *
18 * The `Sender` is responsible for passing the [`RequestInterface`](#requestinterface) objects to
19 * the underlying [`HttpClient`](https://github.com/reactphp/http-client) library
20 * and keeps track of its transmission and converts its reponses back to [`ResponseInterface`](#responseinterface) objects.
21 *
22 * It also registers everything with the main [`EventLoop`](https://github.com/reactphp/event-loop#usage)
23 * and the default [`Connector`](https://github.com/reactphp/socket-client) and [DNS `Resolver`](https://github.com/reactphp/dns).
24 *
25 * The `Sender` class mostly exists in order to abstract changes on the underlying
26 * components away from this package in order to provide backwards and forwards
27 * compatibility.
28 *
29 * @internal You SHOULD NOT rely on this API, it is subject to change without prior notice!
30 * @see Browser
31 */
32 class Sender
33 {
34 /**
35 * create a new default sender attached to the given event loop
36 *
37 * This method is used internally to create the "default sender".
38 *
39 * You may also use this method if you need custom DNS or connector
40 * settings. You can use this method manually like this:
41 *
42 * ```php
43 * $connector = new \React\Socket\Connector($loop);
44 * $sender = \Clue\React\Buzz\Io\Sender::createFromLoop($loop, $connector);
45 * ```
46 *
47 * @param LoopInterface $loop
48 * @param ConnectorInterface|null $connector
49 * @return self
50 */
51 public static function createFromLoop(LoopInterface $loop, ConnectorInterface $connector = null, MessageFactory $messageFactory)
52 {
53 return new self(new HttpClient($loop, $connector), $messageFactory);
54 }
55
56 private $http;
57 private $messageFactory;
58
59 /**
60 * [internal] Instantiate Sender
61 *
62 * @param HttpClient $http
63 * @internal
64 */
65 public function __construct(HttpClient $http, MessageFactory $messageFactory)
66 {
67 $this->http = $http;
68 $this->messageFactory = $messageFactory;
69 }
70
71 /**
72 *
73 * @internal
74 * @param RequestInterface $request
75 * @return PromiseInterface Promise<ResponseInterface, Exception>
76 */
77 public function send(RequestInterface $request)
78 {
79 $body = $request->getBody();
80 $size = $body->getSize();
81
82 if ($size !== null && $size !== 0) {
83 // automatically assign a "Content-Length" request header if the body size is known and non-empty
84 $request = $request->withHeader('Content-Length', (string)$size);
85 } elseif ($size === 0 && \in_array($request->getMethod(), array('POST', 'PUT', 'PATCH'))) {
86 // only assign a "Content-Length: 0" request header if the body is expected for certain methods
87 $request = $request->withHeader('Content-Length', '0');
88 } elseif ($body instanceof ReadableStreamInterface && $body->isReadable() && !$request->hasHeader('Content-Length')) {
89 // use "Transfer-Encoding: chunked" when this is a streaming body and body size is unknown
90 $request = $request->withHeader('Transfer-Encoding', 'chunked');
91 } else {
92 // do not use chunked encoding if size is known or if this is an empty request body
93 $size = 0;
94 }
95
96 $headers = array();
97 foreach ($request->getHeaders() as $name => $values) {
98 $headers[$name] = implode(', ', $values);
99 }
100
101 $requestStream = $this->http->request($request->getMethod(), (string)$request->getUri(), $headers, $request->getProtocolVersion());
102
103 $deferred = new Deferred(function ($_, $reject) use ($requestStream) {
104 // close request stream if request is cancelled
105 $reject(new \RuntimeException('Request cancelled'));
106 $requestStream->close();
107 });
108
109 $requestStream->on('error', function($error) use ($deferred) {
110 $deferred->reject($error);
111 });
112
113 $messageFactory = $this->messageFactory;
114 $requestStream->on('response', function (ResponseStream $responseStream) use ($deferred, $messageFactory) {
115 // apply response header values from response stream
116 $deferred->resolve($messageFactory->response(
117 $responseStream->getVersion(),
118 $responseStream->getCode(),
119 $responseStream->getReasonPhrase(),
120 $responseStream->getHeaders(),
121 $responseStream
122 ));
123 });
124
125 if ($body instanceof ReadableStreamInterface) {
126 if ($body->isReadable()) {
127 // length unknown => apply chunked transfer-encoding
128 if ($size === null) {
129 $body = new ChunkedEncoder($body);
130 }
131
132 // pipe body into request stream
133 // add dummy write to immediately start request even if body does not emit any data yet
134 $body->pipe($requestStream);
135 $requestStream->write('');
136
137 $body->on('close', $close = function () use ($deferred, $requestStream) {
138 $deferred->reject(new \RuntimeException('Request failed because request body closed unexpectedly'));
139 $requestStream->close();
140 });
141 $body->on('error', function ($e) use ($deferred, $requestStream, $close, $body) {
142 $body->removeListener('close', $close);
143 $deferred->reject(new \RuntimeException('Request failed because request body reported an error', 0, $e));
144 $requestStream->close();
145 });
146 $body->on('end', function () use ($close, $body) {
147 $body->removeListener('close', $close);
148 });
149 } else {
150 // stream is not readable => end request without body
151 $requestStream->end();
152 }
153 } else {
154 // body is fully buffered => write as one chunk
155 $requestStream->end((string)$body);
156 }
157
158 return $deferred->promise();
159 }
160 }