summaryrefslogtreecommitdiffstats
path: root/vendor/react/http/src/Browser.php
blob: 72847f66bf060a5e19945cddc726473e82c17694 (plain)
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
<?php

namespace React\Http;

use Psr\Http\Message\ResponseInterface;
use RingCentral\Psr7\Request;
use RingCentral\Psr7\Uri;
use React\EventLoop\Loop;
use React\EventLoop\LoopInterface;
use React\Http\Io\ReadableBodyStream;
use React\Http\Io\Sender;
use React\Http\Io\Transaction;
use React\Promise\PromiseInterface;
use React\Socket\ConnectorInterface;
use React\Stream\ReadableStreamInterface;
use InvalidArgumentException;

/**
 * @final This class is final and shouldn't be extended as it is likely to be marked final in a future release.
 */
class Browser
{
    private $transaction;
    private $baseUrl;
    private $protocolVersion = '1.1';

    /**
     * The `Browser` is responsible for sending HTTP requests to your HTTP server
     * and keeps track of pending incoming HTTP responses.
     *
     * ```php
     * $browser = new React\Http\Browser();
     * ```
     *
     * This class takes two optional arguments for more advanced usage:
     *
     * ```php
     * // constructor signature as of v1.5.0
     * $browser = new React\Http\Browser(?ConnectorInterface $connector = null, ?LoopInterface $loop = null);
     *
     * // legacy constructor signature before v1.5.0
     * $browser = new React\Http\Browser(?LoopInterface $loop = null, ?ConnectorInterface $connector = null);
     * ```
     *
     * If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
     * proxy servers etc.), you can explicitly pass a custom instance of the
     * [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface):
     *
     * ```php
     * $connector = new React\Socket\Connector(array(
     *     'dns' => '127.0.0.1',
     *     'tcp' => array(
     *         'bindto' => '192.168.10.1:0'
     *     ),
     *     'tls' => array(
     *         'verify_peer' => false,
     *         'verify_peer_name' => false
     *     )
     * ));
     *
     * $browser = new React\Http\Browser($connector);
     * ```
     *
     * This class takes an optional `LoopInterface|null $loop` parameter that can be used to
     * pass the event loop instance to use for this object. You can use a `null` value
     * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
     * This value SHOULD NOT be given unless you're sure you want to explicitly use a
     * given event loop instance.
     *
     * @param null|ConnectorInterface|LoopInterface $connector
     * @param null|LoopInterface|ConnectorInterface $loop
     * @throws \InvalidArgumentException for invalid arguments
     */
    public function __construct($connector = null, $loop = null)
    {
        // swap arguments for legacy constructor signature
        if (($connector instanceof LoopInterface || $connector === null) && ($loop instanceof ConnectorInterface || $loop === null)) {
            $swap = $loop;
            $loop = $connector;
            $connector = $swap;
        }

        if (($connector !== null && !$connector instanceof ConnectorInterface) || ($loop !== null && !$loop instanceof LoopInterface)) {
            throw new \InvalidArgumentException('Expected "?ConnectorInterface $connector" and "?LoopInterface $loop" arguments');
        }

        $loop = $loop ?: Loop::get();
        $this->transaction = new Transaction(
            Sender::createFromLoop($loop, $connector),
            $loop
        );
    }

    /**
     * Sends an HTTP GET request
     *
     * ```php
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump((string)$response->getBody());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * See also [GET request client example](../examples/01-client-get-request.php).
     *
     * @param string $url     URL for the request.
     * @param array  $headers
     * @return PromiseInterface<ResponseInterface>
     */
    public function get($url, array $headers = array())
    {
        return $this->requestMayBeStreaming('GET', $url, $headers);
    }

