vendor/guzzlehttp/guzzle/src/Utils.php
942 lines · 31209 bytes
1<?php
2
3namespace GuzzleHttp;
4
5use GuzzleHttp\Exception\InvalidArgumentException;
6use GuzzleHttp\Handler\CurlHandler;
7use GuzzleHttp\Handler\CurlMultiHandler;
8use GuzzleHttp\Handler\CurlShareHandleState;
9use GuzzleHttp\Handler\CurlVersion;
10use GuzzleHttp\Handler\Proxy;
11use GuzzleHttp\Handler\StreamHandler;
12use Psr\Http\Message\RequestInterface;
13use Psr\Http\Message\UriInterface;
14
15final class Utils
16{
17 /**
18 * Debug function used to describe the provided value type and class.
19 *
20 * @param mixed $input
21 *
22 * @return string Returns a string containing the type of the variable and
23 * if a class is provided, the class name.
24 *
25 * @deprecated Utils::describeType() will be removed in guzzlehttp/guzzle:8.0. Use get_debug_type() instead.
26 */
27 public static function describeType($input): string
28 {
29 \trigger_deprecation(
30 'guzzlehttp/guzzle',
31 '7.12',
32 '%s() is deprecated and will be removed in 8.0. Use get_debug_type() instead.',
33 __METHOD__
34 );
35
36 switch (\gettype($input)) {
37 case 'object':
38 return 'object('.\get_class($input).')';
39 case 'array':
40 return 'array('.\count($input).')';
41 default:
42 \ob_start();
43 \var_dump($input);
44 // normalize float vs double
45 /** @var string $varDumpContent */
46 $varDumpContent = \ob_get_clean();
47
48 return \str_replace('double(', 'float(', \rtrim($varDumpContent, " \n\r\t\0\x0B"));
49 }
50 }
51
52 /**
53 * Parses an array of header lines into an associative array of headers.
54 *
55 * @param iterable $lines Header lines array of strings in the following
56 * format: "Name: Value"
57 */
58 public static function headersFromLines(iterable $lines): array
59 {
60 $headers = [];
61
62 foreach ($lines as $line) {
63 $parts = \explode(':', $line, 2);
64 $headers[\trim($parts[0], " \n\r\t\0\x0B")][] = isset($parts[1]) ? \trim($parts[1], " \n\r\t\0\x0B") : null;
65 }
66
67 return $headers;
68 }
69
70 /**
71 * Returns a debug stream based on the provided variable.
72 *
73 * @param mixed $value Optional value
74 *
75 * @return resource
76 */
77 public static function debugResource($value = null)
78 {
79 if (\is_resource($value)) {
80 return $value;
81 }
82 if (\defined('STDOUT')) {
83 return \STDOUT;
84 }
85
86 return Psr7\Utils::tryFopen('php://output', 'w');
87 }
88
89 /**
90 * Chooses and creates a default handler to use based on the environment.
91 *
92 * The returned handler is not wrapped by any default middlewares.
93 *
94 * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options.
95 *
96 * @return callable(RequestInterface, array): Promise\PromiseInterface Returns the best handler for the given system.
97 *
98 * @throws \RuntimeException if no viable Handler is available.
99 */
100 public static function chooseHandler(array $handlerOptions = []): callable
101 {
102 $sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing');
103 $sharingRequired = self::isTransportSharingRequired($sharingMode);
104 $connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions);
105 $handler = self::createCurlHandler($sharingMode, $handlerOptions);
106
107 if ($sharingRequired && $handler === null) {
108 throw new \RuntimeException('Required transport sharing requires the PHP cURL extension, curl_exec() or curl_multi_exec(), and libcurl 7.21.2 or higher.');
109 }
110
111 if (\ini_get('allow_url_fopen')) {
112 return self::addStreamHandler($handler, $sharingMode, $sharingRequired, self::connectionCapOptions($handlerOptions));
113 }
114
115 if ($handler !== null) {
116 return $handler;
117 }
118
119 if ($connectionCapsRequired) {
120 throw new \RuntimeException('Connection cap options require a cap-capable cURL multi handler or the allow_url_fopen ini setting for stream fallback.');
121 }
122
123 throw new \RuntimeException('GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler.');
124 }
125
126 private static function isTransportSharingRequired(string $sharingMode): bool
127 {
128 return $sharingMode === TransportSharing::HANDLER_REQUIRE;
129 }
130
131 /**
132 * @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
133 */
134 private static function hasConnectionCapOptions(array $handlerOptions): bool
135 {
136 return self::connectionCapOptions($handlerOptions) !== [];
137 }
138
139 /**
140 * @param array{max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions
141 *
142 * @return (callable(RequestInterface, array): Promise\PromiseInterface)|null
143 */
144 private static function createCurlHandler(string $sharingMode, array $handlerOptions): ?callable
145 {
146 if (!\defined('CURLOPT_CUSTOMREQUEST') || !CurlVersion::supportsCurlHandler()) {
147 return null;
148 }
149
150 $connectionCapOptions = self::connectionCapOptions($handlerOptions);
151 if ($connectionCapOptions !== [] && (!CurlVersion::supportsConnectionCaps() || !\function_exists('curl_multi_exec'))) {
152 return null;
153 }
154
155 $curlHandlerOptions = self::createCurlHandlerOptions($sharingMode);
156 $curlMultiHandlerOptions = $curlHandlerOptions + $connectionCapOptions;
157 if (($handlerOptions['multiplex'] ?? null) === Multiplexing::NONE) {
158 // Forwarded to the CurlMultiHandler only: CurlHandler and
159 // StreamHandler validate known options, and both satisfy NONE
160 // per-request without a handler option.
161 $curlMultiHandlerOptions['multiplex'] = Multiplexing::NONE;
162 }
163
164 if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
165 $multiHandler = new CurlMultiHandler($curlMultiHandlerOptions);
166
167 if ($connectionCapOptions !== []) {
168 // Connection caps only govern transfers on the multi handle, so
169 // the synchronous CurlHandler fast path would escape them.
170 return $multiHandler;
171 }
172
173 return Proxy::wrapSync($multiHandler, new CurlHandler($curlHandlerOptions));
174 }
175
176 if ($connectionCapOptions === [] && \function_exists('curl_exec')) {
177 return new CurlHandler($curlHandlerOptions);
178 }
179
180 if (\function_exists('curl_multi_exec')) {
181 return new CurlMultiHandler($curlMultiHandlerOptions);
182 }
183
184 return null;
185 }
186
187 /**
188 * @return array<string, mixed>
189 */
190 private static function createCurlHandlerOptions(string $sharingMode): array
191 {
192 if ($sharingMode === TransportSharing::NONE) {
193 return [];
194 }
195
196 $shareState = CurlShareHandleState::fromOption($sharingMode);
197
198 return $shareState === null ? [] : ['transport_sharing' => $shareState];
199 }
200
201 /**
202 * @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
203 *
204 * @return array{max_host_connections?: int, max_total_connections?: int}
205 */
206 private static function connectionCapOptions(array $handlerOptions): array
207 {
208 $options = [];
209 foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
210 $value = $handlerOptions[$capOption] ?? null;
211 if ($value === null) {
212 continue;
213 }
214
215 if (!\is_int($value) || $value < 1) {
216 throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption));
217 }
218
219 $options[$capOption] = $value;
220 }
221
222 return $options;
223 }
224
225 /**
226 * @param (callable(RequestInterface, array): Promise\PromiseInterface)|null $handler
227 * @param array{max_host_connections?: int, max_total_connections?: int} $connectionCapOptions
228 *
229 * @return callable(RequestInterface, array): Promise\PromiseInterface
230 */
231 private static function addStreamHandler(?callable $handler, string $sharingMode, bool $sharingRequired, array $connectionCapOptions): callable
232 {
233 $streamHandler = new StreamHandler(['transport_sharing' => $sharingMode] + $connectionCapOptions);
234
235 if ($handler === null) {
236 return $streamHandler;
237 }
238
239 if (!$sharingRequired) {
240 $handler = Proxy::wrapTlsFallback($handler, $streamHandler);
241 }
242
243 return Proxy::wrapStreaming($handler, $streamHandler);
244 }
245
246 /**
247 * Get the default User-Agent string to use with Guzzle.
248 */
249 public static function defaultUserAgent(): string
250 {
251 return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION);
252 }
253
254 /**
255 * Returns the default cacert bundle for the current system.
256 *
257 * First, the openssl.cafile and curl.cainfo php.ini settings are checked.
258 * If those settings are not configured, then the common locations for
259 * bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
260 * and Windows are checked. If any of these file locations are found on
261 * disk, they will be utilized.
262 *
263 * Note: the result of this function is cached for subsequent calls.
264 *
265 * @throws \RuntimeException if no bundle can be found.
266 *
267 * @deprecated Utils::defaultCaBundle will be removed in guzzlehttp/guzzle:8.0. This method is not needed in PHP 5.6+.
268 */
269 public static function defaultCaBundle(): string
270 {
271 \trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s() is deprecated and will be removed in 8.0. This method is not needed in PHP 5.6+.', __METHOD__);
272
273 static $cached = null;
274 static $cafiles = [
275 // Red Hat, CentOS, Fedora (provided by the ca-certificates package)
276 '/etc/pki/tls/certs/ca-bundle.crt',
277 // Ubuntu, Debian (provided by the ca-certificates package)
278 '/etc/ssl/certs/ca-certificates.crt',
279 // FreeBSD (provided by the ca_root_nss package)
280 '/usr/local/share/certs/ca-root-nss.crt',
281 // SLES 12 (provided by the ca-certificates package)
282 '/var/lib/ca-certificates/ca-bundle.pem',
283 // OS X provided by homebrew (using the default path)
284 '/usr/local/etc/openssl/cert.pem',
285 // Google app engine
286 '/etc/ca-certificates.crt',
287 // Windows?
288 'C:\\windows\\system32\\curl-ca-bundle.crt',
289 'C:\\windows\\curl-ca-bundle.crt',
290 ];
291
292 if ($cached) {
293 return $cached;
294 }
295
296 if ($ca = \ini_get('openssl.cafile')) {
297 return $cached = $ca;
298 }
299
300 if ($ca = \ini_get('curl.cainfo')) {
301 return $cached = $ca;
302 }
303
304 foreach ($cafiles as $filename) {
305 if (\file_exists($filename)) {
306 return $cached = $filename;
307 }
308 }
309
310 throw new \RuntimeException(
311 <<< EOT
312No system CA bundle could be found in any of the the common system locations.
313PHP versions earlier than 5.6 are not properly configured to use the system's
314CA bundle by default. In order to verify peer certificates, you will need to
315supply the path on disk to a certificate bundle to the 'verify' request option:
316https://github.com/guzzle/guzzle/blob/7.16/docs/request-options.md#verify. If
317you do not need a specific certificate bundle, then Mozilla provides a commonly
318used CA bundle which can be downloaded here (provided by the maintainer of
319cURL): https://curl.se/ca/cacert.pem. Once you have a CA bundle available on
320disk, you can set the 'openssl.cafile' PHP ini setting to point to the path to
321the file, allowing you to omit the 'verify' request option. See
322https://curl.se/docs/sslcerts.html for more information.
323EOT
324 );
325 }
326
327 /**
328 * Creates an associative array of lowercase header names to the actual
329 * header casing.
330 */
331 public static function normalizeHeaderKeys(array $headers): array
332 {
333 $result = [];
334 foreach (\array_keys($headers) as $key) {
335 $result[Psr7\Utils::asciiToLower((string) $key)] = $key;
336 }
337
338 return $result;
339 }
340
341 /**
342 * @param mixed $protocols
343 *
344 * @return string[]
345 *
346 * @throws InvalidArgumentException
347 */
348 public static function normalizeProtocols($protocols): array
349 {
350 if (!\is_array($protocols) || $protocols === []) {
351 throw new InvalidArgumentException('protocols must be a non-empty array of "http" and/or "https"');
352 }
353
354 $normalized = [];
355
356 foreach ($protocols as $protocol) {
357 if (!\is_string($protocol)) {
358 throw new InvalidArgumentException('protocols must contain only strings');
359 }
360
361 if ($protocol !== 'http' && $protocol !== 'https') {
362 throw new InvalidArgumentException('protocols may only contain "http" and "https"');
363 }
364
365 $normalized[$protocol] = true;
366 }
367
368 return \array_keys($normalized);
369 }
370
371 /**
372 * Returns true if the provided host matches any of the no proxy areas.
373 *
374 * This method will strip a port from the host if it is present. Domain
375 * patterns are matched case-insensitively. Exact IP literal patterns are
376 * matched by their normalized binary address.
377 *
378 * Areas are matched in the following cases:
379 * 1. "*" (without quotes) always matches any hosts.
380 * 2. An exact domain or IP literal match.
381 * 3. A bare domain matches itself and its subdomains. e.g. 'mit.edu' will
382 * match 'mit.edu' and 'foo.mit.edu'.
383 * 4. The area starts with "." and the area is the last part of the host. e.g.
384 * '.mit.edu' will match any host that ends with '.mit.edu'.
385 * 5. IP CIDR entries match IP literal hosts. e.g. '192.168.0.0/16' will
386 * match '192.168.1.10' and 'fd00::/8' will match '[fd00::1]'.
387 *
388 * @param string $host Host to check against the patterns.
389 * @param string[] $noProxyArray An array of host or CIDR patterns.
390 *
391 * @throws InvalidArgumentException
392 */
393 public static function isHostInNoProxy(string $host, array $noProxyArray): bool
394 {
395 if (\strlen($host) === 0) {
396 throw new InvalidArgumentException('Empty host provided');
397 }
398
399 $target = self::parseNoProxyHostString($host);
400 if ($target === null) {
401 return false;
402 }
403
404 return self::matchesNoProxyList($target, $noProxyArray);
405 }
406
407 /**
408 * Returns true if the provided URI matches any of the no proxy areas.
409 *
410 * Matching follows the same rules as isHostInNoProxy(), with the
411 * addition that areas may carry a port (e.g. "example.com:8080" or
412 * "[::1]:8080") which is compared against the URI port (or the scheme
413 * default port when the URI has none).
414 *
415 * @param mixed $noProxy No-proxy host, host-and-port, or CIDR patterns.
416 *
417 * @internal
418 */
419 public static function isUriInNoProxy(UriInterface $uri, $noProxy): bool
420 {
421 if (\is_string($noProxy)) {
422 $noProxy = \explode(',', $noProxy);
423 }
424
425 if (!\is_array($noProxy)) {
426 return false;
427 }
428
429 $target = self::parseNoProxyTarget($uri);
430 if ($target === null) {
431 return false;
432 }
433
434 return self::matchesNoProxyList($target, $noProxy);
435 }
436
437 /**
438 * @param array{type: string, value: string, port: int|null, matchesRoot: bool} $target
439 * @param array<array-key, mixed> $noProxy
440 */
441 private static function matchesNoProxyList(array $target, array $noProxy): bool
442 {
443 foreach ($noProxy as $area) {
444 if (!\is_string($area)) {
445 continue;
446 }
447
448 $area = \trim($area, " \n\r\t\0\x0B");
449
450 // Always match on wildcards.
451 if ($area === '*') {
452 return true;
453 }
454
455 $rule = self::parseNoProxyRule($area);
456 if ($rule !== null && self::noProxyRuleMatches($target, $rule)) {
457 return true;
458 }
459 }
460
461 return false;
462 }
463
464 /**
465 * @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
466 */
467 private static function parseNoProxyTarget(UriInterface $uri): ?array
468 {
469 $host = $uri->getHost();
470 if ($host === '') {
471 return null;
472 }
473
474 return self::parseNoProxyHost($host, $uri->getPort() ?? self::getDefaultPort($uri->getScheme()), true);
475 }
476
477 /**
478 * @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
479 */
480 private static function parseNoProxyHostString(string $host): ?array
481 {
482 $hostAndPort = self::splitNoProxyHostAndPort($host);
483 if ($hostAndPort === null) {
484 return null;
485 }
486
487 [$host] = $hostAndPort;
488
489 return self::parseNoProxyHost($host, null, true);
490 }
491
492 /**
493 * @return array{type: string, value: string, port: int|null, matchesRoot: bool}|array{type: string, value: string, prefix: int}|null
494 */
495 private static function parseNoProxyRule(string $area): ?array
496 {
497 $area = \trim($area, " \n\r\t\0\x0B");
498 if ($area === '' || $area === '*') {
499 return null;
500 }
501
502 if (\strpos($area, '/') !== false) {
503 return self::parseNoProxyCidrRule($area);
504 }
505
506 $matchesRoot = true;
507 if ($area[0] === '.') {
508 $matchesRoot = false;
509 $area = \substr($area, 1);
510 }
511
512 $hostAndPort = self::splitNoProxyHostAndPort($area);
513 if ($hostAndPort === null) {
514 return null;
515 }
516
517 [$host, $port] = $hostAndPort;
518
519 if ($host === '*') {
520 if (!$matchesRoot) {
521 return null;
522 }
523
524 return [
525 'type' => 'wildcard',
526 'value' => '*',
527 'port' => $port,
528 'matchesRoot' => true,
529 ];
530 }
531
532 $rule = self::parseNoProxyHost($host, $port, $matchesRoot);
533 if ($rule !== null && !$matchesRoot && $rule['type'] === 'ip') {
534 return null;
535 }
536
537 return $rule;
538 }
539
540 /**
541 * @return array{type: string, value: string, port: int|null, matchesRoot: bool}|null
542 */
543 private static function parseNoProxyHost(string $host, ?int $port, bool $matchesRoot): ?array
544 {
545 if ($host !== '' && $host[0] === '[') {
546 if (\substr($host, -1) !== ']') {
547 return null;
548 }
549
550 $address = \substr($host, 1, -1);
551 if (!\filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
552 return null;
553 }
554
555 $host = $address;
556 }
557
558 $packedIp = self::packIpAddress($host);
559 if ($packedIp !== false) {
560 return [
561 'type' => 'ip',
562 'value' => $packedIp,
563 'port' => $port,
564 'matchesRoot' => $matchesRoot,
565 ];
566 }
567
568 if ($host === '' || \strpos($host, ':') !== false) {
569 return null;
570 }
571
572 // Normalize a single DNS root dot for no-proxy domain matching.
573 if (\substr($host, -1) === '.') {
574 $host = \substr($host, 0, -1);
575 if ($host === '') {
576 return null;
577 }
578 }
579
580 return [
581 'type' => 'domain',
582 'value' => Psr7\Utils::asciiToLower($host),
583 'port' => $port,
584 'matchesRoot' => $matchesRoot,
585 ];
586 }
587
588 /**
589 * @return array{0: string, 1: int|null}|null
590 */
591 private static function splitNoProxyHostAndPort(string $area): ?array
592 {
593 if ($area !== '' && $area[0] === '[') {
594 $closingBracket = \strpos($area, ']');
595 if ($closingBracket === false) {
596 return null;
597 }
598
599 $host = \substr($area, 0, $closingBracket + 1);
600 $tail = \substr($area, $closingBracket + 1);
601 if ($tail === '') {
602 return [$host, null];
603 }
604
605 if ($tail[0] !== ':') {
606 return null;
607 }
608
609 $port = self::parseNoProxyPort(\substr($tail, 1));
610
611 return $port === null ? null : [$host, $port];
612 }
613
614 if (self::packIpAddress($area) !== false) {
615 return [$area, null];
616 }
617
618 $colon = \strrpos($area, ':');
619 if ($colon === false) {
620 return [$area, null];
621 }
622
623 $port = self::parseNoProxyPort(\substr($area, $colon + 1));
624 if ($port === null) {
625 return null;
626 }
627
628 return [\substr($area, 0, $colon), $port];
629 }
630
631 private static function parseNoProxyPort(string $port): ?int
632 {
633 return self::parseBoundedUnsignedInteger($port, 65535);
634 }
635
636 /**
637 * @return array{type: string, value: string, prefix: int}|null
638 */
639 private static function parseNoProxyCidrRule(string $area): ?array
640 {
641 $slash = \strpos($area, '/');
642 if ($slash === false) {
643 return null;
644 }
645
646 $prefix = \substr($area, $slash + 1);
647
648 $network = \substr($area, 0, $slash);
649 if ($network !== '' && $network[0] === '[' && \substr($network, -1) === ']') {
650 $network = \substr($network, 1, -1);
651 }
652
653 $network = self::packIpAddress($network);
654 if ($network === false) {
655 return null;
656 }
657
658 $prefix = self::parseBoundedUnsignedInteger($prefix, \strlen($network) * 8);
659 if ($prefix === null) {
660 return null;
661 }
662
663 return [
664 'type' => 'cidr',
665 'value' => $network,
666 'prefix' => $prefix,
667 ];
668 }
669
670 private static function parseBoundedUnsignedInteger(string $value, int $max): ?int
671 {
672 if ($value === '' || !\ctype_digit($value)) {
673 return null;
674 }
675
676 $normalized = \ltrim($value, '0');
677 $normalized = $normalized === '' ? '0' : $normalized;
678 $limit = (string) $max;
679
680 if (\strlen($normalized) > \strlen($limit) || (\strlen($normalized) === \strlen($limit) && \strcmp($normalized, $limit) > 0)) {
681 return null;
682 }
683
684 return (int) $normalized;
685 }
686
687 /**
688 * @param array{type: string, value: string, port: int|null, matchesRoot: bool} $target
689 * @param array{type: string, value: string, port?: int|null, matchesRoot?: bool, prefix?: int|null} $rule
690 */
691 private static function noProxyRuleMatches(array $target, array $rule): bool
692 {
693 if ($rule['type'] === 'wildcard') {
694 return ($rule['port'] ?? null) === null || $rule['port'] === $target['port'];
695 }
696
697 if ($rule['type'] === 'cidr') {
698 if ($target['type'] !== 'ip' || !isset($rule['prefix'])) {
699 return false;
700 }
701
702 if (\strlen($target['value']) !== \strlen($rule['value'])) {
703 return false;
704 }
705
706 return self::ipMatchesPrefix($target['value'], $rule['value'], $rule['prefix']);
707 }
708
709 if (($rule['port'] ?? null) !== null && $rule['port'] !== $target['port']) {
710 return false;
711 }
712
713 if ($rule['type'] !== $target['type']) {
714 return false;
715 }
716
717 if ($rule['type'] === 'ip') {
718 return $rule['value'] === $target['value'];
719 }
720
721 if (($rule['matchesRoot'] ?? false) && $target['value'] === $rule['value']) {
722 return true;
723 }
724
725 $suffix = '.'.$rule['value'];
726
727 return \substr($target['value'], -\strlen($suffix)) === $suffix;
728 }
729
730 /**
731 * @return string|false
732 */
733 private static function packIpAddress(string $ip)
734 {
735 if (!\filter_var($ip, \FILTER_VALIDATE_IP)) {
736 return false;
737 }
738
739 return \inet_pton($ip);
740 }
741
742 private static function ipMatchesPrefix(string $address, string $network, int $prefix): bool
743 {
744 $fullBytes = \intdiv($prefix, 8);
745 $remainingBits = $prefix % 8;
746
747 if ($fullBytes > 0 && \substr($address, 0, $fullBytes) !== \substr($network, 0, $fullBytes)) {
748 return false;
749 }
750
751 if ($remainingBits === 0) {
752 return true;
753 }
754
755 $mask = (0xFF << (8 - $remainingBits)) & 0xFF;
756
757 return (\ord($address[$fullBytes]) & $mask) === (\ord($network[$fullBytes]) & $mask);
758 }
759
760 private static function getDefaultPort(string $scheme): ?int
761 {
762 if ($scheme === 'http') {
763 return 80;
764 }
765
766 if ($scheme === 'https') {
767 return 443;
768 }
769
770 return null;
771 }
772
773 /**
774 * Wrapper for json_decode that throws when an error occurs.
775 *
776 * @param string $json JSON data to parse
777 * @param bool $assoc When true, returned objects will be converted
778 * into associative arrays.
779 * @param int $depth User specified recursion depth.
780 * @param int $options Bitmask of JSON decode options.
781 *
782 * @return object|array|string|int|float|bool|null
783 *
784 * @throws InvalidArgumentException if the JSON cannot be decoded.
785 *
786 * @see https://www.php.net/manual/en/function.json-decode.php
787 * @deprecated Utils::jsonDecode() will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_decode() instead.
788 */
789 public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
790 {
791 \trigger_deprecation('guzzlehttp/guzzle', '7.15', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_decode() instead.', __METHOD__);
792
793 if ($depth < 1) {
794 throw new InvalidArgumentException('json_decode error: Maximum stack depth exceeded');
795 }
796
797 $data = \json_decode($json, $assoc, $depth, $options);
798 if (\JSON_ERROR_NONE !== \json_last_error()) {
799 throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
800 }
801
802 return $data;
803 }
804
805 /**
806 * Wrapper for JSON encoding that throws when an error occurs.
807 *
808 * @param mixed $value The value being encoded
809 * @param int $options JSON encode option bitmask
810 * @param int $depth Set the maximum depth. Must be greater than zero.
811 *
812 * @throws InvalidArgumentException if the JSON cannot be encoded.
813 *
814 * @see https://www.php.net/manual/en/function.json-encode.php
815 * @deprecated Utils::jsonEncode() will be removed in guzzlehttp/guzzle:8.0. Use PHP's json_encode() instead.
816 */
817 public static function jsonEncode($value, int $options = 0, int $depth = 512): string
818 {
819 \trigger_deprecation('guzzlehttp/guzzle', '7.15', '%s() is deprecated and will be removed in 8.0. Use PHP\'s json_encode() instead.', __METHOD__);
820
821 $json = \json_encode($value, $options, $depth);
822 if (\JSON_ERROR_NONE !== \json_last_error()) {
823 throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
824 }
825
826 /** @var string */
827 return $json;
828 }
829
830 /**
831 * Wrapper for the hrtime() or microtime() functions
832 * (depending on the PHP version, one of the two is used)
833 *
834 * @return float UNIX timestamp
835 *
836 * @internal
837 */
838 public static function currentTime(): float
839 {
840 return (float) \function_exists('hrtime') ? \hrtime(true) / 1e9 : \microtime(true);
841 }
842
843 /**
844 * @param mixed $value
845 *
846 * @internal
847 */
848 public static function normalizeIdnConversionOption($value): ?int
849 {
850 if ($value === null || $value === false) {
851 return null;
852 }
853
854 if ($value === true) {
855 return \IDNA_DEFAULT;
856 }
857
858 if (\is_int($value)) {
859 return $value;
860 }
861
862 if ((\is_string($value) && \is_numeric($value)) || (\is_float($value) && \is_finite($value))) {
863 \trigger_deprecation(
864 'guzzlehttp/guzzle',
865 '7.11',
866 'Passing %s as the "idn_conversion" request option is deprecated; guzzlehttp/guzzle 8.0 will reject values that are not true, false, null, or an integer IDNA_* bitmask.',
867 \get_debug_type($value)
868 );
869
870 return (int) $value;
871 }
872
873 throw new InvalidArgumentException('idn_conversion must be true, false, null, or an integer IDNA_* bitmask');
874 }
875
876 /**
877 * @throws InvalidArgumentException
878 *
879 * @internal
880 */
881 public static function idnUriConvert(UriInterface $uri, int $options = 0): UriInterface
882 {
883 if ($uri->getHost()) {
884 $asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
885 if ($asciiHost === false) {
886 $errorBitSet = $info['errors'] ?? 0;
887
888 $errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool {
889 return substr($name, 0, 11) === 'IDNA_ERROR_';
890 });
891
892 $errors = [];
893 foreach ($errorConstants as $errorConstant) {
894 if ($errorBitSet & constant($errorConstant)) {
895 $errors[] = $errorConstant;
896 }
897 }
898
899 $errorMessage = 'IDN conversion failed';
900 if ($errors) {
901 $errorMessage .= ' (errors: '.implode(', ', $errors).')';
902 }
903
904 throw new InvalidArgumentException($errorMessage);
905 }
906 if ($uri->getHost() !== $asciiHost) {
907 // Replace URI only if the ASCII version is different
908 $uri = $uri->withHost($asciiHost);
909 }
910 }
911
912 return $uri;
913 }
914
915 /**
916 * @internal
917 */
918 public static function getenv(string $name): ?string
919 {
920 if (isset($_SERVER[$name])) {
921 return (string) $_SERVER[$name];
922 }
923
924 if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
925 return (string) $value;
926 }
927
928 return null;
929 }
930
931 /**
932 * @return string|false
933 */
934 private static function idnToAsci(string $domain, int $options, ?array &$info = [])
935 {
936 if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) {
937 return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info);
938 }
939
940 throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old');
941 }
942}