Debian Codegraph @

vendor/react/http/src/Io/Sender.php

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