    /**
     * Sends an HTTP POST request
     *
     * ```php
     * $browser->post(
     *     $url,
     *     [
     *         'Content-Type' => 'application/json'
     *     ],
     *     json_encode($data)
     * )->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump(json_decode((string)$response->getBody()));
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * See also [POST JSON client example](../examples/04-client-post-json.php).
     *
     * This method is also commonly used to submit HTML form data:
     *
     * ```php
     * $data = [
     *     'user' => 'Alice',
     *     'password' => 'secret'
     * ];
     *
     * $browser->post(
     *     $url,
     *     [
     *         'Content-Type' => 'application/x-www-form-urlencoded'
     *     ],
     *     http_build_query($data)
     * );
     * ```
     *
     * This method will automatically add a matching `Content-Length` request
     * header if the outgoing request body is a `string`. If you're using a
     * streaming request body (`ReadableStreamInterface`), it will default to
     * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
     * matching `Content-Length` request header like so:
     *
     * ```php
     * $body = new React\Stream\ThroughStream();
     * Loop::addTimer(1.0, function () use ($body) {
     *     $body->end("hello world");
     * });
     *
     * $browser->post($url, array('Content-Length' => '11'), $body);
     * ```
     *
     * @param string                         $url      URL for the request.
     * @param array                          $headers
     * @param string|ReadableStreamInterface $body
     * @return PromiseInterface<ResponseInterface>
     */
    public function post($url, array $headers = array(), $body = '')
    {
        return $this->requestMayBeStreaming('POST', $url, $headers, $body);
    }

    /**
     * Sends an HTTP HEAD request
     *
     * ```php
     * $browser->head($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump($response->getHeaders());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * @param string $url     URL for the request.
     * @param array  $headers
     * @return PromiseInterface<ResponseInterface>
     */
    public function head($url, array $headers = array())
    {
        return $this->requestMayBeStreaming('HEAD', $url, $headers);
    }

    /**
     * Sends an HTTP PATCH request
     *
     * ```php
     * $browser->patch(
     *     $url,
     *     [
     *         'Content-Type' => 'application/json'
     *     ],
     *     json_encode($data)
     * )->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump(json_decode((string)$response->getBody()));
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * This method will automatically add a matching `Content-Length` request
     * header if the outgoing request body is a `string`. If you're using a
     * streaming request body (`ReadableStreamInterface`), it will default to
     * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
     * matching `Content-Length` request header like so:
     *
     * ```php
     * $body = new React\Stream\ThroughStream();
     * Loop::addTimer(1.0, function () use ($body) {
     *     $body->end("hello world");
     * });
     *
     * $browser->patch($url, array('Content-Length' => '11'), $body);
     * ```
     *
     * @param string                         $url      URL for the request.
     * @param array                          $headers
     * @param string|ReadableStreamInterface $body
     * @return PromiseInterface<ResponseInterface>
     */
    public function patch($url, array $headers = array(), $body = '')
    {
        return $this->requestMayBeStreaming('PATCH', $url , $headers, $body);
    }

    /**
     * Sends an HTTP PUT request
     *
     * ```php
     * $browser->put(
     *     $url,
     *     [
     *         'Content-Type' => 'text/xml'
     *     ],
     *     $xml->asXML()
     * )->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump((string)$response->getBody());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * See also [PUT XML client example](../examples/05-client-put-xml.php).
     *
     * This method will automatically add a matching `Content-Length` request
     * header if the outgoing request body is a `string`. If you're using a
     * streaming request body (`ReadableStreamInterface`), it will default to
     * using `Transfer-Encoding: chunked` or you have to explicitly pass in a
     * matching `Content-Length` request header like so:
     *
     * ```php
     * $body = new React\Stream\ThroughStream();
     * Loop::addTimer(1.0, function () use ($body) {
     *     $body->end("hello world");
     * });
     *
     * $browser->put($url, array('Content-Length' => '11'), $body);
     * ```
     *
     * @param string                         $url      URL for the request.
     * @param array                          $headers
     * @param string|ReadableStreamInterface $body
     * @return PromiseInterface<ResponseInterface>
     */
    public function put($url, array $headers = array(), $body = '')
    {
        return $this->requestMayBeStreaming('PUT', $url, $headers, $body);
    }

