vendor/guzzlehttp/guzzle/src/Client.php

1405 lines · 55776 bytes

   1<?php
   2
   3namespace GuzzleHttp;
   4
   5use GuzzleHttp\Cookie\CookieJar;
   6use GuzzleHttp\Cookie\CookieJarInterface;
   7use GuzzleHttp\Exception\GuzzleException;
   8use GuzzleHttp\Exception\InvalidArgumentException;
   9use GuzzleHttp\Handler\CurlShareHandleState;
  10use GuzzleHttp\Handler\CurlVersion;
  11use GuzzleHttp\Promise as P;
  12use GuzzleHttp\Promise\PromiseInterface;
  13use Psr\Http\Message\RequestInterface;
  14use Psr\Http\Message\ResponseInterface;
  15use Psr\Http\Message\StreamInterface;
  16use Psr\Http\Message\UriInterface;
  17
  18/**
  19 * @final
  20 */
  21class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
  22{
  23    use ClientTrait;
  24
  25    /**
  26     * @var array Default request options
  27     */
  28    private $config;
  29
  30    /**
  31     * Clients accept an array of constructor parameters.
  32     *
  33     * Here's an example of creating a client using a base_uri and an array of
  34     * default request options to apply to each request:
  35     *
  36     *     $client = new Client([
  37     *         'base_uri'        => 'http://www.foo.com/1.0/',
  38     *         'timeout'         => 0,
  39     *         'allow_redirects' => false,
  40     *         'proxy'           => '192.168.16.1:10'
  41     *     ]);
  42     *
  43     * Client configuration settings include the following options:
  44     *
  45     * - handler: (callable) Function that transfers HTTP requests over the
  46     *   wire. The function is called with a Psr7\Http\Message\RequestInterface
  47     *   and array of transfer options, and must return a
  48     *   GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
  49     *   Psr7\Http\Message\ResponseInterface on success.
  50     *   If no handler is provided, a default handler will be created
  51     *   that enables all of the request options below by attaching all of the
  52     *   default middleware to the handler.
  53     * - base_uri: (string|UriInterface) Base URI of the client that is merged
  54     *   into relative URIs. Can be a string or instance of UriInterface.
  55     * - transport_sharing: (string|null) Transport sharing mode for the
  56     *   default handler. Accepts TransportSharing::* or null. Defaults to null.
  57     * - max_host_connections: (int|null) Maximum concurrent connections per
  58     *   host, applied by the default CurlMultiHandler. The default stream
  59     *   fallback receives the cap as a marker only: it rejects enabled
  60     *   response streaming ("stream" => true) and does not limit overlapping
  61     *   buffered calls.
  62     * - max_total_connections: (int|null) Maximum concurrent connections
  63     *   overall, applied by the default CurlMultiHandler. The default stream
  64     *   fallback receives the cap as a marker only: it rejects enabled
  65     *   response streaming ("stream" => true) and does not limit overlapping
  66     *   buffered calls.
  67     * - multiplex: (string|null) Multiplexing::NONE to disable multiplexing on
  68     *   the default CurlMultiHandler; the value also becomes the default
  69     *   "multiplex" request option. Other Multiplexing::* values act as the
  70     *   default request option only.
  71     * - **: any request option
  72     *
  73     * @param array $config Client configuration settings.
  74     *
  75     * @see RequestOptions for a list of available request options.
  76     */
  77    public function __construct(array $config = [])
  78    {
  79        $handlerOptions = [];
  80        foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
  81            if (\array_key_exists($capOption, $config)) {
  82                if ($config[$capOption] !== null) {
  83                    $handlerOptions[$capOption] = $config[$capOption];
  84                }
  85
  86                unset($config[$capOption]);
  87            }
  88        }
  89
  90        // Deliberately not unset: the value also becomes the default
  91        // "multiplex" request option, which the configured handler accepts.
  92        $handlerMultiplex = ($config['multiplex'] ?? null) === Multiplexing::NONE;
  93
  94        $transportSharing = \array_key_exists('transport_sharing', $config) ? $config['transport_sharing'] : null;
  95        $transportSharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
  96        unset($config['transport_sharing']);
  97
  98        if (!isset($config['handler'])) {
  99            if ($transportSharingMode !== TransportSharing::NONE) {
 100                $handlerOptions['transport_sharing'] = $transportSharingMode;
 101            }
 102
 103            if ($handlerMultiplex) {
 104                $handlerOptions['multiplex'] = Multiplexing::NONE;
 105            }
 106
 107            $config['handler'] = $handlerOptions === []
 108                ? HandlerStack::create()
 109                : HandlerStack::create(Utils::chooseHandler($handlerOptions));
 110        } elseif (!\is_callable($config['handler'])) {
 111            throw new InvalidArgumentException('handler must be a callable');
 112        } elseif ($handlerOptions !== []) {
 113            throw new InvalidArgumentException('The "max_host_connections" and "max_total_connections" client options require Guzzle to create the default handler. Configure the options on the CurlMultiHandler constructor to apply numeric connection caps, or on the StreamHandler constructor to reject enabled response streaming, when providing a custom handler.');
 114        } elseif ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
 115            throw new InvalidArgumentException('The "transport_sharing" client option can only require sharing when Guzzle creates the default handler. Configure the "transport_sharing" option on CurlHandler or CurlMultiHandler when providing a custom cURL handler.');
 116        }
 117
 118        // Convert the base_uri to a UriInterface
 119        if (isset($config['base_uri'])) {
 120            $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']);
 121        }
 122
 123        $this->configureDefaults($config);
 124    }
 125
 126    /**
 127     * @param string $method
 128     * @param array  $args
 129     *
 130     * @return PromiseInterface|ResponseInterface
 131     *
 132     * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0.
 133     */
 134    public function __call($method, $args)
 135    {
 136        \trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s::%s() is deprecated and will be removed in 8.0.', __CLASS__, __FUNCTION__);
 137
 138        if (\count($args) < 1) {
 139            throw new InvalidArgumentException('Magic request methods require a URI and optional options array');
 140        }
 141
 142        $uri = $args[0];
 143        $opts = $args[1] ?? [];
 144
 145        $isAsync = \substr($method, -5) === 'Async';
 146        $method = $isAsync ? \substr($method, 0, -5) : $method;
 147        $method = Psr7\Utils::asciiToUpper($method);
 148
 149        return $isAsync
 150            ? $this->requestAsync($method, $uri, $opts)
 151            : $this->request($method, $uri, $opts);
 152    }
 153
 154    /**
 155     * Asynchronously send an HTTP request.
 156     *
 157     * @param array $options Request options to apply to the given
 158     *                       request and to the transfer. See {@see RequestOptions}.
 159     */
 160    public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
 161    {
 162        // Merge the base URI into the request URI if needed.
 163        $options = $this->prepareDefaults($options);
 164
 165        return $this->transfer(
 166            $request->withUri($this->buildUri($request->getUri(), $options), self::shouldPreserveHost($request)),
 167            $options
 168        );
 169    }
 170
 171    /**
 172     * Send an HTTP request.
 173     *
 174     * @param array $options Request options to apply to the given
 175     *                       request and to the transfer. See {@see RequestOptions}.
 176     *
 177     * @throws GuzzleException
 178     */
 179    public function send(RequestInterface $request, array $options = []): ResponseInterface
 180    {
 181        $options[RequestOptions::SYNCHRONOUS] = true;
 182
 183        return $this->sendAsync($request, $options)->wait();
 184    }
 185
 186    /**
 187     * The HttpClient PSR (PSR-18) specify this method.
 188     *
 189     * {@inheritDoc}
 190     */
 191    public function sendRequest(RequestInterface $request): ResponseInterface
 192    {
 193        $options[RequestOptions::SYNCHRONOUS] = true;
 194        $options[RequestOptions::ALLOW_REDIRECTS] = false;
 195        $options[RequestOptions::HTTP_ERRORS] = false;
 196
 197        return $this->sendAsync($request, $options)->wait();
 198    }
 199
 200    /**
 201     * Create and send an asynchronous HTTP request.
 202     *
 203     * Use an absolute path to override the base path of the client, or a
 204     * relative path to append to the base path of the client. The URL can
 205     * contain the query string as well. Use an array to provide a URL
 206     * template and additional variables to use in the URL template expansion.
 207     *
 208     * @param string              $method  HTTP method
 209     * @param string|UriInterface $uri     URI object or string.
 210     * @param array               $options Request options to apply. See {@see RequestOptions}.
 211     */
 212    public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface
 213    {
 214        $normalizedMethod = Psr7\Utils::asciiToUpper($method);
 215        if ($method !== $normalizedMethod) {
 216            \trigger_deprecation(
 217                'guzzlehttp/guzzle',
 218                '7.11',
 219                'Passing a non-uppercase HTTP method to Client::requestAsync() is deprecated; guzzlehttp/guzzle 8.0 will preserve HTTP method casing. Pass an uppercase method explicitly if uppercase is required.'
 220            );
 221            $method = $normalizedMethod;
 222        }
 223
 224        $options = $this->prepareDefaults($options);
 225        // Remove request modifying parameter because it can be done up-front.
 226        $headers = $options['headers'] ?? [];
 227        $droppedHeaderNames = self::castDeprecatedHeaderOptionValues($headers);
 228        if ($droppedHeaderNames !== [] && isset($options['_conditional'])) {
 229            $options['_conditional'] = Psr7\Utils::caselessRemove($droppedHeaderNames, $options['_conditional']);
 230        }
 231        $body = $options['body'] ?? null;
 232        $version = self::normalizeProtocolVersion($options['version'] ?? '1.1');
 233        // Merge the URI into the base URI.
 234        $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options);
 235        if (\is_array($body)) {
 236            throw $this->invalidBody();
 237        }
 238        $body = self::createBodyStream($body);
 239        $request = new Psr7\Request($method, $uri, $headers, $body, $version);
 240        // Remove the option so that they are not doubly-applied.
 241        unset($options['headers'], $options['body'], $options['version']);
 242
 243        return $this->transfer($request, $options);
 244    }
 245
 246    /**
 247     * Create and send an HTTP request.
 248     *
 249     * Use an absolute path to override the base path of the client, or a
 250     * relative path to append to the base path of the client. The URL can
 251     * contain the query string as well.
 252     *
 253     * @param string              $method  HTTP method.
 254     * @param string|UriInterface $uri     URI object or string.
 255     * @param array               $options Request options to apply. See {@see RequestOptions}.
 256     *
 257     * @throws GuzzleException
 258     */
 259    public function request(string $method, $uri = '', array $options = []): ResponseInterface
 260    {
 261        $normalizedMethod = Psr7\Utils::asciiToUpper($method);
 262        if ($method !== $normalizedMethod) {
 263            \trigger_deprecation(
 264                'guzzlehttp/guzzle',
 265                '7.11',
 266                'Passing a non-uppercase HTTP method to Client::request() is deprecated; guzzlehttp/guzzle 8.0 will preserve HTTP method casing. Pass an uppercase method explicitly if uppercase is required.'
 267            );
 268            $method = $normalizedMethod;
 269        }
 270
 271        $options[RequestOptions::SYNCHRONOUS] = true;
 272
 273        return $this->requestAsync($method, $uri, $options)->wait();
 274    }
 275
 276    /**
 277     * Get a client configuration option.
 278     *
 279     * These options include default request options of the client, a "handler"
 280     * (if utilized by the concrete client), and a "base_uri" if utilized by
 281     * the concrete client.
 282     *
 283     * @param string|null $option The config option to retrieve.
 284     *
 285     * @return mixed
 286     */
 287    public function getConfig(?string $option = null)
 288    {
 289        return $option === null
 290            ? $this->config
 291            : ($this->config[$option] ?? null);
 292    }
 293
 294    private function buildUri(UriInterface $uri, array $config): UriInterface
 295    {
 296        if (isset($config['base_uri'])) {
 297            $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri);
 298        }
 299
 300        $idnOptions = Utils::normalizeIdnConversionOption($config['idn_conversion'] ?? null);
 301        if ($idnOptions !== null) {
 302            $uri = Utils::idnUriConvert($uri, $idnOptions);
 303        }
 304
 305        if ($uri->getScheme() === '' && $uri->getHost() !== '') {
 306            $uri = $uri->withScheme('http');
 307        }
 308
 309        return $uri;
 310    }
 311
 312    /**
 313     * Whether to preserve an existing Host header when the URI changes.
 314     *
 315     * A header matching the current URI carries no explicit override and is
 316     * regenerated after base URI resolution or IDN conversion. Other values
 317     * are preserved as deliberate overrides, as PSR-7 requires.
 318     */
 319    private static function shouldPreserveHost(RequestInterface $request): bool
 320    {
 321        if (!$request->hasHeader('Host')) {
 322            return false;
 323        }
 324
 325        $uri = $request->getUri();
 326        $host = $uri->getHost();
 327        $port = $uri->getPort();
 328
 329        if ($port !== null) {
 330            $host .= ':'.$port;
 331        }
 332
 333        return $host !== $request->getHeaderLine('Host');
 334    }
 335
 336    /**
 337     * Configures the default options for a client.
 338     */
 339    private function configureDefaults(array $config): void
 340    {
 341        $defaults = [
 342            'allow_redirects' => RedirectMiddleware::$defaultSettings,
 343            'http_errors' => true,
 344            'decode_content' => true,
 345            'verify' => true,
 346            'cookies' => false,
 347            'idn_conversion' => false,
 348            'protocols' => ['http', 'https'],
 349        ];
 350
 351        // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
 352
 353        // We can only trust the HTTP_PROXY environment variable in a CLI
 354        // process due to the fact that PHP has no reliable mechanism to
 355        // get environment variables that start with "HTTP_".
 356        if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) {
 357            $defaults['proxy']['http'] = $proxy;
 358        }
 359
 360        if ($proxy = Utils::getenv('HTTPS_PROXY')) {
 361            $defaults['proxy']['https'] = $proxy;
 362        }
 363
 364        if ($noProxy = Utils::getenv('NO_PROXY')) {
 365            $cleanedNoProxy = \str_replace(' ', '', $noProxy);
 366            $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy);
 367        }
 368
 369        $this->config = $config + $defaults;
 370
 371        if (!empty($config['cookies']) && $config['cookies'] === true) {
 372            $this->config['cookies'] = new CookieJar();
 373        }
 374
 375        // Add the default user-agent header.
 376        if (!isset($this->config['headers'])) {
 377            $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()];
 378        } else {
 379            // Add the User-Agent header if one was not already set.
 380            $hasUserAgent = false;
 381            foreach (\array_keys($this->config['headers']) as $name) {
 382                if (Psr7\Utils::asciiToLower((string) $name) === 'user-agent') {
 383                    $hasUserAgent = true;
 384                    break;
 385                }
 386            }
 387
 388            if (!$hasUserAgent) {
 389                $this->config['headers']['User-Agent'] = Utils::defaultUserAgent();
 390            }
 391        }
 392
 393        if (\is_array($this->config['headers'])) {
 394            self::warnAboutInvalidHeaderOptionTypes($this->config['headers']);
 395            self::castDeprecatedHeaderOptionValues($this->config['headers']);
 396        }
 397    }
 398
 399    /**
 400     * Merges default options into the array.
 401     *
 402     * @param array $options Options to modify by reference
 403     */
 404    private function prepareDefaults(array $options): array
 405    {
 406        self::warnAboutRequestLevelHandler($options);
 407
 408        $defaults = $this->config;
 409
 410        if (!empty($defaults['headers'])) {
 411            // Default headers are only added if they are not present.
 412            $defaults['_conditional'] = $defaults['headers'];
 413            unset($defaults['headers']);
 414        }
 415
 416        // Special handling for headers is required as they are added as
 417        // conditional headers and as headers passed to a request ctor.
 418        if (\array_key_exists('headers', $options)) {
 419            // Allows default headers to be unset.
 420            if ($options['headers'] === null) {
 421                $defaults['_conditional'] = [];
 422                unset($options['headers']);
 423            } elseif (!\is_array($options['headers'])) {
 424                throw new InvalidArgumentException('headers must be an array');
 425            }
 426        }
 427
 428        // Shallow merge defaults underneath options.
 429        $result = $options + $defaults;
 430
 431        // Remove null values.
 432        foreach ($result as $k => $v) {
 433            if ($v === null) {
 434                unset($result[$k]);
 435            }
 436        }
 437
 438        self::warnAboutInvalidRequestOptionTypes($result);
 439
 440        return self::normalizeDeprecatedRequestOptionValues($result);
 441    }
 442
 443    /**
 444     * Normalize values that guzzlehttp/guzzle 8.0 rejects only after the
 445     * corresponding 7.x deprecation has already been emitted.
 446     *
 447     * @param array<string, mixed> $options
 448     *
 449     * @return array<string, mixed>
 450     */
 451    private static function normalizeDeprecatedRequestOptionValues(array $options): array
 452    {
 453        self::normalizeDeprecatedAuthOptionValues($options);
 454        self::normalizeDeprecatedTlsFileOptionValues($options, 'cert');
 455        self::normalizeDeprecatedTlsFileOptionValues($options, 'ssl_key');
 456        self::normalizeDeprecatedStringOptionValues($options);
 457        self::normalizeDeprecatedNumericOptionValues($options);
 458        self::normalizeDeprecatedIntegerOptionValues($options);
 459
 460        return $options;
 461    }
 462
 463    /**
 464     * @param mixed $value
 465     */
 466    private static function canStringifyDeprecatedValue($value): bool
 467    {
 468        return $value === null
 469            || \is_scalar($value)
 470            || (\is_object($value) && \method_exists($value, '__toString'));
 471    }
 472
 473    /**
 474     * @param mixed $value
 475     */
 476    private static function stringifyDeprecatedValue($value): string
 477    {
 478        if (\is_float($value) && !\is_finite($value)) {
 479            return \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
 480        }
 481
 482        if ($value === null) {
 483            return '';
 484        }
 485
 486        if (\is_scalar($value)) {
 487            return (string) $value;
 488        }
 489
 490        if (\is_object($value) && \method_exists($value, '__toString')) {
 491            return $value->__toString();
 492        }
 493
 494        throw new \LogicException('Value is not stringable.');
 495    }
 496
 497    /**
 498     * @param array<string, mixed> $options
 499     */
 500    private static function normalizeDeprecatedAuthOptionValues(array &$options): void
 501    {
 502        if (!isset($options['auth']) || !\is_array($options['auth']) || $options['auth'] === []) {
 503            return;
 504        }
 505
 506        foreach ([0, 1] as $index) {
 507            if (
 508                \array_key_exists($index, $options['auth'])
 509                && !\is_string($options['auth'][$index])
 510                && self::canStringifyDeprecatedValue($options['auth'][$index])
 511            ) {
 512                $options['auth'][$index] = self::stringifyDeprecatedValue($options['auth'][$index]);
 513            }
 514        }
 515
 516        if (
 517            \array_key_exists(2, $options['auth'])
 518            && $options['auth'][2] !== null
 519            && !\is_string($options['auth'][2])
 520            && self::canStringifyDeprecatedValue($options['auth'][2])
 521        ) {
 522            $options['auth'][2] = self::stringifyDeprecatedValue($options['auth'][2]);
 523        }
 524    }
 525
 526    /**
 527     * @param array<string, mixed> $options
 528     */
 529    private static function normalizeDeprecatedTlsFileOptionValues(array &$options, string $option): void
 530    {
 531        if (!isset($options[$option]) || !\is_array($options[$option])) {
 532            return;
 533        }
 534
 535        foreach ([0, 1] as $index) {
 536            if (
 537                \array_key_exists($index, $options[$option])
 538                && $options[$option][$index] !== null
 539                && !\is_string($options[$option][$index])
 540                && self::canStringifyDeprecatedValue($options[$option][$index])
 541            ) {
 542                $options[$option][$index] = self::stringifyDeprecatedValue($options[$option][$index]);
 543            }
 544        }
 545    }
 546
 547    /**
 548     * @param array<string, mixed> $options
 549     */
 550    private static function normalizeDeprecatedStringOptionValues(array &$options): void
 551    {
 552        foreach (['cert_type', 'force_ip_resolve', 'ssl_key_type'] as $option) {
 553            if (
 554                \array_key_exists($option, $options)
 555                && !\is_string($options[$option])
 556                && self::canStringifyDeprecatedValue($options[$option])
 557            ) {
 558                $options[$option] = self::stringifyDeprecatedValue($options[$option]);
 559            }
 560        }
 561    }
 562
 563    /**
 564     * @param array<string, mixed> $options
 565     */
 566    private static function normalizeDeprecatedNumericOptionValues(array &$options): void
 567    {
 568        foreach (['connect_timeout', 'delay', 'read_timeout', 'timeout'] as $option) {
 569            if (
 570                \array_key_exists($option, $options)
 571                && \is_string($options[$option])
 572                && \is_numeric($options[$option])
 573            ) {
 574                $options[$option] = $options[$option] + 0;
 575            }
 576        }
 577    }
 578
 579    /**
 580     * @param array<string, mixed> $options
 581     */
 582    private static function normalizeDeprecatedIntegerOptionValues(array &$options): void
 583    {
 584        foreach (['crypto_method', 'crypto_method_max', 'retries'] as $option) {
 585            if (!\array_key_exists($option, $options)) {
 586                continue;
 587            }
 588
 589            if (\is_string($options[$option]) && \preg_match('/^-?\d+$/D', $options[$option]) === 1) {
 590                $options[$option] = (int) $options[$option];
 591            } elseif (
 592                \is_float($options[$option])
 593                && \is_finite($options[$option])
 594                && $options[$option] === (float) (int) $options[$option]
 595            ) {
 596                $options[$option] = (int) $options[$option];
 597            }
 598        }
 599    }
 600
 601    private static function warnAboutRequestLevelHandler(array $options): void
 602    {
 603        if (!\array_key_exists('handler', $options)) {
 604            return;
 605        }
 606
 607        \trigger_deprecation(
 608            'guzzlehttp/guzzle',
 609            '7.12',
 610            'Passing the "handler" request option is deprecated; guzzlehttp/guzzle 8.0 will ignore request-level handlers. Configure the handler when creating the Client, or use a separate Client instance for requests that need a different handler.'
 611        );
 612    }
 613
 614    private static function warnAboutInvalidRequestOptionTypes(array $options): void
 615    {
 616        if (isset($options['handler']) && !\is_callable($options['handler'])) {
 617            self::warnInvalidRequestOptionType('handler', 'callable', $options['handler']);
 618        }
 619
 620        if (isset($options['allow_redirects']) && \is_array($options['allow_redirects'])) {
 621            self::warnAboutInvalidAllowRedirectsOptionTypes($options['allow_redirects']);
 622        } elseif (isset($options['allow_redirects']) && !\is_bool($options['allow_redirects'])) {
 623            self::warnInvalidRequestOptionType('allow_redirects', 'bool|array', $options['allow_redirects'], '7.13');
 624        }
 625
 626        if (isset($options['auth'])) {
 627            self::warnAboutInvalidAuthOptionTypes($options['auth']);
 628        }
 629
 630        if (isset($options['body']) && \is_array($options['body'])) {
 631            self::warnInvalidRequestOptionType('body', 'resource|string|null|int|float|bool|StreamInterface|(callable&object)|\Iterator|\Stringable', $options['body']);
 632        }
 633
 634        self::warnAboutInvalidTlsFileOptionTypes($options, 'cert');
 635        self::warnIfPresentAndNotString($options, 'cert_type');
 636        self::warnIfPresentAndNotNumber($options, 'connect_timeout');
 637        self::warnIfPresentAndNotInt($options, 'crypto_method');
 638        self::warnIfPresentAndNotInt($options, 'crypto_method_max', null, '7.13');
 639        self::warnIfPresentAndNotBoolOrResource($options, 'debug');
 640        self::warnIfPresentAndNotBoolOrString($options, 'decode_content');
 641        self::warnIfPresentAndNotNumber($options, 'delay');
 642        if (isset($options['delay']) && \is_numeric($options['delay'])) {
 643            $delay = (float) $options['delay'];
 644            if (!\is_finite($delay) || $delay < 0.0) {
 645                self::warnInvalidRequestOptionType('delay', 'finite int|float greater than or equal to 0', $options['delay'], '7.13');
 646            }
 647        }
 648        self::warnIfPresentAndNotBoolOrInt($options, 'expect');
 649
 650        if (isset($options['form_params'])) {
 651            self::warnAboutInvalidFormParamTypes($options['form_params']);
 652        }
 653
 654        if (isset($options['force_ip_resolve']) && !\is_string($options['force_ip_resolve'])) {
 655            self::warnInvalidRequestOptionType('force_ip_resolve', 'string', $options['force_ip_resolve']);
 656        }
 657
 658        if (
 659            isset($options['force_ip_resolve'])
 660            && \is_string($options['force_ip_resolve'])
 661            && $options['force_ip_resolve'] !== 'v4'
 662            && $options['force_ip_resolve'] !== 'v6'
 663        ) {
 664            self::warnInvalidRequestOptionType('force_ip_resolve', '"v4"|"v6"', $options['force_ip_resolve'], '7.13');
 665        }
 666
 667        if (isset($options['headers'])) {
 668            self::warnAboutInvalidHeaderOptionTypes($options['headers']);
 669        }
 670
 671        self::warnIfPresentAndNotBool($options, 'http_errors');
 672
 673        if (isset($options['multipart'])) {
 674            self::warnAboutInvalidMultipartOptionTypes($options['multipart']);
 675        }
 676
 677        self::warnIfPresentAndNotCallable($options, 'on_headers');
 678        self::warnIfPresentAndNotCallable($options, 'on_stats');
 679        self::warnIfPresentAndNotCallable($options, 'on_trailers', null, '7.14');
 680        self::warnIfPresentAndNotCallable($options, 'progress');
 681        self::warnIfPresentAndNotStringArray($options, 'protocols', true);
 682        self::warnAboutInvalidProtocolValues($options, 'protocols');
 683        self::warnAboutInvalidProxyOptionTypes($options);
 684
 685        self::warnIfPresentAndNotNumber($options, 'read_timeout');
 686        self::warnIfPresentAndNotInt($options, 'retries');
 687
 688        if (isset($options['sink']) && !\is_bool($options['sink']) && !\is_resource($options['sink']) && !\is_string($options['sink']) && !$options['sink'] instanceof StreamInterface) {
 689            self::warnInvalidRequestOptionType('sink', 'resource|string|StreamInterface', $options['sink']);
 690        }
 691
 692        self::warnAboutInvalidTlsFileOptionTypes($options, 'ssl_key');
 693        self::warnIfPresentAndNotString($options, 'ssl_key_type');
 694        self::warnIfPresentAndNotBool($options, 'stream');
 695        self::warnIfPresentAndNotArray($options, 'stream_context', 'array<array-key, mixed>');
 696        self::warnIfPresentAndNotBool($options, 'synchronous');
 697        self::warnIfPresentAndNotNumber($options, 'timeout');
 698        self::warnIfPresentAndNotBoolOrString($options, 'verify');
 699        self::warnIfPresentAndNotStringOrNumber($options, 'version');
 700        self::warnIfPresentAndNotArray($options, 'curl', 'array<int|string, mixed>');
 701
 702        if (isset($options['cookies']) && $options['cookies'] === true) {
 703            self::warnInvalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies']);
 704        }
 705
 706        if (
 707            isset($options['cookies'])
 708            && $options['cookies'] !== false
 709            && $options['cookies'] !== true
 710            && !($options['cookies'] instanceof CookieJarInterface)
 711        ) {
 712            self::warnInvalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies'], '7.13');
 713        }
 714    }
 715
 716    private static function warnAboutInvalidAllowRedirectsOptionTypes(array $allowRedirects): void
 717    {
 718        self::warnIfPresentAndNotInt($allowRedirects, 'max', 'allow_redirects.max');
 719        self::warnIfPresentAndNotBool($allowRedirects, 'strict', 'allow_redirects.strict');
 720        self::warnIfPresentAndNotBool($allowRedirects, 'referer', 'allow_redirects.referer');
 721        self::warnIfPresentAndNotStringArray($allowRedirects, 'protocols', true, 'allow_redirects.protocols');
 722        self::warnAboutInvalidProtocolValues($allowRedirects, 'protocols', 'allow_redirects.protocols');
 723        self::warnIfPresentAndNotCallable($allowRedirects, 'on_redirect', 'allow_redirects.on_redirect');
 724        self::warnIfPresentAndNotBool($allowRedirects, 'track_redirects', 'allow_redirects.track_redirects');
 725    }
 726
 727    /**
 728     * @param mixed $auth
 729     */
 730    private static function warnAboutInvalidAuthOptionTypes($auth): void
 731    {
 732        if ($auth === false || \is_string($auth) || $auth === []) {
 733            return;
 734        }
 735
 736        if (!\is_array($auth)) {
 737            self::warnInvalidRequestOptionType('auth', 'array{0: string, 1: string, 2?: string|null}|string|false|null', $auth);
 738
 739            return;
 740        }
 741
 742        if (!\array_key_exists(0, $auth) || !\is_string($auth[0])) {
 743            self::warnInvalidRequestOptionType('auth.0', 'string', $auth[0] ?? null);
 744        }
 745
 746        if (!\array_key_exists(1, $auth) || !\is_string($auth[1])) {
 747            self::warnInvalidRequestOptionType('auth.1', 'string', $auth[1] ?? null);
 748        }
 749
 750        if (\array_key_exists(2, $auth) && $auth[2] !== null && !\is_string($auth[2])) {
 751            self::warnInvalidRequestOptionType('auth.2', 'string|null', $auth[2]);
 752        }
 753    }
 754
 755    /**
 756     * @param mixed $value
 757     */
 758    private static function warnAboutInvalidFormParamTypes($value): void
 759    {
 760        if (!\is_array($value)) {
 761            self::warnInvalidRequestOptionType('form_params', 'array<array-key, string|int|float|bool|null|array>', $value);
 762
 763            return;
 764        }
 765
 766        self::warnAboutInvalidFormParamArray($value, 'form_params');
 767    }
 768
 769    private static function warnAboutInvalidFormParamArray(array $values, string $path): bool
 770    {
 771        foreach ($values as $key => $item) {
 772            $itemPath = $path.'.'.(string) $key;
 773            if (\is_array($item)) {
 774                if (!self::warnAboutInvalidFormParamArray($item, $itemPath)) {
 775                    return false;
 776                }
 777
 778                continue;
 779            }
 780
 781            if ($item !== null && !\is_scalar($item)) {
 782                self::warnInvalidRequestOptionType($itemPath, 'string|int|float|bool|null|array', $item);
 783
 784                return false;
 785            }
 786        }
 787
 788        return true;
 789    }
 790
 791    /**
 792     * @param mixed $headers
 793     */
 794    private static function warnAboutInvalidHeaderOptionTypes($headers): void
 795    {
 796        if (!\is_array($headers)) {
 797            self::warnInvalidRequestOptionType('headers', 'array<array-key, string|non-empty-array<array-key, string>>|null', $headers);
 798
 799            return;
 800        }
 801
 802        foreach ($headers as $name => $value) {
 803            $path = 'headers.'.(string) $name;
 804            if (\is_array($value)) {
 805                if ($value === []) {
 806                    self::warnInvalidRequestOptionType($path, 'string|non-empty-array<array-key, string>', $value);
 807
 808                    break;
 809                }
 810
 811                foreach ($value as $index => $item) {
 812                    if (!\is_string($item)) {
 813                        self::warnInvalidRequestOptionType($path.'.'.(string) $index, 'string', $item);
 814
 815                        break 2;
 816                    }
 817                }
 818            } elseif (!\is_string($value)) {
 819                self::warnInvalidRequestOptionType($path, 'string|non-empty-array<array-key, string>', $value);
 820
 821                break;
 822            }
 823        }
 824    }
 825
 826    /**
 827     * @param mixed $multipart
 828     */
 829    private static function warnAboutInvalidMultipartOptionTypes($multipart): void
 830    {
 831        if (!\is_array($multipart)) {
 832            self::warnInvalidRequestOptionType('multipart', 'array<array-key, array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}>', $multipart);
 833
 834            return;
 835        }
 836
 837        foreach ($multipart as $index => $part) {
 838            $path = 'multipart.'.(string) $index;
 839            if (!\is_array($part)) {
 840                self::warnInvalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}', $part);
 841
 842                return;
 843            }
 844
 845            if (!\array_key_exists('name', $part) || (!\is_string($part['name']) && !\is_int($part['name']))) {
 846                self::warnInvalidRequestOptionType($path.'.name', 'string|int', $part['name'] ?? null);
 847            }
 848
 849            if (!\array_key_exists('contents', $part)) {
 850                self::warnInvalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}', $part);
 851            }
 852
 853            if (\array_key_exists('headers', $part)) {
 854                if (!\is_array($part['headers'])) {
 855                    self::warnInvalidRequestOptionType($path.'.headers', 'array<array-key, string>', $part['headers']);
 856                } else {
 857                    foreach ($part['headers'] as $name => $value) {
 858                        if (!\is_string($value)) {
 859                            self::warnInvalidRequestOptionType($path.'.headers.'.(string) $name, 'string', $value);
 860
 861                            break 2;
 862                        }
 863                    }
 864                }
 865            }
 866
 867            if (\array_key_exists('filename', $part) && !\is_string($part['filename'])) {
 868                self::warnInvalidRequestOptionType($path.'.filename', 'string', $part['filename']);
 869            }
 870        }
 871    }
 872
 873    private static function warnAboutInvalidProxyOptionTypes(array $options): void
 874    {
 875        if (!isset($options['proxy'])) {
 876            return;
 877        }
 878
 879        if (!\is_string($options['proxy']) && !\is_array($options['proxy'])) {
 880            self::warnInvalidRequestOptionType('proxy', 'string|array{http?: string|null, https?: string|null, no?: string|array<array-key, string>|null}', $options['proxy']);
 881
 882            return;
 883        }
 884
 885        if (!\is_array($options['proxy'])) {
 886            return;
 887        }
 888
 889        foreach (['http', 'https'] as $scheme) {
 890            if (\array_key_exists($scheme, $options['proxy']) && $options['proxy'][$scheme] !== null && !\is_string($options['proxy'][$scheme])) {
 891                self::warnInvalidRequestOptionType('proxy.'.$scheme, 'string|null', $options['proxy'][$scheme]);
 892            }
 893        }
 894
 895        if (!\array_key_exists('no', $options['proxy']) || $options['proxy']['no'] === null) {
 896            return;
 897        }
 898
 899        if (\is_string($options['proxy']['no'])) {
 900            return;
 901        }
 902
 903        if (!\is_array($options['proxy']['no'])) {
 904            self::warnInvalidRequestOptionType('proxy.no', 'string|array<array-key, string>|null', $options['proxy']['no']);
 905
 906            return;
 907        }
 908
 909        foreach ($options['proxy']['no'] as $index => $noProxy) {
 910            if (!\is_string($noProxy)) {
 911                self::warnInvalidRequestOptionType('proxy.no.'.(string) $index, 'string', $noProxy);
 912
 913                return;
 914            }
 915        }
 916    }
 917
 918    private static function warnAboutInvalidTlsFileOptionTypes(array $options, string $option): void
 919    {
 920        if (!isset($options[$option])) {
 921            return;
 922        }
 923
 924        if (\is_string($options[$option])) {
 925            return;
 926        }
 927
 928        if (!\is_array($options[$option])) {
 929            self::warnInvalidRequestOptionType($option, 'string|array{0: string, 1?: string}', $options[$option]);
 930
 931            return;
 932        }
 933
 934        if (!\array_key_exists(0, $options[$option]) || !\is_string($options[$option][0])) {
 935            self::warnInvalidRequestOptionType($option.'.0', 'string', $options[$option][0] ?? null);
 936        }
 937
 938        if (\array_key_exists(1, $options[$option]) && $options[$option][1] !== null && !\is_string($options[$option][1])) {
 939            self::warnInvalidRequestOptionType($option.'.1', 'string|null', $options[$option][1]);
 940        }
 941    }
 942
 943    private static function warnIfPresentAndNotArray(array $options, string $option, string $expected): void
 944    {
 945        if (\array_key_exists($option, $options) && !\is_array($options[$option])) {
 946            self::warnInvalidRequestOptionType($option, $expected, $options[$option]);
 947        }
 948    }
 949
 950    private static function warnIfPresentAndNotBool(array $options, string $option, ?string $path = null): void
 951    {
 952        if (\array_key_exists($option, $options) && !\is_bool($options[$option])) {
 953            self::warnInvalidRequestOptionType($path ?? $option, 'bool', $options[$option]);
 954        }
 955    }
 956
 957    private static function warnIfPresentAndNotBoolOrInt(array $options, string $option): void
 958    {
 959        if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_int($options[$option])) {
 960            self::warnInvalidRequestOptionType($option, 'bool|int', $options[$option]);
 961        }
 962    }
 963
 964    private static function warnIfPresentAndNotBoolOrResource(array $options, string $option): void
 965    {
 966        if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_resource($options[$option])) {
 967            self::warnInvalidRequestOptionType($option, 'bool|resource', $options[$option]);
 968        }
 969    }
 970
 971    private static function warnIfPresentAndNotBoolOrString(array $options, string $option): void
 972    {
 973        if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_string($options[$option])) {
 974            self::warnInvalidRequestOptionType($option, 'bool|string', $options[$option]);
 975        }
 976    }
 977
 978    private static function warnIfPresentAndNotCallable(
 979        array $options,
 980        string $option,
 981        ?string $path = null,
 982        string $since = '7.11'
 983    ): void {
 984        if (\array_key_exists($option, $options) && !\is_callable($options[$option])) {
 985            self::warnInvalidRequestOptionType($path ?? $option, 'callable', $options[$option], $since);
 986        }
 987    }
 988
 989    private static function warnIfPresentAndNotInt(
 990        array $options,
 991        string $option,
 992        ?string $path = null,
 993        string $since = '7.11'
 994    ): void {
 995        if (\array_key_exists($option, $options) && !\is_int($options[$option])) {
 996            self::warnInvalidRequestOptionType($path ?? $option, 'int', $options[$option], $since);
 997        }
 998    }
 999
