Debian Codegraph @

vendor/guzzlehttp/guzzle/src/Utils.php

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