    /**
     * Sends an HTTP DELETE request
     *
     * ```php
     * $browser->delete($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump((string)$response->getBody());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * @param string                         $url      URL for the request.
     * @param array                          $headers
     * @param string|ReadableStreamInterface $body
     * @return PromiseInterface<ResponseInterface>
     */
    public function delete($url, array $headers = array(), $body = '')
    {
        return $this->requestMayBeStreaming('DELETE', $url, $headers, $body);
    }

    /**
     * Sends an arbitrary HTTP request.
     *
     * The preferred way to send an HTTP request is by using the above
     * [request methods](#request-methods), for example the [`get()`](#get)
     * method to send an HTTP `GET` request.
     *
     * As an alternative, if you want to use a custom HTTP request method, you
     * can use this method:
     *
     * ```php
     * $browser->request('OPTIONS', $url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     var_dump((string)$response->getBody());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * This method will automatically add a matching `Content-Length` request
     * header if the size of the outgoing request body is known and non-empty.
     * For an empty request body, if will only include a `Content-Length: 0`
     * request header if the request method usually expects a request body (only
     * applies to `POST`, `PUT` and `PATCH`).
     *
     * If you're using a streaming request body (`ReadableStreamInterface`), it
     * will default to using `Transfer-Encoding: chunked` or you have to
     * explicitly pass in a matching `Content-Length` request header like so:
     *
     * ```php
     * $body = new React\Stream\ThroughStream();
     * Loop::addTimer(1.0, function () use ($body) {
     *     $body->end("hello world");
     * });
     *
     * $browser->request('POST', $url, array('Content-Length' => '11'), $body);
     * ```
     *
     * @param string                         $method   HTTP request method, e.g. GET/HEAD/POST etc.
     * @param string                         $url      URL for the request
     * @param array                          $headers  Additional request headers
     * @param string|ReadableStreamInterface $body     HTTP request body contents
     * @return PromiseInterface<ResponseInterface,\Exception>
     */
    public function request($method, $url, array $headers = array(), $body = '')
    {
        return $this->withOptions(array('streaming' => false))->requestMayBeStreaming($method, $url, $headers, $body);
    }

    /**
     * Sends an arbitrary HTTP request and receives a streaming response without buffering the response body.
     *
     * The preferred way to send an HTTP request is by using the above
     * [request methods](#request-methods), for example the [`get()`](#get)
     * method to send an HTTP `GET` request. Each of these methods will buffer
     * the whole response body in memory by default. This is easy to get started
     * and works reasonably well for smaller responses.
     *
     * In some situations, it's a better idea to use a streaming approach, where
     * only small chunks have to be kept in memory. You can use this method to
     * send an arbitrary HTTP request and receive a streaming response. It uses
     * the same HTTP message API, but does not buffer the response body in
     * memory. It only processes the response body in small chunks as data is
     * received and forwards this data through [ReactPHP's Stream API](https://github.com/reactphp/stream).
     * This works for (any number of) responses of arbitrary sizes.
     *
     * ```php
     * $browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     $body = $response->getBody();
     *     assert($body instanceof Psr\Http\Message\StreamInterface);
     *     assert($body instanceof React\Stream\ReadableStreamInterface);
     *
     *     $body->on('data', function ($chunk) {
     *         echo $chunk;
     *     });
     *
     *     $body->on('error', function (Exception $e) {
     *         echo 'Error: ' . $e->getMessage() . PHP_EOL;
     *     });
     *
     *     $body->on('close', function () {
     *         echo '[DONE]' . PHP_EOL;
     *     });
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * See also [`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface)
     * and the [streaming response](#streaming-response) for more details,
     * examples and possible use-cases.
     *
     * This method will automatically add a matching `Content-Length` request
     * header if the size of the outgoing request body is known and non-empty.
     * For an empty request body, if will only include a `Content-Length: 0`
     * request header if the request method usually expects a request body (only
     * applies to `POST`, `PUT` and `PATCH`).
     *
     * If you're using a streaming request body (`ReadableStreamInterface`), it
     * will default to using `Transfer-Encoding: chunked` or you have to
     * explicitly pass in a matching `Content-Length` request header like so:
     *
     * ```php
     * $body = new React\Stream\ThroughStream();
     * Loop::addTimer(1.0, function () use ($body) {
     *     $body->end("hello world");
     * });
     *
     * $browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body);
     * ```
     *
     * @param string                         $method   HTTP request method, e.g. GET/HEAD/POST etc.
     * @param string                         $url      URL for the request
     * @param array                          $headers  Additional request headers
     * @param string|ReadableStreamInterface $body     HTTP request body contents
     * @return PromiseInterface<ResponseInterface,\Exception>
     */
    public function requestStreaming($method, $url, $headers = array(), $body = '')
    {
        return $this->withOptions(array('streaming' => true))->requestMayBeStreaming($method, $url, $headers, $body);
    }

