Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/HttpClientTrait.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient;
13
14 use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
15 use Symfony\Component\HttpClient\Exception\TransportException;
16 use Symfony\Component\HttpClient\Response\StreamableInterface;
17 use Symfony\Component\HttpClient\Response\StreamWrapper;
18 use Symfony\Component\Mime\MimeTypes;
19
20 /**
21 * Provides the common logic from writing HttpClientInterface implementations.
22 *
23 * All private methods are static to prevent implementers from creating memory leaks via circular references.
24 *
25 * @author Nicolas Grekas <[email protected]>
26 */
27 trait HttpClientTrait
28 {
29 private static int $CHUNK_SIZE = 16372;
30
31 public function withOptions(array $options): static
32 {
33 $clone = clone $this;
34 $clone->defaultOptions = self::mergeDefaultOptions($options, $this->defaultOptions);
35
36 return $clone;
37 }
38
39 /**
40 * Validates and normalizes method, URL and options, and merges them with defaults.
41 *
42 * @throws InvalidArgumentException When a not-supported option is found
43 */
44 private static function prepareRequest(?string $method, ?string $url, array $options, array $defaultOptions = [], bool $allowExtraOptions = false): array
45 {
46 if (null !== $method) {
47 if (\strlen($method) !== strspn($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')) {
48 throw new InvalidArgumentException(\sprintf('Invalid HTTP method "%s", only uppercase letters are accepted.', $method));
49 }
50 if (!$method) {
51 throw new InvalidArgumentException('The HTTP method cannot be empty.');
52 }
53 }
54
55 $options = self::mergeDefaultOptions($options, $defaultOptions, $allowExtraOptions);
56
57 $buffer = $options['buffer'] ?? true;
58
59 if ($buffer instanceof \Closure) {
60 $options['buffer'] = static function (array $headers) use ($buffer) {
61 if (!\is_bool($buffer = $buffer($headers))) {
62 if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
63 throw new \LogicException(\sprintf('The closure passed as option "buffer" must return bool or stream resource, got "%s".', get_debug_type($buffer)));
64 }
65
66 if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
67 throw new \LogicException(\sprintf('The stream returned by the closure passed as option "buffer" must be writeable, got mode "%s".', $bufferInfo['mode']));
68 }
69 }
70
71 return $buffer;
72 };
73 } elseif (!\is_bool($buffer)) {
74 if (!\is_array($bufferInfo = @stream_get_meta_data($buffer))) {
75 throw new InvalidArgumentException(\sprintf('Option "buffer" must be bool, stream resource or Closure, "%s" given.', get_debug_type($buffer)));
76 }
77
78 if (false === strpbrk($bufferInfo['mode'], 'acew+')) {
79 throw new InvalidArgumentException(\sprintf('The stream in option "buffer" must be writeable, mode "%s" given.', $bufferInfo['mode']));
80 }
81 }
82
83 if (isset($options['json'])) {
84 if (isset($options['body']) && '' !== $options['body']) {
85 throw new InvalidArgumentException('Define either the "json" or the "body" option, setting both is not supported.');
86 }
87 $options['body'] = self::jsonEncode($options['json']);
88 unset($options['json']);
89
90 if (!isset($options['normalized_headers']['content-type'])) {
91 $options['normalized_headers']['content-type'] = ['Content-Type: application/json'];
92 }
93 }
94
95 if (!isset($options['normalized_headers']['accept'])) {
96 $options['normalized_headers']['accept'] = ['Accept: */*'];
97 }
98
99 if (isset($options['body'])) {
100 $options['body'] = self::normalizeBody($options['body'], $options['normalized_headers']);
101
102 if (\is_string($options['body'])
103 && (string) \strlen($options['body']) !== substr($h = $options['normalized_headers']['content-length'][0] ?? '', 16)
104 && ('' !== $h || '' !== $options['body'])
105 ) {
106 if ('chunked' === substr($options['normalized_headers']['transfer-encoding'][0] ?? '', \strlen('Transfer-Encoding: '))) {
107 unset($options['normalized_headers']['transfer-encoding']);
108 $options['body'] = self::dechunk($options['body']);
109 }
110
111 $options['normalized_headers']['content-length'] = [substr_replace($h ?: 'Content-Length: ', \strlen($options['body']), 16)];
112 }
113 }
114
115 if (isset($options['peer_fingerprint'])) {
116 $options['peer_fingerprint'] = self::normalizePeerFingerprint($options['peer_fingerprint']);
117 }
118
119 if (isset($options['crypto_method']) && !\in_array($options['crypto_method'], [
120 \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT,
121 \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT,
122 \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
123 \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT,
124 ], true)) {
125 throw new InvalidArgumentException('Option "crypto_method" must be one of "STREAM_CRYPTO_METHOD_TLSv1_*_CLIENT".');
126 }
127
128 // Validate on_progress
129 if (isset($options['on_progress']) && !\is_callable($onProgress = $options['on_progress'])) {
130 throw new InvalidArgumentException(\sprintf('Option "on_progress" must be callable, "%s" given.', get_debug_type($onProgress)));
131 }
132
133 if (\is_array($options['auth_basic'] ?? null)) {
134 $count = \count($options['auth_basic']);
135 if ($count <= 0 || $count > 2) {
136 throw new InvalidArgumentException(\sprintf('Option "auth_basic" must contain 1 or 2 elements, "%s" given.', $count));
137 }
138
139 $options['auth_basic'] = implode(':', $options['auth_basic']);
140 }
141
142 if (!\is_string($options['auth_basic'] ?? '')) {
143 throw new InvalidArgumentException(\sprintf('Option "auth_basic" must be string or an array, "%s" given.', get_debug_type($options['auth_basic'])));
144 }
145
146 if (isset($options['auth_bearer'])) {
147 if (!\is_string($options['auth_bearer'])) {
148 throw new InvalidArgumentException(\sprintf('Option "auth_bearer" must be a string, "%s" given.', get_debug_type($options['auth_bearer'])));
149 }
150 if (preg_match('{[^\x21-\x7E]}', $options['auth_bearer'])) {
151 throw new InvalidArgumentException('Invalid character found in option "auth_bearer": '.json_encode($options['auth_bearer']).'.');
152 }
153 }
154
155 if (isset($options['auth_basic'], $options['auth_bearer'])) {
156 throw new InvalidArgumentException('Define either the "auth_basic" or the "auth_bearer" option, setting both is not supported.');
157 }
158
159 if (null !== $url) {
160 // Merge auth with headers
161 if (($options['auth_basic'] ?? false) && !($options['normalized_headers']['authorization'] ?? false)) {
162 $options['normalized_headers']['authorization'] = ['Authorization: Basic '.base64_encode($options['auth_basic'])];
163 }
164 // Merge bearer with headers
165 if (($options['auth_bearer'] ?? false) && !($options['normalized_headers']['authorization'] ?? false)) {
166 $options['normalized_headers']['authorization'] = ['Authorization: Bearer '.$options['auth_bearer']];
167 }
168
169 unset($options['auth_basic'], $options['auth_bearer']);
170
171 // Parse base URI
172 if (\is_string($baseUri = $options['base_uri'] ?? null)) {
173 $baseUri = self::parseUrl($baseUri);
174 }
175 unset($options['base_uri']);
176
177 // Validate and resolve URL
178 $url = self::parseUrl($url, $options['query']);
179 $url = self::resolveUrl($url, $baseUri, $defaultOptions['query'] ?? []);
180 }
181
182 // Finalize normalization of options
183 $options['http_version'] = (string) ($options['http_version'] ?? '') ?: null;
184 if (0 > $options['timeout'] = (float) ($options['timeout'] ?? \ini_get('default_socket_timeout'))) {
185 $options['timeout'] = 172800.0; // 2 days
186 }
187
188 $options['max_duration'] = isset($options['max_duration']) ? (float) $options['max_duration'] : 0;
189 $options['headers'] = array_merge(...array_values($options['normalized_headers']));
190
191 return [$url, $options];
192 }
193
194 /**
195 * @throws InvalidArgumentException When an invalid option is found
196 */
197 private static function mergeDefaultOptions(array $options, array $defaultOptions, bool $allowExtraOptions = false): array
198 {
199 $options['normalized_headers'] = self::normalizeHeaders($options['headers'] ?? []);
200
201 if ($defaultOptions['headers'] ?? false) {
202 $options['normalized_headers'] += self::normalizeHeaders($defaultOptions['headers']);
203 }
204
205 $options['headers'] = array_merge(...array_values($options['normalized_headers']) ?: [[]]);
206
207 if ($resolve = $options['resolve'] ?? false) {
208 $options['resolve'] = [];
209 foreach ($resolve as $k => $v) {
210 if ('' === $v = (string) $v) {
211 $v = null;
212 } elseif ('[' === $v[0] && ']' === substr($v, -1) && str_contains($v, ':')) {
213 $v = substr($v, 1, -1);
214 }
215
216 $options['resolve'][substr(self::parseUrl('http://'.$k)['authority'], 2)] = $v;
217 }
218 }
219
220 // Option "query" is never inherited from defaults
221 $options['query'] ??= [];
222
223 $options += $defaultOptions;
224
225 if (isset(self::$emptyDefaults)) {
226 foreach (self::$emptyDefaults as $k => $v) {
227 if (!isset($options[$k])) {
228 $options[$k] = $v;
229 }
230 }
231 }
232
233 if (isset($defaultOptions['extra'])) {
234 $options['extra'] += $defaultOptions['extra'];
235 }
236
237 if ($resolve = $defaultOptions['resolve'] ?? false) {
238 foreach ($resolve as $k => $v) {
239 if ('' === $v = (string) $v) {
240 $v = null;
241 } elseif ('[' === $v[0] && ']' === substr($v, -1) && str_contains($v, ':')) {
242 $v = substr($v, 1, -1);
243 }
244
245 $options['resolve'] += [substr(self::parseUrl('http://'.$k)['authority'], 2) => $v];
246 }
247 }
248
249 if ($allowExtraOptions || !$defaultOptions) {
250 return $options;
251 }
252
253 // Look for unsupported options
254 foreach ($options as $name => $v) {
255 if (\array_key_exists($name, $defaultOptions) || 'normalized_headers' === $name) {
256 continue;
257 }
258
259 if ('auth_ntlm' === $name) {
260 if (!\extension_loaded('curl')) {
261 $msg = 'try installing the "curl" extension to use "%s" instead.';
262 } else {
263 $msg = 'try using "%s" instead.';
264 }
265
266 throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class));
267 }
268
269 if ('vars' === $name) {
270 throw new InvalidArgumentException(\sprintf('Option "vars" is not supported by "%s", try using "%s" instead.', __CLASS__, UriTemplateHttpClient::class));
271 }
272
273 $alternatives = [];
274
275 foreach ($defaultOptions as $k => $v) {
276 if (levenshtein($name, $k) <= \strlen($name) / 3 || str_contains($k, $name)) {
277 $alternatives[] = $k;
278 }
279 }
280
281 throw new InvalidArgumentException(\sprintf('Unsupported option "%s" passed to "%s", did you mean "%s"?', $name, __CLASS__, implode('", "', $alternatives ?: array_keys($defaultOptions))));
282 }
283
284 return $options;
285 }
286
287 /**
288 * @return string[][]
289 *
290 * @throws InvalidArgumentException When an invalid header is found
291 */
292 private static function normalizeHeaders(array $headers): array
293 {
294 $normalizedHeaders = [];
295
296 foreach ($headers as $name => $values) {
297 if ($values instanceof \Stringable) {
298 $values = (string) $values;
299 }
300
301 if (\is_int($name)) {
302 if (!\is_string($values)) {
303 throw new InvalidArgumentException(\sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
304 }
305 [$name, $values] = explode(':', $values, 2);
306 $values = [ltrim($values)];
307 } elseif (!is_iterable($values)) {
308 if (\is_object($values)) {
309 throw new InvalidArgumentException(\sprintf('Invalid value for header "%s": expected string, "%s" given.', $name, get_debug_type($values)));
310 }
311
312 $values = (array) $values;
313 }
314
315 $lcName = strtolower($name);
316 $normalizedHeaders[$lcName] = [];
317
318 foreach ($values as $value) {
319 $normalizedHeaders[$lcName][] = $value = $name.': '.$value;
320
321 if (\strlen($value) !== strcspn($value, "\r\n\0")) {
322 throw new InvalidArgumentException(\sprintf('Invalid header: CR/LF/NUL found in "%s".', $value));
323 }
324 }
325 }
326
327 return $normalizedHeaders;
328 }
329
330 /**
331 * @param array|string|resource|\Traversable|\Closure $body
332 *
333 * @return string|resource|\Closure
334 *
335 * @throws InvalidArgumentException When an invalid body is passed
336 */
337 private static function normalizeBody($body, array &$normalizedHeaders = [])
338 {
339 if (\is_array($body)) {
340 static $cookie;
341
342 $streams = [];
343 array_walk_recursive($body, $caster = static function (&$v) use (&$caster, &$streams, &$cookie) {
344 if (\is_resource($v) || $v instanceof StreamableInterface) {
345 $cookie = hash('xxh128', $cookie ??= random_bytes(8), true);
346 $k = substr(strtr(base64_encode($cookie), '+/', '-_'), 0, -2);
347 $streams[$k] = $v instanceof StreamableInterface ? $v->toStream(false) : $v;
348 $v = $k;
349 } elseif (\is_object($v)) {
350 if ($vars = get_object_vars($v)) {
351 array_walk_recursive($vars, $caster);
352 $v = $vars;
353 } elseif ($v instanceof \Stringable) {
354 $v = (string) $v;
355 }
356 }
357 });
358 $caster = null;
359
360 if ('' === $body = http_build_query($body, '', '&')) {
361 return '';
362 }
363
364 if (!$streams && !str_contains($normalizedHeaders['content-type'][0] ?? '', 'multipart/form-data')) {
365 if (!str_contains($normalizedHeaders['content-type'][0] ?? '', 'application/x-www-form-urlencoded')) {
366 $normalizedHeaders['content-type'] = ['Content-Type: application/x-www-form-urlencoded'];
367 }
368
369 return $body;
370 }
371
372 if (preg_match('{multipart/form-data; boundary=(?|"([^"\r\n]++)"|([-!#$%&\'*+.^_`|~_A-Za-z0-9]++))}', $normalizedHeaders['content-type'][0] ?? '', $boundary)) {
373 $boundary = $boundary[1];
374 } else {
375 $boundary = substr(strtr(base64_encode($cookie ??= random_bytes(8)), '+/', '-_'), 0, -2);
376 $normalizedHeaders['content-type'] = ['Content-Type: multipart/form-data; boundary='.$boundary];
377 }
378
379 $body = explode('&', $body);
380 $contentLength = 0;
381
382 foreach ($body as $i => $part) {
383 [$k, $v] = explode('=', $part, 2);
384 $part = ($i ? "\r\n" : '')."--{$boundary}\r\n";
385 $k = str_replace(['"', "\r", "\n"], ['%22', '%0D', '%0A'], urldecode($k)); // see WHATWG HTML living standard
386
387 if (!isset($streams[$v])) {
388 $part .= "Content-Disposition: form-data; name=\"{$k}\"\r\n\r\n".urldecode($v);
389 $contentLength += 0 <= $contentLength ? \strlen($part) : 0;
390 $body[$i] = [$k, $part, null];
391 continue;
392 }
393 $v = $streams[$v];
394
395 if (!\is_array($m = @stream_get_meta_data($v))) {
396 throw new TransportException(\sprintf('Invalid "%s" resource found in body part "%s".', get_resource_type($v), $k));
397 }
398 if (feof($v)) {
399 throw new TransportException(\sprintf('Uploaded stream ended for body part "%s".', $k));
400 }
401
402 $m += stream_context_get_options($v)['http'] ?? [];
403 $filename = basename($m['filename'] ?? $m['uri'] ?? 'unknown');
404 $filename = str_replace(['"', "\r", "\n"], ['%22', '%0D', '%0A'], $filename);
405 $contentType = $m['content_type'] ?? null;
406
407 if (($headers = $m['wrapper_data'] ?? []) instanceof StreamWrapper) {
408 $hasContentLength = false;
409 $headers = $headers->getResponse()->getInfo('response_headers');
410 } elseif ($hasContentLength = 0 < $h = fstat($v)['size'] ?? 0) {
411 $contentLength += 0 <= $contentLength ? $h : 0;
412 }
413
414 foreach (\is_array($headers) ? $headers : [] as $h) {
415 if (\is_string($h) && 0 === stripos($h, 'Content-Type: ')) {
416 $contentType ??= substr($h, 14);
417 } elseif (!$hasContentLength && \is_string($h) && 0 === stripos($h, 'Content-Length: ')) {
418 $hasContentLength = true;
419 $contentLength += 0 <= $contentLength ? substr($h, 16) : 0;
420 } elseif (\is_string($h) && 0 === stripos($h, 'Content-Encoding: ')) {
421 $contentLength = -1;
422 }
423 }
424
425 if (!$hasContentLength) {
426 $contentLength = -1;
427 }
428 if (null === $contentType && 'plainfile' === ($m['wrapper_type'] ?? null) && isset($m['uri'])) {
429 $mimeTypes = class_exists(MimeTypes::class) ? MimeTypes::getDefault() : false;
430 $contentType = $mimeTypes ? $mimeTypes->guessMimeType($m['uri']) : null;
431 }
432 $contentType ??= 'application/octet-stream';
433
434 $part .= "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$filename}\"\r\n";
435 $part .= "Content-Type: {$contentType}\r\n\r\n";
436
437 $contentLength += 0 <= $contentLength ? \strlen($part) : 0;
438 $body[$i] = [$k, $part, $v];
439 }
440
441 $body[++$i] = ['', "\r\n--{$boundary}--\r\n", null];
442
443 if (0 < $contentLength) {
444 $normalizedHeaders['content-length'] = ['Content-Length: '.($contentLength += \strlen($body[$i][1]))];
445 }
446
447 $body = static function ($size) use ($body) {
448 foreach ($body as $i => [$k, $part, $h]) {
449 unset($body[$i]);
450
451 yield $part;
452
453 while (null !== $h && !feof($h)) {
454 if (false === $part = fread($h, $size)) {
455 throw new TransportException(\sprintf('Error while reading uploaded stream for body part "%s".', $k));
456 }
457
458 yield $part;
459 }
460 }
461 $h = null;
462 };
463 }
464
465 if (\is_string($body)) {
466 return $body;
467 }
468
469 $generatorToCallable = static fn (\Generator $body): \Closure => static function () use ($body) {
470 while ($body->valid()) {
471 $chunk = $body->current();
472 $body->next();
473
474 if ('' !== $chunk) {
475 return $chunk;
476 }
477 }
478
479 return '';
480 };
481
482 if ($body instanceof \Generator) {
483 return $generatorToCallable($body);
484 }
485
486 if ($body instanceof \Traversable) {
487 return $generatorToCallable((static function ($body) { yield from $body; })($body));
488 }
489
490 if ($body instanceof \Closure) {
491 $r = new \ReflectionFunction($body);
492 $body = $r->getClosure();
493
494 if ($r->isGenerator()) {
495 $body = $body(self::$CHUNK_SIZE);
496
497 return $generatorToCallable($body);
498 }
499
500 return $body;
501 }
502
503 if (!\is_array(@stream_get_meta_data($body))) {
504 throw new InvalidArgumentException(\sprintf('Option "body" must be string, stream resource, iterable or callable, "%s" given.', get_debug_type($body)));
505 }
506
507 return $body;
508 }
509
510 private static function dechunk(string $body): string
511 {
512 $h = fopen('php://temp', 'w+');
513 stream_filter_append($h, 'dechunk', \STREAM_FILTER_WRITE);
514 fwrite($h, $body);
515 $body = stream_get_contents($h, -1, 0);
516 rewind($h);
517 ftruncate($h, 0);
518
519 if (fwrite($h, '-') && '' !== stream_get_contents($h, -1, 0)) {
520 throw new TransportException('Request body has broken chunked encoding.');
521 }
522
523 return $body;
524 }
525
526 /**
527 * @throws InvalidArgumentException When an invalid fingerprint is passed
528 */
529 private static function normalizePeerFingerprint(mixed $fingerprint): array
530 {
531 if (\is_string($fingerprint)) {
532 $fingerprint = match (\strlen($fingerprint = str_replace(':', '', $fingerprint))) {
533 32 => ['md5' => $fingerprint],
534 40 => ['sha1' => $fingerprint],
535 44 => ['pin-sha256' => [$fingerprint]],
536 64 => ['sha256' => $fingerprint],
537 default => throw new InvalidArgumentException(\sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint)),
538 };
539 } elseif (\is_array($fingerprint)) {
540 foreach ($fingerprint as $algo => $hash) {
541 $fingerprint[$algo] = 'pin-sha256' === $algo ? (array) $hash : str_replace(':', '', $hash);
542 }
543 } else {
544 throw new InvalidArgumentException(\sprintf('Option "peer_fingerprint" must be string or array, "%s" given.', get_debug_type($fingerprint)));
545 }
546
547 return $fingerprint;
548 }
549
550 /**
551 * @throws InvalidArgumentException When the value cannot be json-encoded
552 */
553 private static function jsonEncode(mixed $value, ?int $flags = null, int $maxDepth = 512): string
554 {
555 $flags ??= \JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT | \JSON_PRESERVE_ZERO_FRACTION;
556
557 try {
558 $value = json_encode($value, $flags | \JSON_THROW_ON_ERROR, $maxDepth);
559 } catch (\JsonException $e) {
560 throw new InvalidArgumentException('Invalid value for "json" option: '.$e->getMessage());
561 }
562
563 return $value;
564 }
565
566 /**
567 * Resolves a URL against a base URI.
568 *
569 * @see https://tools.ietf.org/html/rfc3986#section-5.2.2
570 *
571 * @throws InvalidArgumentException When an invalid URL is passed
572 */
573 private static function resolveUrl(array $url, ?array $base, array $queryDefaults = []): array
574 {
575 $givenUrl = $url;
576
577 if (null !== $base && '' === ($base['scheme'] ?? '').($base['authority'] ?? '')) {
578 throw new InvalidArgumentException(\sprintf('Invalid "base_uri" option: host or scheme is missing in "%s".', implode('', $base)));
579 }
580
581 if (null === $url['scheme'] && (null === $base || null === $base['scheme'])) {
582 throw new InvalidArgumentException(\sprintf('Invalid URL: scheme is missing in "%s". Did you forget to add "http(s)://"?', implode('', $base ?? $url)));
583 }
584
585 if (null === $base && '' === $url['scheme'].$url['authority']) {
586 throw new InvalidArgumentException(\sprintf('Invalid URL: no "base_uri" option was provided and host or scheme is missing in "%s".', implode('', $url)));
587 }
588
589 if (null !== $url['scheme']) {
590 $url['path'] = self::removeDotSegments($url['path'] ?? '');
591 } else {
592 if (null !== $url['authority']) {
593 $url['path'] = self::removeDotSegments($url['path'] ?? '');
594 } else {
595 if (null === $url['path']) {
596 $url['path'] = $base['path'];
597 $url['query'] ??= $base['query'];
598 } else {
599 if ('/' !== $url['path'][0]) {
600 if (null === $base['path']) {
601 $url['path'] = '/'.$url['path'];
602 } else {
603 $segments = explode('/', $base['path']);
604 array_splice($segments, -1, 1, [$url['path']]);
605 $url['path'] = implode('/', $segments);
606 }
607 }
608
609 $url['path'] = self::removeDotSegments($url['path']);
610 }
611
612 $url['authority'] = $base['authority'];
613
614 if ($queryDefaults) {
615 $url['query'] = '?'.self::mergeQueryString(substr($url['query'] ?? '', 1), $queryDefaults, false);
616 }
617 }
618
619 $url['scheme'] = $base['scheme'];
620 }
621
622 if ('' === ($url['path'] ?? '')) {
623 $url['path'] = '/';
624 }
625
626 if ('?' === ($url['query'] ?? '')) {
627 $url['query'] = null;
628 }
629
630 if (null !== $url['scheme'] && null === $url['authority']) {
631 throw new InvalidArgumentException(\sprintf('Invalid URL: host is missing in "%s".', implode('', $givenUrl)));
632 }
633
634 return $url;
635 }
636
637 /**
638 * Parses a URL and fixes its encoding if needed.
639 *
640 * @throws InvalidArgumentException When an invalid URL is passed
641 */
642 private static function parseUrl(string $url, array $query = [], array $allowedSchemes = ['http' => 80, 'https' => 443]): array
643 {
644 if (false !== ($i = strpos($url, '\\')) && $i < strcspn($url, '?#')) {
645 throw new InvalidArgumentException(\sprintf('Malformed URL "%s": backslashes are not allowed.', $url));
646 }
647 if (\strlen($url) !== strcspn($url, "\r\n\t")) {
648 throw new InvalidArgumentException(\sprintf('Malformed URL "%s": CR/LF/TAB characters are not allowed.', $url));
649 }
650 if ('' !== $url && (\ord($url[0]) <= 32 || \ord($url[-1]) <= 32)) {
651 throw new InvalidArgumentException(\sprintf('Malformed URL "%s": leading/trailing ASCII control characters or spaces are not allowed.', $url));
652 }
653
654 $tail = '';
655
656 if (false === $parts = parse_url(\strlen($url) !== strcspn($url, '?#') ? $url : $url.$tail = '#')) {
657 throw new InvalidArgumentException(\sprintf('Malformed URL "%s".', $url));
658 }
659
660 if ($query) {
661 $parts['query'] = self::mergeQueryString($parts['query'] ?? null, $query, true);
662 }
663
664 $scheme = $parts['scheme'] ?? null;
665 $host = $parts['host'] ?? null;
666
667 if (!$scheme && $host && !str_starts_with($url, '//')) {
668 $parts = parse_url(':/'.$url.$tail);
669 $parts['path'] = substr($parts['path'], 2);
670 $scheme = $host = null;
671 }
672
673 $port = $parts['port'] ?? 0;
674
675 if (null !== $scheme) {
676 if (!isset($allowedSchemes[$scheme = strtolower($scheme)])) {
677 throw new InvalidArgumentException(\sprintf('Unsupported scheme in "%s": "%s" expected.', $url, implode('" or "', array_keys($allowedSchemes))));
678 }
679
680 $port = $allowedSchemes[$scheme] === $port ? 0 : $port;
681 $scheme .= ':';
682 }
683
684 if (null !== $host) {
685 if (!\defined('INTL_IDNA_VARIANT_UTS46') && preg_match('/[\x80-\xFF]/', $host)) {
686 throw new InvalidArgumentException(\sprintf('Unsupported IDN "%s", try enabling the "intl" PHP extension or running "composer require symfony/polyfill-intl-idn".', $host));
687 }
688
689 $host = \defined('INTL_IDNA_VARIANT_UTS46') ? idn_to_ascii($host, \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI | \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII, \INTL_IDNA_VARIANT_UTS46) ?: strtolower($host) : strtolower($host);
690 $host .= $port ? ':'.$port : '';
691 }
692
693 foreach (['user', 'pass', 'path', 'query', 'fragment'] as $part) {
694 if (!isset($parts[$part])) {
695 continue;
696 }
697
698 if (str_contains($parts[$part], '%')) {
699 // https://tools.ietf.org/html/rfc3986#section-2.3
700 $parts[$part] = preg_replace_callback('/%(?:2[DE]|3[0-9]|[46][1-9A-F]|5F|[57][0-9A]|7E)++/i', static fn ($m) => rawurldecode($m[0]), $parts[$part]);
701 }
702
703 // https://tools.ietf.org/html/rfc3986#section-3.3
704 $parts[$part] = preg_replace_callback("#[^-A-Za-z0-9._~!$&/'()[\]*+,;=:@{}%]++#", static fn ($m) => rawurlencode($m[0]), $parts[$part]);
705 }
706
707 return [
708 'scheme' => $scheme,
709 'authority' => null !== $host ? '//'.(isset($parts['user']) ? $parts['user'].(isset($parts['pass']) ? ':'.$parts['pass'] : '').'@' : '').$host : null,
710 'path' => isset($parts['path'][0]) ? $parts['path'] : null,
711 'query' => isset($parts['query']) ? '?'.$parts['query'] : null,
712 'fragment' => isset($parts['fragment']) && !$tail ? '#'.$parts['fragment'] : null,
713 ];
714 }
715
716 /**
717 * Removes dot-segments from a path.
718 *
719 * @see https://tools.ietf.org/html/rfc3986#section-5.2.4
720 */
721 private static function removeDotSegments(string $path): string
722 {
723 $result = '';
724
725 while (!\in_array($path, ['', '.', '..'], true)) {
726 if ('.' === $path[0] && (str_starts_with($path, $p = '../') || str_starts_with($path, $p = './'))) {
727 $path = substr($path, \strlen($p));
728 } elseif ('/.' === $path || str_starts_with($path, '/./')) {
729 $path = substr_replace($path, '/', 0, 3);
730 } elseif ('/..' === $path || str_starts_with($path, '/../')) {
731 $i = strrpos($result, '/');
732 $result = $i ? substr($result, 0, $i) : '';
733 $path = substr_replace($path, '/', 0, 4);
734 } else {
735 $i = strpos($path, '/', 1) ?: \strlen($path);
736 $result .= substr($path, 0, $i);
737 $path = substr($path, $i);
738 }
739 }
740
741 return $result;
742 }
743
744 /**
745 * Merges and encodes a query array with a query string.
746 *
747 * @throws InvalidArgumentException When an invalid query-string value is passed
748 */
749 private static function mergeQueryString(?string $queryString, array $queryArray, bool $replace): ?string
750 {
751 if (!$queryArray) {
752 return $queryString;
753 }
754
755 $query = [];
756
757 if (null !== $queryString) {
758 foreach (explode('&', $queryString) as $v) {
759 if ('' !== $v) {
760 $k = urldecode(explode('=', $v, 2)[0]);
761 $query[$k] = (isset($query[$k]) ? $query[$k].'&' : '').$v;
762 }
763 }
764 }
765
766 if ($replace) {
767 foreach ($queryArray as $k => $v) {
768 if (null === $v) {
769 unset($query[$k]);
770 }
771 }
772 }
773
774 $queryString = http_build_query($queryArray, '', '&', \PHP_QUERY_RFC3986);
775 $queryArray = [];
776
777 if ($queryString) {
778 if (str_contains($queryString, '%')) {
779 // https://tools.ietf.org/html/rfc3986#section-2.3 + some chars not encoded by browsers
780 $queryString = strtr($queryString, [
781 '%21' => '!',
782 '%24' => '$',
783 '%28' => '(',
784 '%29' => ')',
785 '%2A' => '*',
786 '%2F' => '/',
787 '%3A' => ':',
788 '%3B' => ';',
789 '%40' => '@',
790 '%5B' => '[',
791 '%5D' => ']',
792 ]);
793 }
794
795 foreach (explode('&', $queryString) as $v) {
796 $queryArray[rawurldecode(explode('=', $v, 2)[0])] = $v;
797 }
798 }
799
800 return implode('&', $replace ? array_replace($query, $queryArray) : ($query + $queryArray));
801 }
802
803 /**
804 * Loads proxy configuration from the same environment variables as curl when no proxy is explicitly set.
805 */
806 private static function getProxy(?string $proxy, array $url, ?string $noProxy): ?array
807 {
808 if (null === $proxy = self::getProxyUrl($proxy, $url)) {
809 return null;
810 }
811
812 $proxy = (parse_url($proxy) ?: []) + ['scheme' => 'http'];
813
814 if (!isset($proxy['host'])) {
815 throw new TransportException('Invalid HTTP proxy: host is missing.');
816 }
817
818 if ('http' === $proxy['scheme']) {
819 $proxyUrl = 'tcp://'.$proxy['host'].':'.($proxy['port'] ?? '80');
820 } elseif ('https' === $proxy['scheme']) {
821 $proxyUrl = 'ssl://'.$proxy['host'].':'.($proxy['port'] ?? '443');
822 } else {
823 throw new TransportException(\sprintf('Unsupported proxy scheme "%s": "http" or "https" expected.', $proxy['scheme']));
824 }
825
826 $noProxy ??= $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '';
827 $noProxy = $noProxy ? preg_split('/[\s,]+/', $noProxy) : [];
828
829 return [
830 'url' => $proxyUrl,
831 'auth' => isset($proxy['user']) ? 'Basic '.base64_encode(rawurldecode($proxy['user']).':'.rawurldecode($proxy['pass'] ?? '')) : null,
832 'no_proxy' => $noProxy,
833 ];
834 }
835
836 private static function getProxyUrl(?string $proxy, array $url): ?string
837 {
838 if (null !== $proxy) {
839 return $proxy;
840 }
841
842 // Ignore HTTP_PROXY except on the CLI to work around httpoxy set of vulnerabilities
843 $proxy = $_SERVER['http_proxy'] ?? (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? $_SERVER['HTTP_PROXY'] ?? null : null) ?? $_SERVER['all_proxy'] ?? $_SERVER['ALL_PROXY'] ?? null;
844
845 if ('https:' === $url['scheme']) {
846 $proxy = $_SERVER['https_proxy'] ?? $_SERVER['HTTPS_PROXY'] ?? $proxy;
847 }
848
849 return $proxy;
850 }
851
852 private static function shouldBuffer(array $headers): bool
853 {
854 if (null === $contentType = $headers['content-type'][0] ?? null) {
855 return false;
856 }
857
858 if (false !== $i = strpos($contentType, ';')) {
859 $contentType = substr($contentType, 0, $i);
860 }
861
862 return $contentType && preg_match('#^(?:text/|application/(?:.+\+)?(?:json|xml)$)#i', $contentType);
863 }
864 }