1000    private static function warnIfPresentAndNotNumber(array $options, string $option): void
1001    {
1002        if (\array_key_exists($option, $options) && !\is_int($options[$option]) && !\is_float($options[$option])) {
1003            self::warnInvalidRequestOptionType($option, 'int|float', $options[$option]);
1004        }
1005    }
1006
1007    private static function warnIfPresentAndNotString(array $options, string $option): void
1008    {
1009        if (\array_key_exists($option, $options) && !\is_string($options[$option])) {
1010            self::warnInvalidRequestOptionType($option, 'string', $options[$option]);
1011        }
1012    }
1013
1014    private static function warnIfPresentAndNotStringArray(array $options, string $option, bool $nonEmpty, ?string $path = null): void
1015    {
1016        if (!\array_key_exists($option, $options)) {
1017            return;
1018        }
1019
1020        $path = $path ?? $option;
1021        $expected = ($nonEmpty ? 'non-empty-' : '').'array<array-key, string>';
1022
1023        if (!\is_array($options[$option]) || ($nonEmpty && $options[$option] === [])) {
1024            self::warnInvalidRequestOptionType($path, $expected, $options[$option]);
1025
1026            return;
1027        }
1028
1029        foreach ($options[$option] as $index => $item) {
1030            if (!\is_string($item)) {
1031                self::warnInvalidRequestOptionType($path.'.'.(string) $index, 'string', $item);
1032
1033                return;
1034            }
1035        }
1036    }
1037
1038    /**
1039     * @param array<array-key, mixed> $options
1040     */
1041    private static function warnAboutInvalidProtocolValues(array $options, string $option, ?string $path = null): void
1042    {
1043        if (!isset($options[$option]) || !\is_array($options[$option])) {
1044            return;
1045        }
1046
1047        $path = $path ?? $option;
1048
1049        foreach ($options[$option] as $index => $protocol) {
1050            if (\is_string($protocol) && $protocol !== 'http' && $protocol !== 'https') {
1051                self::warnInvalidRequestOptionType($path.'.'.(string) $index, '"http"|"https"', $protocol, '7.13');
1052            }
1053        }
1054    }
1055
1056    private static function warnIfPresentAndNotStringOrNumber(array $options, string $option): void
1057    {
1058        if (
1059            \array_key_exists($option, $options)
1060            && !\is_string($options[$option])
1061            && !\is_int($options[$option])
1062            && !\is_float($options[$option])
1063        ) {
1064            self::warnInvalidRequestOptionType($option, 'string|int|float', $options[$option]);
1065        }
1066    }
1067
1068    /**
1069     * @param mixed $value
1070     */
1071    private static function warnInvalidRequestOptionType(string $option, string $expected, $value, string $since = '7.11'): void
1072    {
1073        \trigger_deprecation(
1074            'guzzlehttp/guzzle',
1075            $since,
1076            'Passing %s to request option "%s" is deprecated; guzzlehttp/guzzle 8.0 requires %s.',
1077            \get_debug_type($value),
1078            $option,
1079            $expected
1080        );
1081    }
1082
1083    /**
1084     * Transfers the given request and applies request options.
1085     *
1086     * The URI of the request is not modified and the request options are used
1087     * as-is without merging in default options.
1088     *
1089     * @param array $options See {@see RequestOptions}.
1090     */
1091    private function transfer(RequestInterface $request, array $options): PromiseInterface
1092    {
1093        $request = $this->applyOptions($request, $options);
1094
1095        $protocolVersion = $request->getProtocolVersion();
1096
1097        if ('' === $protocolVersion) {
1098            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
1099
1100            $request = Psr7\Utils::modifyRequest($request, ['version' => '1.1']);
1101        } elseif (!self::isProtocolVersionValid($protocolVersion)) {
1102            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with a malformed protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject malformed protocol versions.');
1103        }
1104
1105        /** @var HandlerStack $handler */
1106        $handler = $options['handler'];
1107
1108        try {
1109            return P\Create::promiseFor($handler($request, $options));
1110        } catch (\Exception $e) {
1111            return P\Create::rejectionFor($e);
1112        }
1113    }
1114
1115    /**
1116     * Applies the array of request options to a request.
1117     */
1118    private function applyOptions(RequestInterface $request, array &$options): RequestInterface
1119    {
1120        $modify = [
1121            'set_headers' => [],
1122        ];
1123
1124        if (isset($options['headers'])) {
1125            if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) {
1126                throw new InvalidArgumentException('The headers array must have header name as keys.');
1127            }
1128            $headers = $options['headers'];
1129            $droppedHeaderNames = self::castDeprecatedHeaderOptionValues($headers);
1130            if ($droppedHeaderNames !== [] && isset($options['_conditional'])) {
1131                $options['_conditional'] = Psr7\Utils::caselessRemove($droppedHeaderNames, $options['_conditional']);
1132            }
1133            $modify['set_headers'] = $headers;
1134            unset($options['headers']);
1135        }
1136
1137        if (isset($options['form_params'])) {
1138            if (isset($options['multipart'])) {
1139                throw new InvalidArgumentException('You cannot use '
1140                    .'form_params and multipart at the same time. Use the '
1141                    .'form_params option if you want to send application/'
1142                    .'x-www-form-urlencoded requests, and the multipart '
1143                    .'option to send multipart/form-data requests.');
1144            }
1145            $options['body'] = \http_build_query(self::normalizeNonFiniteFloats($options['form_params'], 'form_params'), '', '&');
1146            unset($options['form_params']);
1147            // Ensure that we don't have the header in different case and set the new value.
1148            $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
1149            $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
1150        }
1151
1152        if (isset($options['multipart'])) {
1153            $options['body'] = new Psr7\MultipartStream($options['multipart']);
1154            unset($options['multipart']);
1155        }
1156
1157        if (isset($options['json'])) {
1158            $json = \json_encode($options['json']);
1159            if (\JSON_ERROR_NONE !== \json_last_error()) {
1160                throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
1161            }
1162
1163            /** @var non-empty-string $json */
1164            $options['body'] = $json;
1165            unset($options['json']);
1166            // Ensure that we don't have the header in different case and set the new value.
1167            $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
1168            $options['_conditional']['Content-Type'] = 'application/json';
1169        }
1170
1171        if (isset($options['decode_content']) && \is_string($options['decode_content'])) {
1172            // Ensure that we don't have the header in different case and set the new value.
1173            $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']);
1174            $modify['set_headers']['Accept-Encoding'] = (string) $options['decode_content'];
1175        }
1176
1177        if (isset($options['body'])) {
1178            if (\is_array($options['body'])) {
1179                throw $this->invalidBody();
1180            }
1181            $modify['body'] = self::createBodyStream($options['body']);
1182            unset($options['body']);
1183        }
1184
1185        if (!empty($options['auth']) && \is_array($options['auth'])) {
1186            $value = $options['auth'];
1187            $type = isset($value[2]) ? Psr7\Utils::asciiToLower($value[2]) : 'basic';
1188            switch ($type) {
1189                case 'basic':
1190                    // Ensure that we don't have the header in different case and set the new value.
1191                    $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']);
1192                    $modify['set_headers']['Authorization'] = 'Basic '
1193                        .\base64_encode("$value[0]:$value[1]");
1194                    break;
1195                case 'digest':
1196                    // @todo: Do not rely on curl
1197                    $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST;
1198                    $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
1199                    break;
1200                case 'ntlm':
1201                    \trigger_deprecation(
1202                        'guzzlehttp/guzzle',
1203                        '7.12',
1204                        'Passing "ntlm" as the built-in auth type is deprecated; guzzlehttp/guzzle 8.0 will no longer apply NTLM through the "auth" request option. NTLM is also deprecated by curl/libcurl and may be unavailable in current or future libcurl builds. Avoid NTLM; if you must use it temporarily, configure cURL HTTP authentication options directly with a libcurl build that still supports NTLM.'
1205                    );
1206                    if (!CurlVersion::supportsNtlm()) {
1207                        throw new InvalidArgumentException('NTLM authentication is not available because the installed curl/libcurl build does not provide NTLM support.');
1208                    }
1209                    $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
1210                    $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
1211                    break;
1212            }
1213        }
1214
1215        if (isset($options['query'])) {
1216            $value = $options['query'];
1217            if (\is_array($value)) {
1218                $value = \http_build_query(self::normalizeNonFiniteFloats($value, 'query'), '', '&', \PHP_QUERY_RFC3986);
1219            }
1220            if (!\is_string($value)) {
1221                throw new InvalidArgumentException('query must be a string or array');
1222            }
1223            $modify['query'] = $value;
1224            unset($options['query']);
1225        }
1226
1227        // Ensure that sink is not an invalid value.
1228        if (isset($options['sink'])) {
1229            // TODO: Add more sink validation?
1230            if (\is_bool($options['sink'])) {
1231                throw new InvalidArgumentException('sink must not be a boolean');
1232            }
1233        }
1234
1235        if (isset($options['version'])) {
1236            $modify['version'] = self::normalizeProtocolVersion($options['version']);
1237        }
1238
1239        $request = Psr7\Utils::modifyRequest($request, $modify);
1240        if ($request->getBody() instanceof Psr7\MultipartStream) {
1241            // Use a multipart/form-data POST if a Content-Type is not set.
1242            // Ensure that we don't have the header in different case and set the new value.
1243            $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
1244            $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
1245                .$request->getBody()->getBoundary();
1246        }
1247
1248        // Merge in conditional headers if they are not present.
1249        if (isset($options['_conditional'])) {
1250            // Build up the changes so it's in a single clone of the message.
1251            $modify = [];
1252            foreach ($options['_conditional'] as $k => $v) {
1253                $name = (string) $k;
1254                if (!$request->hasHeader($name)) {
1255                    $modify['set_headers'][$name] = $v;
1256                }
1257            }
1258            $request = Psr7\Utils::modifyRequest($request, $modify);
1259            // Don't pass this internal value along to middleware/handlers.
1260            unset($options['_conditional']);
1261        }
1262
1263        return $request;
1264    }
1265
1266    /**
1267     * @param array<array-key, mixed> $headers
1268     *
1269     * @return list<string>
1270     */
1271    private static function castDeprecatedHeaderOptionValues(array &$headers): array
1272    {
1273        $droppedHeaderNames = [];
1274
1275        foreach ($headers as $name => $value) {
1276            if (\is_array($value)) {
1277                if ($value === []) {
1278                    $droppedHeaderNames[] = (string) $name;
1279                    unset($headers[$name]);
1280
1281                    continue;
1282                }
1283
1284                foreach ($value as $index => $item) {
1285                    if ($item === null || (!\is_string($item) && \is_scalar($item))) {
1286                        if (\is_float($item) && !\is_finite($item)) {
1287                            $item = \is_nan($item) ? 'NAN' : ($item > 0 ? 'INF' : '-INF');
1288                        }
1289                        $value[$index] = (string) $item;
1290                    }
1291                }
1292
1293                $headers[$name] = $value;
1294
1295                continue;
1296            }
1297
1298            if ($value === null || (!\is_string($value) && \is_scalar($value))) {
1299                if (\is_float($value) && !\is_finite($value)) {
1300                    $value = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
1301                }
1302                $headers[$name] = (string) $value;
1303            }
1304        }
1305
1306        return $droppedHeaderNames;
1307    }
1308
1309    /**
1310     * @param mixed $body
1311     */
1312    private static function createBodyStream($body): StreamInterface
1313    {
1314        if ($body instanceof StreamInterface) {
1315            return $body;
1316        }
1317
1318        if (\is_resource($body) || $body === null || \is_string($body) || $body instanceof \Iterator) {
1319            return Psr7\Utils::streamFor($body);
1320        }
1321
1322        if (\is_scalar($body)) {
1323            \trigger_deprecation('guzzlehttp/guzzle', '7.12', 'Passing a non-string scalar to the "body" request option is deprecated; guzzlehttp/guzzle 8.0 will reject non-string scalar bodies.');
1324
1325            return Psr7\Utils::streamFor(self::stringifyScalar($body));
1326        }
1327
1328        if (\is_object($body) && \method_exists($body, '__toString')) {
1329            return Psr7\Utils::streamFor((string) $body);
1330        }
1331
1332        if (\is_callable($body)) {
1333            return Psr7\Utils::streamFor($body);
1334        }
1335
1336        throw new InvalidArgumentException(\sprintf(
1337            'Passing %s to request option "body" is invalid; expected resource|string|null|int|float|bool|StreamInterface|callable&object|Iterator|Stringable.',
1338            \get_debug_type($body)
1339        ));
1340    }
1341
1342    /**
1343     * @param bool|float|int|string $value
1344     */
1345    private static function stringifyScalar($value): string
1346    {
1347        // Normalize non-finite floats to dodge PHP 8.5's (string) NAN
1348        // coercion warning while the value is still accepted.
1349        if (\is_float($value) && !\is_finite($value)) {
1350            $value = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
1351        }
1352
1353        return (string) $value;
1354    }
1355
1356    /**
1357     * Converts non-finite floats in the array to the strings PHP coerces
1358     * them to, as implicit coercion of NAN emits a warning on PHP 8.5.
1359     */
1360    private static function normalizeNonFiniteFloats(array $values, string $option): array
1361    {
1362        foreach ($values as $key => $value) {
1363            if (\is_array($value)) {
1364                $values[$key] = self::normalizeNonFiniteFloats($value, $option);
1365            } elseif (\is_float($value) && !\is_finite($value)) {
1366                \trigger_deprecation('guzzlehttp/guzzle', '7.12', 'Passing a non-finite float in the "%s" request option is deprecated; guzzlehttp/guzzle 8.0 will reject non-finite floats.', $option);
1367
1368                $values[$key] = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
1369            }
1370        }
1371
1372        return $values;
1373    }
1374
1375    /**
1376     * @param string|int|float $version
1377     */
1378    private static function normalizeProtocolVersion($version): string
1379    {
1380        if ('' === $version) {
1381            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing an empty "version" request option is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
1382
1383            return '1.1';
1384        }
1385
1386        return \is_float($version) ? \number_format($version, 1, '.', '') : (string) $version;
1387    }
1388
1389    private static function isProtocolVersionValid(string $version): bool
1390    {
1391        return 1 === \preg_match('/^\d+(?:\.\d+)?$/D', $version);
1392    }
1393
1394    /**
1395     * Return an InvalidArgumentException with pre-set message.
1396     */
1397    private function invalidBody(): InvalidArgumentException
1398    {
1399        return new InvalidArgumentException('Passing in the "body" request '
1400            .'option as an array to send a request is not supported. '
1401            .'Please use the "form_params" request option to send a '
1402            .'application/x-www-form-urlencoded request, or the "multipart" '
1403            .'request option to send a multipart/form-data request.');
1404    }
1405}