Debian Codegraph @

lib/3rdParty/composer/guzzlehttp/psr7/src/Uri.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace GuzzleHttp\Psr7;
6
7 use GuzzleHttp\Psr7\Exception\MalformedUriException;
8 use Psr\Http\Message\UriInterface;
9
10 /**
11 * PSR-7 URI implementation.
12 *
13 * @author Michael Dowling
14 * @author Tobias Schultze
15 * @author Matthew Weier O'Phinney
16 */
17 class Uri implements UriInterface, \JsonSerializable
18 {
19 /**
20 * Absolute http and https URIs require a host per RFC 7230 Section 2.7
21 * but in generic URIs the host can be empty. So for http(s) URIs
22 * we apply this default host when no host is given yet to form a
23 * valid URI.
24 */
25 private const HTTP_DEFAULT_HOST = 'localhost';
26
27 private const DEFAULT_PORTS = [
28 'http' => 80,
29 'https' => 443,
30 'ftp' => 21,
31 'gopher' => 70,
32 'nntp' => 119,
33 'news' => 119,
34 'telnet' => 23,
35 'tn3270' => 23,
36 'imap' => 143,
37 'pop' => 110,
38 'ldap' => 389,
39 ];
40
41 private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26', '+' => '%2B'];
42
43 /** @var string Uri scheme. */
44 private $scheme = '';
45
46 /** @var string Uri user info. */
47 private $userInfo = '';
48
49 /** @var string Uri host. */
50 private $host = '';
51
52 /** @var int|null Uri port. */
53 private $port;
54
55 /** @var string Uri path. */
56 private $path = '';
57
58 /** @var string Uri query string. */
59 private $query = '';
60
61 /** @var string Uri fragment. */
62 private $fragment = '';
63
64 public function __construct(string $uri = '')
65 {
66 if ($uri !== '') {
67 $parts = self::parse($uri);
68 if ($parts === false) {
69 throw new MalformedUriException("Unable to parse URI: $uri");
70 }
71 try {
72 $this->applyParts($parts);
73 } catch (MalformedUriException $e) {
74 throw $e;
75 } catch (\InvalidArgumentException $e) {
76 throw new MalformedUriException($e->getMessage(), 0, $e);
77 }
78 }
79 }
80
81 /**
82 * UTF-8 aware \parse_url() replacement.
83 *
84 * The internal function produces broken output for non ASCII domain names
85 * (IDN) when used with locales other than "C".
86 *
87 * On the other hand, cURL understands IDN correctly only when UTF-8 locale
88 * is configured ("C.UTF-8", "en_US.UTF-8", etc.).
89 *
90 * @see https://bugs.php.net/bug.php?id=52923
91 * @see https://www.php.net/manual/en/function.parse-url.php#114817
92 * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
93 *
94 * @return array|false
95 */
96 private static function parse(string $url)
97 {
98 if (self::isPathNoSchemeReference($url)) {
99 return self::parsePathNoSchemeReference($url);
100 }
101
102 // Preserve bracketed IPv6 literals before encoding, including dotted IPv4 tails.
103 $prefix = '';
104 if (preg_match('%^([0-9A-Za-z+.-]+://\[[0-9:.a-fA-F]+\])(.*?)$%', $url, $matches)) {
105 /** @var array{0:string, 1:string, 2:string} $matches */
106 $prefix = $matches[1];
107 $url = $matches[2];
108 }
109
110 /** @var string|null */
111 $encodedUrl = preg_replace_callback(
112 '%[^:/@?&=#]+%usD',
113 static function ($matches) {
114 return urlencode($matches[0]);
115 },
116 $url
117 );
118
119 if ($encodedUrl === null) {
120 return false;
121 }
122
123 $result = parse_url($prefix.$encodedUrl);
124
125 if ($result === false) {
126 return false;
127 }
128
129 return array_map('urldecode', $result);
130 }
131
132 private static function isPathNoSchemeReference(string $url): bool
133 {
134 if ($url === '' || $url[0] === '/' || $url[0] === '?' || $url[0] === '#') {
135 return false;
136 }
137
138 $firstSegment = substr($url, 0, strcspn($url, '/?#'));
139
140 return strpos($firstSegment, ':') === false;
141 }
142
143 /**
144 * @return array{path: string, query?: string, fragment?: string}
145 */
146 private static function parsePathNoSchemeReference(string $url): array
147 {
148 $parts = [];
149
150 if (false !== ($fragmentPosition = strpos($url, '#'))) {
151 $parts['fragment'] = substr($url, $fragmentPosition + 1);
152 $url = substr($url, 0, $fragmentPosition);
153 }
154
155 if (false !== ($queryPosition = strpos($url, '?'))) {
156 $parts['query'] = substr($url, $queryPosition + 1);
157 $url = substr($url, 0, $queryPosition);
158 }
159
160 $parts['path'] = $url;
161
162 return $parts;
163 }
164
165 public function __toString(): string
166 {
167 return self::composeComponents(
168 $this->scheme,
169 $this->getAuthority(),
170 $this->path,
171 $this->query,
172 $this->fragment
173 );
174 }
175
176 /**
177 * Composes a URI reference string from its various components.
178 *
179 * Usually this method does not need to be called manually but instead is used indirectly via
180 * `Psr\Http\Message\UriInterface::__toString`.
181 *
182 * PSR-7 UriInterface treats an empty component the same as a missing component as
183 * getQuery(), getFragment() etc. always return a string. This explains the slight
184 * difference to RFC 3986 Section 5.3.
185 *
186 * Another adjustment is that the authority separator is added even when the authority is missing/empty
187 * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
188 * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
189 * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
190 * that format).
191 *
192 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
193 */
194 public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string
195 {
196 $uri = '';
197
198 // weak type checks to also accept null until we can add scalar type hints
199 if ($scheme != '') {
200 $uri .= $scheme.':';
201 }
202
203 if ($authority != '' || $scheme === 'file') {
204 $uri .= '//'.$authority;
205 }
206
207 if ($authority != '' && $path != '' && $path[0] != '/') {
208 $path = '/'.$path;
209 }
210
211 $uri .= $path;
212
213 if ($query != '') {
214 $uri .= '?'.$query;
215 }
216
217 if ($fragment != '') {
218 $uri .= '#'.$fragment;
219 }
220
221 return $uri;
222 }
223
224 /**
225 * Whether the URI has the default port of the current scheme.
226 *
227 * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
228 * independently of the implementation.
229 */
230 public static function isDefaultPort(UriInterface $uri): bool
231 {
232 return $uri->getPort() === null
233 || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]);
234 }
235
236 /**
237 * Whether the URI is absolute, i.e. it has a scheme.
238 *
239 * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
240 * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
241 * to another URI, the base URI. Relative references can be divided into several forms:
242 * - network-path references, e.g. '//example.com/path'
243 * - absolute-path references, e.g. '/path'
244 * - relative-path references, e.g. 'subpath'
245 *
246 * @see Uri::isNetworkPathReference
247 * @see Uri::isAbsolutePathReference
248 * @see Uri::isRelativePathReference
249 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4
250 */
251 public static function isAbsolute(UriInterface $uri): bool
252 {
253 return $uri->getScheme() !== '';
254 }
255
256 /**
257 * Whether the URI is a network-path reference.
258 *
259 * A relative reference that begins with two slash characters is termed an network-path reference.
260 *
261 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
262 */
263 public static function isNetworkPathReference(UriInterface $uri): bool
264 {
265 return $uri->getScheme() === '' && $uri->getAuthority() !== '';
266 }
267
268 /**
269 * Whether the URI is a absolute-path reference.
270 *
271 * A relative reference that begins with a single slash character is termed an absolute-path reference.
272 *
273 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
274 */
275 public static function isAbsolutePathReference(UriInterface $uri): bool
276 {
277 return $uri->getScheme() === ''
278 && $uri->getAuthority() === ''
279 && isset($uri->getPath()[0])
280 && $uri->getPath()[0] === '/';
281 }
282
283 /**
284 * Whether the URI is a relative-path reference.
285 *
286 * A relative reference that does not begin with a slash character is termed a relative-path reference.
287 *
288 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
289 */
290 public static function isRelativePathReference(UriInterface $uri): bool
291 {
292 return $uri->getScheme() === ''
293 && $uri->getAuthority() === ''
294 && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
295 }
296
297 /**
298 * Whether the URI is a same-document reference.
299 *
300 * A same-document reference refers to a URI that is, aside from its fragment
301 * component, identical to the base URI. When no base URI is given, only an empty
302 * URI reference (apart from its fragment) is considered a same-document reference.
303 *
304 * @param UriInterface $uri The URI to check
305 * @param UriInterface|null $base An optional base URI to compare against
306 *
307 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4
308 */
309 public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool
310 {
311 if ($base !== null) {
312 $uri = UriResolver::resolve($base, $uri);
313
314 return ($uri->getScheme() === $base->getScheme())
315 && ($uri->getAuthority() === $base->getAuthority())
316 && ($uri->getPath() === $base->getPath())
317 && ($uri->getQuery() === $base->getQuery());
318 }
319
320 return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
321 }
322
323 /**
324 * Creates a new URI with a specific query string value removed.
325 *
326 * Any existing query string values that exactly match the provided key are
327 * removed.
328 *
329 * @param UriInterface $uri URI to use as a base.
330 * @param string $key Query string key to remove.
331 */
332 public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface
333 {
334 $result = self::getFilteredQueryString($uri, [$key]);
335
336 return $uri->withQuery(implode('&', $result));
337 }
338
339 /**
340 * Creates a new URI with a specific query string value.
341 *
342 * Any existing query string values that exactly match the provided key are
343 * removed and replaced with the given key value pair.
344 *
345 * A value of null will set the query string key without a value, e.g. "key"
346 * instead of "key=value".
347 *
348 * @param UriInterface $uri URI to use as a base.
349 * @param string $key Key to set.
350 * @param string|null $value Value to set
351 */
352 public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface
353 {
354 $result = self::getFilteredQueryString($uri, [$key]);
355
356 $result[] = self::generateQueryString($key, $value);
357
358 return $uri->withQuery(implode('&', $result));
359 }
360
361 /**
362 * Creates a new URI with multiple specific query string values.
363 *
364 * It has the same behavior as withQueryValue() but for an associative array of key => value.
365 *
366 * @param UriInterface $uri URI to use as a base.
367 * @param (string|null)[] $keyValueArray Associative array of key and values
368 */
369 public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface
370 {
371 $result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
372
373 foreach ($keyValueArray as $key => $value) {
374 $result[] = self::generateQueryString((string) $key, $value !== null ? (string) $value : null);
375 }
376
377 return $uri->withQuery(implode('&', $result));
378 }
379
380 /**
381 * Creates a URI from a hash of `parse_url` components.
382 *
383 * @see https://www.php.net/manual/en/function.parse-url.php
384 *
385 * @throws MalformedUriException If the components do not form a valid URI.
386 */
387 public static function fromParts(array $parts): UriInterface
388 {
389 $uri = new self();
390 try {
391 $uri->applyParts($parts);
392 $uri->validateState();
393 } catch (MalformedUriException $e) {
394 throw $e;
395 } catch (\InvalidArgumentException $e) {
396 throw new MalformedUriException($e->getMessage(), 0, $e);
397 }
398
399 return $uri;
400 }
401
402 /**
403 * @throws \InvalidArgumentException If the host is invalid.
404 *
405 * @internal
406 */
407 public static function assertValidHost(string $host): void
408 {
409 if ($host === '') {
410 return;
411 }
412
413 if (preg_match('/[\x00-\x20\x7F]/', $host)) {
414 throw new \InvalidArgumentException(sprintf('Invalid host: "%s"', $host));
415 }
416 }
417
418 public function getScheme(): string
419 {
420 return $this->scheme;
421 }
422
423 public function getAuthority(): string
424 {
425 $authority = $this->host;
426 if ($this->userInfo !== '') {
427 $authority = $this->userInfo.'@'.$authority;
428 }
429
430 if ($this->port !== null) {
431 $authority .= ':'.$this->port;
432 }
433
434 return $authority;
435 }
436
437 public function getUserInfo(): string
438 {
439 return $this->userInfo;
440 }
441
442 public function getHost(): string
443 {
444 return $this->host;
445 }
446
447 public function getPort(): ?int
448 {
449 return $this->port;
450 }
451
452 public function getPath(): string
453 {
454 return $this->path;
455 }
456
457 public function getQuery(): string
458 {
459 return $this->query;
460 }
461
462 public function getFragment(): string
463 {
464 return $this->fragment;
465 }
466
467 public function withScheme($scheme): UriInterface
468 {
469 $scheme = $this->filterScheme($scheme);
470
471 if ($this->scheme === $scheme) {
472 return $this;
473 }
474
475 $new = clone $this;
476 $new->scheme = $scheme;
477 $new->removeDefaultPort();
478 $new->validateState();
479
480 return $new;
481 }
482
483 public function withUserInfo($user, $password = null): UriInterface
484 {
485 $info = $this->filterUserInfoComponent($user);
486 if ($password !== null) {
487 $info .= ':'.$this->filterUserInfoComponent($password);
488 }
489
490 if ($this->userInfo === $info) {
491 return $this;
492 }
493
494 $new = clone $this;
495 $new->userInfo = $info;
496 $new->validateState();
497
498 return $new;
499 }
500
501 public function withHost($host): UriInterface
502 {
503 $host = $this->filterHost($host);
504
505 if ($this->host === $host) {
506 return $this;
507 }
508
509 $new = clone $this;
510 $new->host = $host;
511 $new->validateState();
512
513 return $new;
514 }
515
516 public function withPort($port): UriInterface
517 {
518 if ($port !== null && !\is_int($port)) {
519 \trigger_deprecation(
520 'guzzlehttp/psr7',
521 '2.11',
522 'Passing %s to UriInterface::withPort() is deprecated; guzzlehttp/psr7 3.0 requires int|null.',
523 \get_debug_type($port)
524 );
525 }
526
527 $port = $this->filterPort($port);
528
529 if ($this->port === $port) {
530 return $this;
531 }
532
533 $new = clone $this;
534 $new->port = $port;
535 $new->removeDefaultPort();
536 $new->validateState();
537
538 return $new;
539 }
540
541 public function withPath($path): UriInterface
542 {
543 $path = $this->filterPath($path);
544
545 if ($this->path === $path) {
546 return $this;
547 }
548
549 $new = clone $this;
550 $new->path = $path;
551 $new->validateState();
552
553 return $new;
554 }
555
556 public function withQuery($query): UriInterface
557 {
558 $query = $this->filterQueryAndFragment($query);
559
560 if ($this->query === $query) {
561 return $this;
562 }
563
564 $new = clone $this;
565 $new->query = $query;
566
567 return $new;
568 }
569
570 public function withFragment($fragment): UriInterface
571 {
572 $fragment = $this->filterQueryAndFragment($fragment);
573
574 if ($this->fragment === $fragment) {
575 return $this;
576 }
577
578 $new = clone $this;
579 $new->fragment = $fragment;
580
581 return $new;
582 }
583
584 public function jsonSerialize(): string
585 {
586 return $this->__toString();
587 }
588
589 /**
590 * Apply parse_url parts to a URI.
591 *
592 * @param array $parts Array of parse_url parts to apply.
593 */
594 private function applyParts(array $parts): void
595 {
596 $this->scheme = isset($parts['scheme'])
597 ? $this->filterScheme($parts['scheme'])
598 : '';
599 $this->userInfo = isset($parts['user'])
600 ? $this->filterUserInfoComponent($parts['user'])
601 : '';
602 $this->host = isset($parts['host'])
603 ? $this->filterHost($parts['host'])
604 : '';
605 $this->port = isset($parts['port'])
606 ? $this->filterPort($parts['port'])
607 : null;
608 $this->path = isset($parts['path'])
609 ? $this->filterPath($parts['path'])
610 : '';
611 $this->query = isset($parts['query'])
612 ? $this->filterQueryAndFragment($parts['query'])
613 : '';
614 $this->fragment = isset($parts['fragment'])
615 ? $this->filterQueryAndFragment($parts['fragment'])
616 : '';
617 if (isset($parts['pass'])) {
618 $this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']);
619 }
620
621 $this->removeDefaultPort();
622 }
623
624 /**
625 * @param mixed $scheme
626 *
627 * @throws \InvalidArgumentException If the scheme is invalid.
628 */
629 private function filterScheme($scheme): string
630 {
631 if (!is_string($scheme)) {
632 throw new \InvalidArgumentException('Scheme must be a string');
633 }
634
635 $scheme = \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
636
637 if ($scheme !== '' && !preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme)) {
638 \trigger_deprecation(
639 'guzzlehttp/psr7',
640 '2.11',
641 'Passing "%s" as a URI scheme is deprecated; guzzlehttp/psr7 3.0 requires URI schemes to match RFC 3986 syntax and begin with a letter.',
642 $scheme
643 );
644 }
645
646 return $scheme;
647 }
648
649 /**
650 * @param mixed $component
651 *
652 * @throws \InvalidArgumentException If the user info is invalid.
653 */
654 private function filterUserInfoComponent($component): string
655 {
656 if (!is_string($component)) {
657 throw new \InvalidArgumentException('User info must be a string');
658 }
659
660 return preg_replace_callback(
661 '/(?:[^%'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.']+|%(?![A-Fa-f0-9]{2}))/',
662 [$this, 'rawurlencodeMatchZero'],
663 $component
664 );
665 }
666
667 /**
668 * @param mixed $host
669 *
670 * @throws \InvalidArgumentException If the host is invalid.
671 */
672 private function filterHost($host): string
673 {
674 if (!is_string($host)) {
675 throw new \InvalidArgumentException('Host must be a string');
676 }
677
678 $host = \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
679 self::assertValidHost($host);
680
681 return $host;
682 }
683
684 /**
685 * @param mixed $port
686 *
687 * @throws \InvalidArgumentException If the port is invalid.
688 */
689 private function filterPort($port): ?int
690 {
691 if ($port === null) {
692 return null;
693 }
694
695 $port = (int) $port;
696 if (0 > $port || 0xFFFF < $port) {
697 throw new \InvalidArgumentException(
698 sprintf('Invalid port: %d. Must be between 0 and 65535', $port)
699 );
700 }
701
702 return $port;
703 }
704
705 /**
706 * @param (string|int)[] $keys
707 *
708 * @return string[]
709 */
710 private static function getFilteredQueryString(UriInterface $uri, array $keys): array
711 {
712 $current = $uri->getQuery();
713
714 if ($current === '') {
715 return [];
716 }
717
718 $decodedKeys = array_map(function ($k): string {
719 return rawurldecode((string) $k);
720 }, $keys);
721
722 return array_filter(explode('&', $current), function ($part) use ($decodedKeys) {
723 return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true);
724 });
725 }
726
727 private static function generateQueryString(string $key, ?string $value): string
728 {
729 // Query string separators ("=", "&") and literal plus signs ("+") within the
730 // key or value need to be encoded
731 // (while preventing double-encoding) before setting the query string. All other
732 // chars that need percent-encoding will be encoded by withQuery().
733 $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT);
734
735 if ($value !== null) {
736 $queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT);
737 }
738
739 return $queryString;
740 }
741
742 private function removeDefaultPort(): void
743 {
744 if ($this->port !== null && self::isDefaultPort($this)) {
745 $this->port = null;
746 }
747 }
748
749 /**
750 * Filters the path of a URI
751 *
752 * @param mixed $path
753 *
754 * @throws \InvalidArgumentException If the path is invalid.
755 */
756 private function filterPath($path): string
757 {
758 if (!is_string($path)) {
759 throw new \InvalidArgumentException('Path must be a string');
760 }
761
762 return preg_replace_callback(
763 '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
764 [$this, 'rawurlencodeMatchZero'],
765 $path
766 );
767 }
768
769 /**
770 * Filters the query string or fragment of a URI.
771 *
772 * @param mixed $str
773 *
774 * @throws \InvalidArgumentException If the query or fragment is invalid.
775 */
776 private function filterQueryAndFragment($str): string
777 {
778 if (!is_string($str)) {
779 throw new \InvalidArgumentException('Query and fragment must be a string');
780 }
781
782 return preg_replace_callback(
783 '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
784 [$this, 'rawurlencodeMatchZero'],
785 $str
786 );
787 }
788
789 private function rawurlencodeMatchZero(array $match): string
790 {
791 return rawurlencode($match[0]);
792 }
793
794 private function validateState(): void
795 {
796 if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
797 $this->host = self::HTTP_DEFAULT_HOST;
798 }
799
800 if ($this->getAuthority() === '') {
801 if (0 === strpos($this->path, '//')) {
802 throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"');
803 }
804 if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
805 throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon');
806 }
807 }
808 }
809 }