    /**
     * Changes the maximum timeout used for waiting for pending requests.
     *
     * You can pass in the number of seconds to use as a new timeout value:
     *
     * ```php
     * $browser = $browser->withTimeout(10.0);
     * ```
     *
     * You can pass in a bool `false` to disable any timeouts. In this case,
     * requests can stay pending forever:
     *
     * ```php
     * $browser = $browser->withTimeout(false);
     * ```
     *
     * You can pass in a bool `true` to re-enable default timeout handling. This
     * will respects PHP's `default_socket_timeout` setting (default 60s):
     *
     * ```php
     * $browser = $browser->withTimeout(true);
     * ```
     *
     * See also [timeouts](#timeouts) for more details about timeout handling.
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * given timeout value applied.
     *
     * @param bool|number $timeout
     * @return self
     */
    public function withTimeout($timeout)
    {
        if ($timeout === true) {
            $timeout = null;
        } elseif ($timeout === false) {
            $timeout = -1;
        } elseif ($timeout < 0) {
            $timeout = 0;
        }

        return $this->withOptions(array(
            'timeout' => $timeout,
        ));
    }

    /**
     * Changes how HTTP redirects will be followed.
     *
     * You can pass in the maximum number of redirects to follow:
     *
     * ```php
     * $browser = $browser->withFollowRedirects(5);
     * ```
     *
     * The request will automatically be rejected when the number of redirects
     * is exceeded. You can pass in a `0` to reject the request for any
     * redirects encountered:
     *
     * ```php
     * $browser = $browser->withFollowRedirects(0);
     *
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     // only non-redirected responses will now end up here
     *     var_dump($response->getHeaders());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * You can pass in a bool `false` to disable following any redirects. In
     * this case, requests will resolve with the redirection response instead
     * of following the `Location` response header:
     *
     * ```php
     * $browser = $browser->withFollowRedirects(false);
     *
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     // any redirects will now end up here
     *     var_dump($response->getHeaderLine('Location'));
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * You can pass in a bool `true` to re-enable default redirect handling.
     * This defaults to following a maximum of 10 redirects:
     *
     * ```php
     * $browser = $browser->withFollowRedirects(true);
     * ```
     *
     * See also [redirects](#redirects) for more details about redirect handling.
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * given redirect setting applied.
     *
     * @param bool|int $followRedirects
     * @return self
     */
    public function withFollowRedirects($followRedirects)
    {
        return $this->withOptions(array(
            'followRedirects' => $followRedirects !== false,
            'maxRedirects' => \is_bool($followRedirects) ? null : $followRedirects
        ));
    }

