Debian Codegraph @

vendor/clue/buzz-react/src/Browser.php

raw
1 <?php
2
3 namespace Clue\React\Buzz;
4
5 use Clue\React\Buzz\Io\Sender;
6 use Clue\React\Buzz\Io\Transaction;
7 use Clue\React\Buzz\Message\MessageFactory;
8 use InvalidArgumentException;
9 use Psr\Http\Message\RequestInterface;
10 use Psr\Http\Message\UriInterface;
11 use React\EventLoop\LoopInterface;
12 use React\Promise\PromiseInterface;
13 use React\Socket\ConnectorInterface;
14 use React\Stream\ReadableStreamInterface;
15
16 class Browser
17 {
18 private $transaction;
19 private $messageFactory;
20 private $baseUri = null;
21
22 /** @var LoopInterface $loop */
23 private $loop;
24
25 /**
26 * The `Browser` is responsible for sending HTTP requests to your HTTP server
27 * and keeps track of pending incoming HTTP responses.
28 * It also registers everything with the main [`EventLoop`](https://github.com/reactphp/event-loop#usage).
29 *
30 * ```php
31 * $loop = React\EventLoop\Factory::create();
32 *
33 * $browser = new Browser($loop);
34 * ```
35 *
36 * If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
37 * proxy servers etc.), you can explicitly pass a custom instance of the
38 * [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface):
39 *
40 * ```php
41 * $connector = new \React\Socket\Connector($loop, array(
42 * 'dns' => '127.0.0.1',
43 * 'tcp' => array(
44 * 'bindto' => '192.168.10.1:0'
45 * ),
46 * 'tls' => array(
47 * 'verify_peer' => false,
48 * 'verify_peer_name' => false
49 * )
50 * ));
51 *
52 * $browser = new Browser($loop, $connector);
53 * ```
54 *
55 * @param LoopInterface $loop
56 * @param ConnectorInterface|null $connector [optional] Connector to use.
57 * Should be `null` in order to use default Connector.
58 */
59 public function __construct(LoopInterface $loop, ConnectorInterface $connector = null)
60 {
61 $this->messageFactory = new MessageFactory();
62 $this->transaction = new Transaction(
63 Sender::createFromLoop($loop, $connector, $this->messageFactory),
64 $this->messageFactory,
65 $loop
66 );
67 }
68
69 /**
70 * @param string|UriInterface $url URI for the request.
71 * @param array $headers
72 * @return PromiseInterface
73 */
74 public function get($url, array $headers = array())
75 {
76 return $this->send($this->messageFactory->request('GET', $url, $headers));
77 }
78
79 /**
80 *
81 * This method will automatically add a matching `Content-Length` request
82 * header if the outgoing request body is a `string`. If you're using a
83 * streaming request body (`ReadableStreamInterface`), it will default to
84 * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
85 * matching `Content-Length` request header like so:
86 *
87 * ```php
88 * $body = new ThroughStream();
89 * $loop->addTimer(1.0, function () use ($body) {
90 * $body->end("hello world");
91 * });
92 *
93 * $browser->post($url, array('Content-Length' => '11'), $body);
94 * ```
95 *
96 * @param string|UriInterface $url URI for the request.
97 * @param array $headers
98 * @param string|ReadableStreamInterface $contents
99 * @return PromiseInterface
100 */
101 public function post($url, array $headers = array(), $contents = '')
102 {
103 return $this->send($this->messageFactory->request('POST', $url, $headers, $contents));
104 }
105
106 /**
107 * @param string|UriInterface $url URI for the request.
108 * @param array $headers
109 * @return PromiseInterface
110 */
111 public function head($url, array $headers = array())
112 {
113 return $this->send($this->messageFactory->request('HEAD', $url, $headers));
114 }
115
116 /**
117 *
118 * This method will automatically add a matching `Content-Length` request
119 * header if the outgoing request body is a `string`. If you're using a
120 * streaming request body (`ReadableStreamInterface`), it will default to
121 * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
122 * matching `Content-Length` request header like so:
123 *
124 * ```php
125 * $body = new ThroughStream();
126 * $loop->addTimer(1.0, function () use ($body) {
127 * $body->end("hello world");
128 * });
129 *
130 * $browser->patch($url, array('Content-Length' => '11'), $body);
131 * ```
132 *
133 * @param string|UriInterface $url URI for the request.
134 * @param array $headers
135 * @param string|ReadableStreamInterface $contents
136 * @return PromiseInterface
137 */
138 public function patch($url, array $headers = array(), $contents = '')
139 {
140 return $this->send($this->messageFactory->request('PATCH', $url , $headers, $contents));
141 }
142
143 /**
144 *
145 * This method will automatically add a matching `Content-Length` request
146 * header if the outgoing request body is a `string`. If you're using a
147 * streaming request body (`ReadableStreamInterface`), it will default to
148 * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
149 * matching `Content-Length` request header like so:
150 *
151 * ```php
152 * $body = new ThroughStream();
153 * $loop->addTimer(1.0, function () use ($body) {
154 * $body->end("hello world");
155 * });
156 *
157 * $browser->put($url, array('Content-Length' => '11'), $body);
158 * ```
159 *
160 * @param string|UriInterface $url URI for the request.
161 * @param array $headers
162 * @param string|ReadableStreamInterface $contents
163 * @return PromiseInterface
164 */
165 public function put($url, array $headers = array(), $contents = '')
166 {
167 return $this->send($this->messageFactory->request('PUT', $url, $headers, $contents));
168 }
169
170 /**
171 * @param string|UriInterface $url URI for the request.
172 * @param array $headers
173 * @param string|ReadableStreamInterface $contents
174 * @return PromiseInterface
175 */
176 public function delete($url, array $headers = array(), $contents = '')
177 {
178 return $this->send($this->messageFactory->request('DELETE', $url, $headers, $contents));
179 }
180
181 /**
182 * Submits an array of field values similar to submitting a form (`application/x-www-form-urlencoded`).
183 *
184 * ```php
185 * $browser->submit($url, array('user' => 'test', 'password' => 'secret'));
186 * ```
187 *
188 * This method will automatically add a matching `Content-Length` request
189 * header for the encoded length of the given `$fields`.
190 *
191 * @param string|UriInterface $url URI for the request.
192 * @param array $fields
193 * @param array $headers
194 * @param string $method
195 * @return PromiseInterface
196 */
197 public function submit($url, array $fields, $headers = array(), $method = 'POST')
198 {
199 $headers['Content-Type'] = 'application/x-www-form-urlencoded';
200 $contents = http_build_query($fields);
201
202 return $this->send($this->messageFactory->request($method, $url, $headers, $contents));
203 }
204
205 /**
206 * Sends an arbitrary instance implementing the [`RequestInterface`](#requestinterface) (PSR-7).
207 *
208 * All the above [predefined methods](#methods) default to sending requests as HTTP/1.0.
209 * If you need a custom HTTP protocol method or version, then you may want to use this
210 * method:
211 *
212 * ```php
213 * $request = new Request('OPTIONS', $url);
214 * $request = $request->withProtocolVersion('1.1');
215 *
216 * $browser->send($request)->then(…);
217 * ```
218 *
219 * This method will automatically add a matching `Content-Length` request
220 * header if the size of the outgoing request body is known and non-empty.
221 * For an empty request body, if will only include a `Content-Length: 0`
222 * request header if the request method usually expects a request body (only
223 * applies to `POST`, `PUT` and `PATCH`).
224 *
225 * @param RequestInterface $request
226 * @return PromiseInterface
227 */
228 public function send(RequestInterface $request)
229 {
230 if ($this->baseUri !== null) {
231 // ensure we're actually below the base URI
232 $request = $request->withUri($this->messageFactory->expandBase($request->getUri(), $this->baseUri));
233 }
234
235 return $this->transaction->send($request);
236 }
237
238 /**
239 * Changes the base URI used to resolve relative URIs to.
240 *
241 * ```php
242 * $newBrowser = $browser->withBase('http://api.example.com/v3');
243 * ```
244 *
245 * Notice that the [`Browser`](#browser) is an immutable object, i.e. the `withBase()` method
246 * actually returns a *new* [`Browser`](#browser) instance with the given base URI applied.
247 *
248 * Any requests to relative URIs will then be processed by first prepending
249 * the (absolute) base URI.
250 * Please note that this merely prepends the base URI and does *not* resolve
251 * any relative path references (like `../` etc.).
252 * This is mostly useful for (RESTful) API calls where all endpoints (URIs)
253 * are located under a common base URI scheme.
254 *
255 * ```php
256 * // will request http://api.example.com/v3/example
257 * $newBrowser->get('/example')->then(…);
258 * ```
259 *
260 * By definition of this library, a given base URI MUST always absolute and
261 * can not contain any placeholders.
262 *
263 * @param string|UriInterface $baseUri absolute base URI
264 * @return self
265 * @throws InvalidArgumentException if the given $baseUri is not a valid absolute URI
266 * @see self::withoutBase()
267 */
268 public function withBase($baseUri)
269 {
270 $browser = clone $this;
271 $browser->baseUri = $this->messageFactory->uri($baseUri);
272
273 if ($browser->baseUri->getScheme() === '' || $browser->baseUri->getHost() === '') {
274 throw new \InvalidArgumentException('Base URI must be absolute');
275 }
276
277 return $browser;
278 }
279
280 /**
281 * Removes the base URI.
282 *
283 * ```php
284 * $newBrowser = $browser->withoutBase();
285 * ```
286 *
287 * Notice that the [`Browser`](#browser) is an immutable object, i.e. the `withoutBase()` method
288 * actually returns a *new* [`Browser`](#browser) instance without any base URI applied.
289 *
290 * See also [`withBase()`](#withbase).
291 *
292 * @return self
293 * @see self::withBase()
294 */
295 public function withoutBase()
296 {
297 $browser = clone $this;
298 $browser->baseUri = null;
299
300 return $browser;
301 }
302
303 /**
304 * Changes the [options](#options) to use:
305 *
306 * The [`Browser`](#browser) class exposes several options for the handling of
307 * HTTP transactions. These options resemble some of PHP's
308 * [HTTP context options](http://php.net/manual/en/context.http.php) and
309 * can be controlled via the following API (and their defaults):
310 *
311 * ```php
312 * $newBrowser = $browser->withOptions(array(
313 * 'timeout' => null,
314 * 'followRedirects' => true,
315 * 'maxRedirects' => 10,
316 * 'obeySuccessCode' => true,
317 * 'streaming' => false,
318 * ));
319 * ```
320 *
321 * See also [timeouts](#timeouts), [redirects](#redirects) and
322 * [streaming](#streaming) for more details.
323 *
324 * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
325 * method actually returns a *new* [`Browser`](#browser) instance with the
326 * options applied.
327 *
328 * @param array $options
329 * @return self
330 */
331 public function withOptions(array $options)
332 {
333 $browser = clone $this;
334 $browser->transaction = $this->transaction->withOptions($options);
335
336 return $browser;
337 }
338 }