Debian Codegraph @

lib/3rdParty/composer/guzzlehttp/guzzle/src/Client.php

raw symbols SCIP
1 <?php
2
3 namespace GuzzleHttp;
4
5 use GuzzleHttp\Cookie\CookieJar;
6 use GuzzleHttp\Exception\GuzzleException;
7 use GuzzleHttp\Exception\InvalidArgumentException;
8 use GuzzleHttp\Handler\CurlShareHandleState;
9 use GuzzleHttp\Promise as P;
10 use GuzzleHttp\Promise\PromiseInterface;
11 use Psr\Http\Message\RequestInterface;
12 use Psr\Http\Message\ResponseInterface;
13 use Psr\Http\Message\StreamInterface;
14 use Psr\Http\Message\UriInterface;
15
16 /**
17 * @final
18 */
19 class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
20 {
21 use ClientTrait;
22
23 /**
24 * @var array Default request options
25 */
26 private $config;
27
28 /**
29 * Clients accept an array of constructor parameters.
30 *
31 * Here's an example of creating a client using a base_uri and an array of
32 * default request options to apply to each request:
33 *
34 * $client = new Client([
35 * 'base_uri' => 'http://www.foo.com/1.0/',
36 * 'timeout' => 0,
37 * 'allow_redirects' => false,
38 * 'proxy' => '192.168.16.1:10'
39 * ]);
40 *
41 * Client configuration settings include the following options:
42 *
43 * - handler: (callable) Function that transfers HTTP requests over the
44 * wire. The function is called with a Psr7\Http\Message\RequestInterface
45 * and array of transfer options, and must return a
46 * GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
47 * Psr7\Http\Message\ResponseInterface on success.
48 * If no handler is provided, a default handler will be created
49 * that enables all of the request options below by attaching all of the
50 * default middleware to the handler.
51 * - base_uri: (string|UriInterface) Base URI of the client that is merged
52 * into relative URIs. Can be a string or instance of UriInterface.
53 * - transport_sharing: (string|null) Transport sharing mode for the
54 * default handler. Accepts TransportSharing::* or null. Defaults to null.
55 * - **: any request option
56 *
57 * @param array $config Client configuration settings.
58 *
59 * @see RequestOptions for a list of available request options.
60 */
61 public function __construct(array $config = [])
62 {
63 $transportSharing = \array_key_exists('transport_sharing', $config) ? $config['transport_sharing'] : null;
64 $transportSharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
65 unset($config['transport_sharing']);
66
67 if (!isset($config['handler'])) {
68 $config['handler'] = $transportSharingMode === TransportSharing::NONE
69 ? HandlerStack::create()
70 : HandlerStack::create(Utils::chooseHandler(['transport_sharing' => $transportSharingMode]));
71 } elseif (!\is_callable($config['handler'])) {
72 throw new InvalidArgumentException('handler must be a callable');
73 } elseif ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
74 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.');
75 }
76
77 // Convert the base_uri to a UriInterface
78 if (isset($config['base_uri'])) {
79 $config['base_uri'] = Psr7\Utils::uriFor($config['base_uri']);
80 }
81
82 $this->configureDefaults($config);
83 }
84
85 /**
86 * @param string $method
87 * @param array $args
88 *
89 * @return PromiseInterface|ResponseInterface
90 *
91 * @deprecated Client::__call will be removed in guzzlehttp/guzzle:8.0.
92 */
93 public function __call($method, $args)
94 {
95 if (\count($args) < 1) {
96 throw new InvalidArgumentException('Magic request methods require a URI and optional options array');
97 }
98
99 $uri = $args[0];
100 $opts = $args[1] ?? [];
101
102 $isAsync = \substr($method, -5) === 'Async';
103 $method = $isAsync ? \substr($method, 0, -5) : $method;
104 $method = \strtoupper($method);
105
106 return $isAsync
107 ? $this->requestAsync($method, $uri, $opts)
108 : $this->request($method, $uri, $opts);
109 }
110
111 /**
112 * Asynchronously send an HTTP request.
113 *
114 * @param array $options Request options to apply to the given
115 * request and to the transfer. See {@see RequestOptions}.
116 */
117 public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface
118 {
119 // Merge the base URI into the request URI if needed.
120 $options = $this->prepareDefaults($options);
121
122 return $this->transfer(
123 $request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
124 $options
125 );
126 }
127
128 /**
129 * Send an HTTP request.
130 *
131 * @param array $options Request options to apply to the given
132 * request and to the transfer. See {@see RequestOptions}.
133 *
134 * @throws GuzzleException
135 */
136 public function send(RequestInterface $request, array $options = []): ResponseInterface
137 {
138 $options[RequestOptions::SYNCHRONOUS] = true;
139
140 return $this->sendAsync($request, $options)->wait();
141 }
142
143 /**
144 * The HttpClient PSR (PSR-18) specify this method.
145 *
146 * {@inheritDoc}
147 */
148 public function sendRequest(RequestInterface $request): ResponseInterface
149 {
150 $options[RequestOptions::SYNCHRONOUS] = true;
151 $options[RequestOptions::ALLOW_REDIRECTS] = false;
152 $options[RequestOptions::HTTP_ERRORS] = false;
153
154 return $this->sendAsync($request, $options)->wait();
155 }
156
157 /**
158 * Create and send an asynchronous HTTP request.
159 *
160 * Use an absolute path to override the base path of the client, or a
161 * relative path to append to the base path of the client. The URL can
162 * contain the query string as well. Use an array to provide a URL
163 * template and additional variables to use in the URL template expansion.
164 *
165 * @param string $method HTTP method
166 * @param string|UriInterface $uri URI object or string.
167 * @param array $options Request options to apply. See {@see RequestOptions}.
168 */
169 public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface
170 {
171 $normalizedMethod = \strtoupper($method);
172 if ($method !== $normalizedMethod) {
173 \trigger_deprecation(
174 'guzzlehttp/guzzle',
175 '7.11',
176 '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.'
177 );
178 $method = $normalizedMethod;
179 }
180
181 $options = $this->prepareDefaults($options);
182 // Remove request modifying parameter because it can be done up-front.
183 $headers = $options['headers'] ?? [];
184 $droppedHeaderNames = self::castDeprecatedHeaderOptionValues($headers);
185 if ($droppedHeaderNames !== [] && isset($options['_conditional'])) {
186 $options['_conditional'] = Psr7\Utils::caselessRemove($droppedHeaderNames, $options['_conditional']);
187 }
188 $body = $options['body'] ?? null;
189 $version = self::normalizeProtocolVersion($options['version'] ?? '1.1');
190 // Merge the URI into the base URI.
191 $uri = $this->buildUri(Psr7\Utils::uriFor($uri), $options);
192 if (\is_array($body)) {
193 throw $this->invalidBody();
194 }
195 $request = new Psr7\Request($method, $uri, $headers, $body, $version);
196 // Remove the option so that they are not doubly-applied.
197 unset($options['headers'], $options['body'], $options['version']);
198
199 return $this->transfer($request, $options);
200 }
201
202 /**
203 * Create and send an HTTP request.
204 *
205 * Use an absolute path to override the base path of the client, or a
206 * relative path to append to the base path of the client. The URL can
207 * contain the query string as well.
208 *
209 * @param string $method HTTP method.
210 * @param string|UriInterface $uri URI object or string.
211 * @param array $options Request options to apply. See {@see RequestOptions}.
212 *
213 * @throws GuzzleException
214 */
215 public function request(string $method, $uri = '', array $options = []): ResponseInterface
216 {
217 $normalizedMethod = \strtoupper($method);
218 if ($method !== $normalizedMethod) {
219 \trigger_deprecation(
220 'guzzlehttp/guzzle',
221 '7.11',
222 '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.'
223 );
224 $method = $normalizedMethod;
225 }
226
227 $options[RequestOptions::SYNCHRONOUS] = true;
228
229 return $this->requestAsync($method, $uri, $options)->wait();
230 }
231
232 /**
233 * Get a client configuration option.
234 *
235 * These options include default request options of the client, a "handler"
236 * (if utilized by the concrete client), and a "base_uri" if utilized by
237 * the concrete client.
238 *
239 * @param string|null $option The config option to retrieve.
240 *
241 * @return mixed
242 */
243 public function getConfig(?string $option = null)
244 {
245 return $option === null
246 ? $this->config
247 : ($this->config[$option] ?? null);
248 }
249
250 private function buildUri(UriInterface $uri, array $config): UriInterface
251 {
252 if (isset($config['base_uri'])) {
253 $uri = Psr7\UriResolver::resolve(Psr7\Utils::uriFor($config['base_uri']), $uri);
254 }
255
256 $idnOptions = Utils::normalizeIdnConversionOption($config['idn_conversion'] ?? null);
257 if ($idnOptions !== null) {
258 $uri = Utils::idnUriConvert($uri, $idnOptions);
259 }
260
261 return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
262 }
263
264 /**
265 * Configures the default options for a client.
266 */
267 private function configureDefaults(array $config): void
268 {
269 $defaults = [
270 'allow_redirects' => RedirectMiddleware::$defaultSettings,
271 'http_errors' => true,
272 'decode_content' => true,
273 'verify' => true,
274 'cookies' => false,
275 'idn_conversion' => false,
276 'protocols' => ['http', 'https'],
277 ];
278
279 // Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
280
281 // We can only trust the HTTP_PROXY environment variable in a CLI
282 // process due to the fact that PHP has no reliable mechanism to
283 // get environment variables that start with "HTTP_".
284 if (\PHP_SAPI === 'cli' && ($proxy = Utils::getenv('HTTP_PROXY'))) {
285 $defaults['proxy']['http'] = $proxy;
286 }
287
288 if ($proxy = Utils::getenv('HTTPS_PROXY')) {
289 $defaults['proxy']['https'] = $proxy;
290 }
291
292 if ($noProxy = Utils::getenv('NO_PROXY')) {
293 $cleanedNoProxy = \str_replace(' ', '', $noProxy);
294 $defaults['proxy']['no'] = \explode(',', $cleanedNoProxy);
295 }
296
297 $this->config = $config + $defaults;
298
299 if (!empty($config['cookies']) && $config['cookies'] === true) {
300 $this->config['cookies'] = new CookieJar();
301 }
302
303 // Add the default user-agent header.
304 if (!isset($this->config['headers'])) {
305 $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()];
306 } else {
307 // Add the User-Agent header if one was not already set.
308 $hasUserAgent = false;
309 foreach (\array_keys($this->config['headers']) as $name) {
310 if (\strtolower((string) $name) === 'user-agent') {
311 $hasUserAgent = true;
312 break;
313 }
314 }
315
316 if (!$hasUserAgent) {
317 $this->config['headers']['User-Agent'] = Utils::defaultUserAgent();
318 }
319 }
320
321 if (\is_array($this->config['headers'])) {
322 self::warnAboutInvalidHeaderOptionTypes($this->config['headers']);
323 self::castDeprecatedHeaderOptionValues($this->config['headers']);
324 }
325 }
326
327 /**
328 * Merges default options into the array.
329 *
330 * @param array $options Options to modify by reference
331 */
332 private function prepareDefaults(array $options): array
333 {
334 $defaults = $this->config;
335
336 if (!empty($defaults['headers'])) {
337 // Default headers are only added if they are not present.
338 $defaults['_conditional'] = $defaults['headers'];
339 unset($defaults['headers']);
340 }
341
342 // Special handling for headers is required as they are added as
343 // conditional headers and as headers passed to a request ctor.
344 if (\array_key_exists('headers', $options)) {
345 // Allows default headers to be unset.
346 if ($options['headers'] === null) {
347 $defaults['_conditional'] = [];
348 unset($options['headers']);
349 } elseif (!\is_array($options['headers'])) {
350 throw new InvalidArgumentException('headers must be an array');
351 }
352 }
353
354 // Shallow merge defaults underneath options.
355 $result = $options + $defaults;
356
357 // Remove null values.
358 foreach ($result as $k => $v) {
359 if ($v === null) {
360 unset($result[$k]);
361 }
362 }
363
364 self::warnAboutInvalidRequestOptionTypes($result);
365
366 return $result;
367 }
368
369 private static function warnAboutInvalidRequestOptionTypes(array $options): void
370 {
371 if (isset($options['handler']) && !\is_callable($options['handler'])) {
372 self::warnInvalidRequestOptionType('handler', 'callable', $options['handler']);
373 }
374
375 if (isset($options['allow_redirects']) && \is_array($options['allow_redirects'])) {
376 self::warnAboutInvalidAllowRedirectsOptionTypes($options['allow_redirects']);
377 }
378
379 if (isset($options['auth'])) {
380 self::warnAboutInvalidAuthOptionTypes($options['auth']);
381 }
382
383 if (isset($options['body']) && \is_array($options['body'])) {
384 self::warnInvalidRequestOptionType('body', 'resource|string|null|int|float|bool|StreamInterface|(callable&object)|\Iterator|\Stringable', $options['body']);
385 }
386
387 self::warnAboutInvalidTlsFileOptionTypes($options, 'cert');
388 self::warnIfPresentAndNotString($options, 'cert_type');
389 self::warnIfPresentAndNotNumber($options, 'connect_timeout');
390 self::warnIfPresentAndNotInt($options, 'crypto_method');
391 self::warnIfPresentAndNotBoolOrResource($options, 'debug');
392 self::warnIfPresentAndNotBoolOrString($options, 'decode_content');
393 self::warnIfPresentAndNotNumber($options, 'delay');
394 self::warnIfPresentAndNotBoolOrInt($options, 'expect');
395
396 if (isset($options['form_params'])) {
397 self::warnAboutInvalidFormParamTypes($options['form_params']);
398 }
399
400 if (isset($options['force_ip_resolve']) && !\is_string($options['force_ip_resolve'])) {
401 self::warnInvalidRequestOptionType('force_ip_resolve', 'string', $options['force_ip_resolve']);
402 }
403
404 if (isset($options['headers'])) {
405 self::warnAboutInvalidHeaderOptionTypes($options['headers']);
406 }
407
408 self::warnIfPresentAndNotBool($options, 'http_errors');
409
410 if (isset($options['multipart'])) {
411 self::warnAboutInvalidMultipartOptionTypes($options['multipart']);
412 }
413
414 self::warnIfPresentAndNotCallable($options, 'on_headers');
415 self::warnIfPresentAndNotCallable($options, 'on_stats');
416 self::warnIfPresentAndNotCallable($options, 'progress');
417 self::warnIfPresentAndNotStringArray($options, 'protocols', true);
418 self::warnAboutInvalidProxyOptionTypes($options);
419
420 self::warnIfPresentAndNotNumber($options, 'read_timeout');
421 self::warnIfPresentAndNotInt($options, 'retries');
422
423 if (isset($options['sink']) && !\is_bool($options['sink']) && !\is_resource($options['sink']) && !\is_string($options['sink']) && !$options['sink'] instanceof StreamInterface) {
424 self::warnInvalidRequestOptionType('sink', 'resource|string|StreamInterface', $options['sink']);
425 }
426
427 self::warnAboutInvalidTlsFileOptionTypes($options, 'ssl_key');
428 self::warnIfPresentAndNotString($options, 'ssl_key_type');
429 self::warnIfPresentAndNotBool($options, 'stream');
430 self::warnIfPresentAndNotArray($options, 'stream_context', 'array<array-key, mixed>');
431 self::warnIfPresentAndNotBool($options, 'synchronous');
432 self::warnIfPresentAndNotNumber($options, 'timeout');
433 self::warnIfPresentAndNotBoolOrString($options, 'verify');
434 self::warnIfPresentAndNotStringOrNumber($options, 'version');
435 self::warnIfPresentAndNotArray($options, 'curl', 'array<int|string, mixed>');
436
437 if (isset($options['cookies']) && $options['cookies'] === true) {
438 self::warnInvalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies']);
439 }
440 }
441
442 private static function warnAboutInvalidAllowRedirectsOptionTypes(array $allowRedirects): void
443 {
444 self::warnIfPresentAndNotInt($allowRedirects, 'max', 'allow_redirects.max');
445 self::warnIfPresentAndNotBool($allowRedirects, 'strict', 'allow_redirects.strict');
446 self::warnIfPresentAndNotBool($allowRedirects, 'referer', 'allow_redirects.referer');
447 self::warnIfPresentAndNotStringArray($allowRedirects, 'protocols', true, 'allow_redirects.protocols');
448 self::warnIfPresentAndNotCallable($allowRedirects, 'on_redirect', 'allow_redirects.on_redirect');
449 self::warnIfPresentAndNotBool($allowRedirects, 'track_redirects', 'allow_redirects.track_redirects');
450 }
451
452 /**
453 * @param mixed $auth
454 */
455 private static function warnAboutInvalidAuthOptionTypes($auth): void
456 {
457 if ($auth === false || \is_string($auth) || $auth === []) {
458 return;
459 }
460
461 if (!\is_array($auth)) {
462 self::warnInvalidRequestOptionType('auth', 'array{0: string, 1: string, 2?: string|null}|string|false|null', $auth);
463
464 return;
465 }
466
467 if (!\array_key_exists(0, $auth) || !\is_string($auth[0])) {
468 self::warnInvalidRequestOptionType('auth.0', 'string', $auth[0] ?? null);
469 }
470
471 if (!\array_key_exists(1, $auth) || !\is_string($auth[1])) {
472 self::warnInvalidRequestOptionType('auth.1', 'string', $auth[1] ?? null);
473 }
474
475 if (\array_key_exists(2, $auth) && $auth[2] !== null && !\is_string($auth[2])) {
476 self::warnInvalidRequestOptionType('auth.2', 'string|null', $auth[2]);
477 }
478 }
479
480 /**
481 * @param mixed $value
482 */
483 private static function warnAboutInvalidFormParamTypes($value): void
484 {
485 if (!\is_array($value)) {
486 self::warnInvalidRequestOptionType('form_params', 'array<array-key, string|int|float|bool|null|array>', $value);
487
488 return;
489 }
490
491 self::warnAboutInvalidFormParamArray($value, 'form_params');
492 }
493
494 private static function warnAboutInvalidFormParamArray(array $values, string $path): bool
495 {
496 foreach ($values as $key => $item) {
497 $itemPath = $path.'.'.(string) $key;
498 if (\is_array($item)) {
499 if (!self::warnAboutInvalidFormParamArray($item, $itemPath)) {
500 return false;
501 }
502
503 continue;
504 }
505
506 if ($item !== null && !\is_scalar($item)) {
507 self::warnInvalidRequestOptionType($itemPath, 'string|int|float|bool|null|array', $item);
508
509 return false;
510 }
511 }
512
513 return true;
514 }
515
516 /**
517 * @param mixed $headers
518 */
519 private static function warnAboutInvalidHeaderOptionTypes($headers): void
520 {
521 if (!\is_array($headers)) {
522 self::warnInvalidRequestOptionType('headers', 'array<array-key, string|non-empty-array<array-key, string>>|null', $headers);
523
524 return;
525 }
526
527 foreach ($headers as $name => $value) {
528 $path = 'headers.'.(string) $name;
529 if (\is_array($value)) {
530 if ($value === []) {
531 self::warnInvalidRequestOptionType($path, 'string|non-empty-array<array-key, string>', $value);
532
533 break;
534 }
535
536 foreach ($value as $index => $item) {
537 if (!\is_string($item)) {
538 self::warnInvalidRequestOptionType($path.'.'.(string) $index, 'string', $item);
539
540 break 2;
541 }
542 }
543 } elseif (!\is_string($value)) {
544 self::warnInvalidRequestOptionType($path, 'string|non-empty-array<array-key, string>', $value);
545
546 break;
547 }
548 }
549 }
550
551 /**
552 * @param mixed $multipart
553 */
554 private static function warnAboutInvalidMultipartOptionTypes($multipart): void
555 {
556 if (!\is_array($multipart)) {
557 self::warnInvalidRequestOptionType('multipart', 'array<array-key, array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}>', $multipart);
558
559 return;
560 }
561
562 foreach ($multipart as $index => $part) {
563 $path = 'multipart.'.(string) $index;
564 if (!\is_array($part)) {
565 self::warnInvalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}', $part);
566
567 return;
568 }
569
570 if (!\array_key_exists('name', $part) || (!\is_string($part['name']) && !\is_int($part['name']))) {
571 self::warnInvalidRequestOptionType($path.'.name', 'string|int', $part['name'] ?? null);
572 }
573
574 if (!\array_key_exists('contents', $part)) {
575 self::warnInvalidRequestOptionType($path, 'array{name: string|int, contents: mixed, headers?: array<array-key, string>, filename?: string}', $part);
576 }
577
578 if (\array_key_exists('headers', $part)) {
579 if (!\is_array($part['headers'])) {
580 self::warnInvalidRequestOptionType($path.'.headers', 'array<array-key, string>', $part['headers']);
581 } else {
582 foreach ($part['headers'] as $name => $value) {
583 if (!\is_string($value)) {
584 self::warnInvalidRequestOptionType($path.'.headers.'.(string) $name, 'string', $value);
585
586 break 2;
587 }
588 }
589 }
590 }
591
592 if (\array_key_exists('filename', $part) && !\is_string($part['filename'])) {
593 self::warnInvalidRequestOptionType($path.'.filename', 'string', $part['filename']);
594 }
595 }
596 }
597
598 private static function warnAboutInvalidProxyOptionTypes(array $options): void
599 {
600 if (!isset($options['proxy'])) {
601 return;
602 }
603
604 if (!\is_string($options['proxy']) && !\is_array($options['proxy'])) {
605 self::warnInvalidRequestOptionType('proxy', 'string|array{http?: string|null, https?: string|null, no?: string|array<array-key, string>|null}', $options['proxy']);
606
607 return;
608 }
609
610 if (!\is_array($options['proxy'])) {
611 return;
612 }
613
614 foreach (['http', 'https'] as $scheme) {
615 if (\array_key_exists($scheme, $options['proxy']) && $options['proxy'][$scheme] !== null && !\is_string($options['proxy'][$scheme])) {
616 self::warnInvalidRequestOptionType('proxy.'.$scheme, 'string|null', $options['proxy'][$scheme]);
617 }
618 }
619
620 if (!\array_key_exists('no', $options['proxy']) || $options['proxy']['no'] === null) {
621 return;
622 }
623
624 if (\is_string($options['proxy']['no'])) {
625 return;
626 }
627
628 if (!\is_array($options['proxy']['no'])) {
629 self::warnInvalidRequestOptionType('proxy.no', 'string|array<array-key, string>|null', $options['proxy']['no']);
630
631 return;
632 }
633
634 foreach ($options['proxy']['no'] as $index => $noProxy) {
635 if (!\is_string($noProxy)) {
636 self::warnInvalidRequestOptionType('proxy.no.'.(string) $index, 'string', $noProxy);
637
638 return;
639 }
640 }
641 }
642
643 private static function warnAboutInvalidTlsFileOptionTypes(array $options, string $option): void
644 {
645 if (!isset($options[$option])) {
646 return;
647 }
648
649 if (\is_string($options[$option])) {
650 return;
651 }
652
653 if (!\is_array($options[$option])) {
654 self::warnInvalidRequestOptionType($option, 'string|array{0: string, 1?: string}', $options[$option]);
655
656 return;
657 }
658
659 if (!\array_key_exists(0, $options[$option]) || !\is_string($options[$option][0])) {
660 self::warnInvalidRequestOptionType($option.'.0', 'string', $options[$option][0] ?? null);
661 }
662
663 if (\array_key_exists(1, $options[$option]) && $options[$option][1] !== null && !\is_string($options[$option][1])) {
664 self::warnInvalidRequestOptionType($option.'.1', 'string|null', $options[$option][1]);
665 }
666 }
667
668 private static function warnIfPresentAndNotArray(array $options, string $option, string $expected): void
669 {
670 if (\array_key_exists($option, $options) && !\is_array($options[$option])) {
671 self::warnInvalidRequestOptionType($option, $expected, $options[$option]);
672 }
673 }
674
675 private static function warnIfPresentAndNotBool(array $options, string $option, ?string $path = null): void
676 {
677 if (\array_key_exists($option, $options) && !\is_bool($options[$option])) {
678 self::warnInvalidRequestOptionType($path ?? $option, 'bool', $options[$option]);
679 }
680 }
681
682 private static function warnIfPresentAndNotBoolOrInt(array $options, string $option): void
683 {
684 if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_int($options[$option])) {
685 self::warnInvalidRequestOptionType($option, 'bool|int', $options[$option]);
686 }
687 }
688
689 private static function warnIfPresentAndNotBoolOrResource(array $options, string $option): void
690 {
691 if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_resource($options[$option])) {
692 self::warnInvalidRequestOptionType($option, 'bool|resource', $options[$option]);
693 }
694 }
695
696 private static function warnIfPresentAndNotBoolOrString(array $options, string $option): void
697 {
698 if (\array_key_exists($option, $options) && !\is_bool($options[$option]) && !\is_string($options[$option])) {
699 self::warnInvalidRequestOptionType($option, 'bool|string', $options[$option]);
700 }
701 }
702
703 private static function warnIfPresentAndNotCallable(array $options, string $option, ?string $path = null): void
704 {
705 if (\array_key_exists($option, $options) && !\is_callable($options[$option])) {
706 self::warnInvalidRequestOptionType($path ?? $option, 'callable', $options[$option]);
707 }
708 }
709
710 private static function warnIfPresentAndNotInt(array $options, string $option, ?string $path = null): void
711 {
712 if (\array_key_exists($option, $options) && !\is_int($options[$option])) {
713 self::warnInvalidRequestOptionType($path ?? $option, 'int', $options[$option]);
714 }
715 }
716
717 private static function warnIfPresentAndNotNumber(array $options, string $option): void
718 {
719 if (\array_key_exists($option, $options) && !\is_int($options[$option]) && !\is_float($options[$option])) {
720 self::warnInvalidRequestOptionType($option, 'int|float', $options[$option]);
721 }
722 }
723
724 private static function warnIfPresentAndNotString(array $options, string $option): void
725 {
726 if (\array_key_exists($option, $options) && !\is_string($options[$option])) {
727 self::warnInvalidRequestOptionType($option, 'string', $options[$option]);
728 }
729 }
730
731 private static function warnIfPresentAndNotStringArray(array $options, string $option, bool $nonEmpty, ?string $path = null): void
732 {
733 if (!\array_key_exists($option, $options)) {
734 return;
735 }
736
737 $path = $path ?? $option;
738 $expected = ($nonEmpty ? 'non-empty-' : '').'array<array-key, string>';
739
740 if (!\is_array($options[$option]) || ($nonEmpty && $options[$option] === [])) {
741 self::warnInvalidRequestOptionType($path, $expected, $options[$option]);
742
743 return;
744 }
745
746 foreach ($options[$option] as $index => $item) {
747 if (!\is_string($item)) {
748 self::warnInvalidRequestOptionType($path.'.'.(string) $index, 'string', $item);
749
750 return;
751 }
752 }
753 }
754
755 private static function warnIfPresentAndNotStringOrNumber(array $options, string $option): void
756 {
757 if (
758 \array_key_exists($option, $options)
759 && !\is_string($options[$option])
760 && !\is_int($options[$option])
761 && !\is_float($options[$option])
762 ) {
763 self::warnInvalidRequestOptionType($option, 'string|int|float', $options[$option]);
764 }
765 }
766
767 /**
768 * @param mixed $value
769 */
770 private static function warnInvalidRequestOptionType(string $option, string $expected, $value): void
771 {
772 \trigger_deprecation(
773 'guzzlehttp/guzzle',
774 '7.11',
775 'Passing %s to request option "%s" is deprecated; guzzlehttp/guzzle 8.0 requires %s.',
776 \get_debug_type($value),
777 $option,
778 $expected
779 );
780 }
781
782 /**
783 * Transfers the given request and applies request options.
784 *
785 * The URI of the request is not modified and the request options are used
786 * as-is without merging in default options.
787 *
788 * @param array $options See {@see RequestOptions}.
789 */
790 private function transfer(RequestInterface $request, array $options): PromiseInterface
791 {
792 $request = $this->applyOptions($request, $options);
793
794 $protocolVersion = $request->getProtocolVersion();
795
796 if ('' === $protocolVersion) {
797 \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.');
798
799 $request = Psr7\Utils::modifyRequest($request, ['version' => '1.1']);
800 } elseif (!self::isProtocolVersionValid($protocolVersion)) {
801 \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.');
802 }
803
804 /** @var HandlerStack $handler */
805 $handler = $options['handler'];
806
807 try {
808 return P\Create::promiseFor($handler($request, $options));
809 } catch (\Exception $e) {
810 return P\Create::rejectionFor($e);
811 }
812 }
813
814 /**
815 * Applies the array of request options to a request.
816 */
817 private function applyOptions(RequestInterface $request, array &$options): RequestInterface
818 {
819 $modify = [
820 'set_headers' => [],
821 ];
822
823 if (isset($options['headers'])) {
824 if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) {
825 throw new InvalidArgumentException('The headers array must have header name as keys.');
826 }
827 $headers = $options['headers'];
828 $droppedHeaderNames = self::castDeprecatedHeaderOptionValues($headers);
829 if ($droppedHeaderNames !== [] && isset($options['_conditional'])) {
830 $options['_conditional'] = Psr7\Utils::caselessRemove($droppedHeaderNames, $options['_conditional']);
831 }
832 $modify['set_headers'] = $headers;
833 unset($options['headers']);
834 }
835
836 if (isset($options['form_params'])) {
837 if (isset($options['multipart'])) {
838 throw new InvalidArgumentException('You cannot use '
839 .'form_params and multipart at the same time. Use the '
840 .'form_params option if you want to send application/'
841 .'x-www-form-urlencoded requests, and the multipart '
842 .'option to send multipart/form-data requests.');
843 }
844 $options['body'] = \http_build_query($options['form_params'], '', '&');
845 unset($options['form_params']);
846 // Ensure that we don't have the header in different case and set the new value.
847 $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
848 $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
849 }
850
851 if (isset($options['multipart'])) {
852 $options['body'] = new Psr7\MultipartStream($options['multipart']);
853 unset($options['multipart']);
854 }
855
856 if (isset($options['json'])) {
857 $options['body'] = Utils::jsonEncode($options['json']);
858 unset($options['json']);
859 // Ensure that we don't have the header in different case and set the new value.
860 $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
861 $options['_conditional']['Content-Type'] = 'application/json';
862 }
863
864 if (!empty($options['decode_content'])
865 && $options['decode_content'] !== true
866 ) {
867 // Ensure that we don't have the header in different case and set the new value.
868 $options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']);
869 $modify['set_headers']['Accept-Encoding'] = (string) $options['decode_content'];
870 }
871
872 if (isset($options['body'])) {
873 if (\is_array($options['body'])) {
874 throw $this->invalidBody();
875 }
876 $modify['body'] = Psr7\Utils::streamFor($options['body']);
877 unset($options['body']);
878 }
879
880 if (!empty($options['auth']) && \is_array($options['auth'])) {
881 $value = $options['auth'];
882 $type = isset($value[2]) ? \strtolower($value[2]) : 'basic';
883 switch ($type) {
884 case 'basic':
885 // Ensure that we don't have the header in different case and set the new value.
886 $modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']);
887 $modify['set_headers']['Authorization'] = 'Basic '
888 .\base64_encode("$value[0]:$value[1]");
889 break;
890 case 'digest':
891 // @todo: Do not rely on curl
892 $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_DIGEST;
893 $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
894 break;
895 case 'ntlm':
896 $options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
897 $options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
898 break;
899 }
900 }
901
902 if (isset($options['query'])) {
903 $value = $options['query'];
904 if (\is_array($value)) {
905 $value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986);
906 }
907 if (!\is_string($value)) {
908 throw new InvalidArgumentException('query must be a string or array');
909 }
910 $modify['query'] = $value;
911 unset($options['query']);
912 }
913
914 // Ensure that sink is not an invalid value.
915 if (isset($options['sink'])) {
916 // TODO: Add more sink validation?
917 if (\is_bool($options['sink'])) {
918 throw new InvalidArgumentException('sink must not be a boolean');
919 }
920 }
921
922 if (isset($options['version'])) {
923 $modify['version'] = self::normalizeProtocolVersion($options['version']);
924 }
925
926 $request = Psr7\Utils::modifyRequest($request, $modify);
927 if ($request->getBody() instanceof Psr7\MultipartStream) {
928 // Use a multipart/form-data POST if a Content-Type is not set.
929 // Ensure that we don't have the header in different case and set the new value.
930 $options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
931 $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
932 .$request->getBody()->getBoundary();
933 }
934
935 // Merge in conditional headers if they are not present.
936 if (isset($options['_conditional'])) {
937 // Build up the changes so it's in a single clone of the message.
938 $modify = [];
939 foreach ($options['_conditional'] as $k => $v) {
940 $name = (string) $k;
941 if (!$request->hasHeader($name)) {
942 $modify['set_headers'][$name] = $v;
943 }
944 }
945 $request = Psr7\Utils::modifyRequest($request, $modify);
946 // Don't pass this internal value along to middleware/handlers.
947 unset($options['_conditional']);
948 }
949
950 return $request;
951 }
952
953 /**
954 * @param array<array-key, mixed> $headers
955 *
956 * @return list<string>
957 */
958 private static function castDeprecatedHeaderOptionValues(array &$headers): array
959 {
960 $droppedHeaderNames = [];
961
962 foreach ($headers as $name => $value) {
963 if (\is_array($value)) {
964 if ($value === []) {
965 $droppedHeaderNames[] = (string) $name;
966 unset($headers[$name]);
967
968 continue;
969 }
970
971 foreach ($value as $index => $item) {
972 if ($item === null || (!\is_string($item) && \is_scalar($item))) {
973 $value[$index] = (string) $item;
974 }
975 }
976
977 $headers[$name] = $value;
978
979 continue;
980 }
981
982 if ($value === null || (!\is_string($value) && \is_scalar($value))) {
983 $headers[$name] = (string) $value;
984 }
985 }
986
987 return $droppedHeaderNames;
988 }
989
990 /**
991 * @param string|int|float $version
992 */
993 private static function normalizeProtocolVersion($version): string
994 {
995 if ('' === $version) {
996 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing an empty "version" request option is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
997
998 return '1.1';
999 }
1000
1001 return \is_float($version) ? \number_format($version, 1, '.', '') : (string) $version;
1002 }
1003
1004 private static function isProtocolVersionValid(string $version): bool
1005 {
1006 return 1 === \preg_match('/^\d+(?:\.\d+)?$/D', $version);
1007 }
1008
1009 /**
1010 * Return an InvalidArgumentException with pre-set message.
1011 */
1012 private function invalidBody(): InvalidArgumentException
1013 {
1014 return new InvalidArgumentException('Passing in the "body" request '
1015 .'option as an array to send a request is not supported. '
1016 .'Please use the "form_params" request option to send a '
1017 .'application/x-www-form-urlencoded request, or the "multipart" '
1018 .'request option to send a multipart/form-data request.');
1019 }
1020 }