    /**
     * Changes whether non-successful HTTP response status codes (4xx and 5xx) will be rejected.
     *
     * You can pass in a bool `false` to disable rejecting incoming responses
     * that use a 4xx or 5xx response status code. In this case, requests will
     * resolve with the response message indicating an error condition:
     *
     * ```php
     * $browser = $browser->withRejectErrorResponse(false);
     *
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     // any HTTP response will now end up here
     *     var_dump($response->getStatusCode(), $response->getReasonPhrase());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * You can pass in a bool `true` to re-enable default status code handling.
     * This defaults to rejecting any response status codes in the 4xx or 5xx
     * range:
     *
     * ```php
     * $browser = $browser->withRejectErrorResponse(true);
     *
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     // any successful HTTP response will now end up here
     *     var_dump($response->getStatusCode(), $response->getReasonPhrase());
     * }, function (Exception $e) {
     *     if ($e instanceof React\Http\Message\ResponseException) {
     *         // any HTTP response error message will now end up here
     *         $response = $e->getResponse();
     *         var_dump($response->getStatusCode(), $response->getReasonPhrase());
     *     } else {
     *         echo 'Error: ' . $e->getMessage() . PHP_EOL;
     *     }
     * });
     * ```
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * given setting applied.
     *
     * @param bool $obeySuccessCode
     * @return self
     */
    public function withRejectErrorResponse($obeySuccessCode)
    {
        return $this->withOptions(array(
            'obeySuccessCode' => $obeySuccessCode,
        ));
    }

    /**
     * Changes the base URL used to resolve relative URLs to.
     *
     * If you configure a base URL, any requests to relative URLs will be
     * processed by first resolving this relative to the given absolute base
     * URL. This supports resolving relative path references (like `../` etc.).
     * This is particularly useful for (RESTful) API calls where all endpoints
     * (URLs) are located under a common base URL.
     *
     * ```php
     * $browser = $browser->withBase('http://api.example.com/v3/');
     *
     * // will request http://api.example.com/v3/users
     * $browser->get('users')->then(…);
     * ```
     *
     * You can pass in a `null` base URL to return a new instance that does not
     * use a base URL:
     *
     * ```php
     * $browser = $browser->withBase(null);
     * ```
     *
     * Accordingly, any requests using relative URLs to a browser that does not
     * use a base URL can not be completed and will be rejected without sending
     * a request.
     *
     * This method will throw an `InvalidArgumentException` if the given
     * `$baseUrl` argument is not a valid URL.
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. the `withBase()` method
     * actually returns a *new* [`Browser`](#browser) instance with the given base URL applied.
     *
     * @param string|null $baseUrl absolute base URL
     * @return self
     * @throws InvalidArgumentException if the given $baseUrl is not a valid absolute URL
     * @see self::withoutBase()
     */
    public function withBase($baseUrl)
    {
        $browser = clone $this;
        if ($baseUrl === null) {
            $browser->baseUrl = null;
            return $browser;
        }

        $browser->baseUrl = new Uri($baseUrl);
        if (!\in_array($browser->baseUrl->getScheme(), array('http', 'https')) || $browser->baseUrl->getHost() === '') {
            throw new \InvalidArgumentException('Base URL must be absolute');
        }

        return $browser;
    }

    /**
     * Changes the HTTP protocol version that will be used for all subsequent requests.
     *
     * All the above [request methods](#request-methods) default to sending
     * requests as HTTP/1.1. This is the preferred HTTP protocol version which
     * also provides decent backwards-compatibility with legacy HTTP/1.0
     * servers. As such, there should rarely be a need to explicitly change this
     * protocol version.
     *
     * If you want to explicitly use the legacy HTTP/1.0 protocol version, you
     * can use this method:
     *
     * ```php
     * $browser = $browser->withProtocolVersion('1.0');
     *
     * $browser->get($url)->then(…);
     * ```
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * new protocol version applied.
     *
     * @param string $protocolVersion HTTP protocol version to use, must be one of "1.1" or "1.0"
     * @return self
     * @throws InvalidArgumentException
     */
    public function withProtocolVersion($protocolVersion)
    {
        if (!\in_array($protocolVersion, array('1.0', '1.1'), true)) {
            throw new InvalidArgumentException('Invalid HTTP protocol version, must be one of "1.1" or "1.0"');
        }

        $browser = clone $this;
        $browser->protocolVersion = (string) $protocolVersion;

        return $browser;
    }

    /**
     * Changes the maximum size for buffering a response body.
     *
     * The preferred way to send an HTTP request is by using the above
     * [request methods](#request-methods), for example the [`get()`](#get)
     * method to send an HTTP `GET` request. Each of these methods will buffer
     * the whole response body in memory by default. This is easy to get started
     * and works reasonably well for smaller responses.
     *
     * By default, the response body buffer will be limited to 16 MiB. If the
     * response body exceeds this maximum size, the request will be rejected.
     *
     * You can pass in the maximum number of bytes to buffer:
     *
     * ```php
     * $browser = $browser->withResponseBuffer(1024 * 1024);
     *
     * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) {
     *     // response body will not exceed 1 MiB
     *     var_dump($response->getHeaders(), (string) $response->getBody());
     * }, function (Exception $e) {
     *     echo 'Error: ' . $e->getMessage() . PHP_EOL;
     * });
     * ```
     *
     * Note that the response body buffer has to be kept in memory for each
     * pending request until its transfer is completed and it will only be freed
     * after a pending request is fulfilled. As such, increasing this maximum
     * buffer size to allow larger response bodies is usually not recommended.
     * Instead, you can use the [`requestStreaming()` method](#requeststreaming)
     * to receive responses with arbitrary sizes without buffering. Accordingly,
     * this maximum buffer size setting has no effect on streaming responses.
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * given setting applied.
     *
     * @param int $maximumSize
     * @return self
     * @see self::requestStreaming()
     */
    public function withResponseBuffer($maximumSize)
    {
        return $this->withOptions(array(
            'maximumSize' => $maximumSize
        ));
    }

    /**
     * Changes the [options](#options) to use:
     *
     * The [`Browser`](#browser) class exposes several options for the handling of
     * HTTP transactions. These options resemble some of PHP's
     * [HTTP context options](http://php.net/manual/en/context.http.php) and
     * can be controlled via the following API (and their defaults):
     *
     * ```php
     * // deprecated
     * $newBrowser = $browser->withOptions(array(
     *     'timeout' => null, // see withTimeout() instead
     *     'followRedirects' => true, // see withFollowRedirects() instead
     *     'maxRedirects' => 10, // see withFollowRedirects() instead
     *     'obeySuccessCode' => true, // see withRejectErrorResponse() instead
     *     'streaming' => false, // deprecated, see requestStreaming() instead
     * ));
     * ```
     *
     * See also [timeouts](#timeouts), [redirects](#redirects) and
     * [streaming](#streaming) for more details.
     *
     * Notice that the [`Browser`](#browser) is an immutable object, i.e. this
     * method actually returns a *new* [`Browser`](#browser) instance with the
     * options applied.
     *
     * @param array $options
     * @return self
     * @see self::withTimeout()
     * @see self::withFollowRedirects()
     * @see self::withRejectErrorResponse()
     */
    private function withOptions(array $options)
    {
        $browser = clone $this;
        $browser->transaction = $this->transaction->withOptions($options);

        return $browser;
    }

    /**
     * @param string                         $method
     * @param string                         $url
     * @param array                          $headers
     * @param string|ReadableStreamInterface $body
     * @return PromiseInterface<ResponseInterface,\Exception>
     */
    private function requestMayBeStreaming($method, $url, array $headers = array(), $body = '')
    {
        if ($this->baseUrl !== null) {
            // ensure we're actually below the base URL
            $url = Uri::resolve($this->baseUrl, $url);
        }

        if ($body instanceof ReadableStreamInterface) {
            $body = new ReadableBodyStream($body);
        }

        return $this->transaction->send(
            new Request($method, $url, $headers, $body, $this->protocolVersion)
        );
    }
}