Debian Codegraph @

vendor/guzzlehttp/psr7/src/Uri.php

raw
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 $ipv6Prefix = preg_match('%\A([0-9A-Za-z+.-]+://\[[^\]\x00-\x20/?#@]+\])(.*)\z%s', $url, $matches);
105
106 if ($ipv6Prefix === false) {
107 return false;
108 }
109
110 if ($ipv6Prefix === 1) {
111 /** @var array{0:string, 1:string, 2:string} $matches */
112 $suffix = $matches[2];
113
114 if ($suffix !== '' && strpos(':/?#', $suffix[0]) === false) {
115 return false;
116 }
117
118 $prefix = $matches[1];
119 $url = $suffix;
120 }
121
122 /** @var string|null */
123 $encodedUrl = preg_replace_callback(
124 '%[^:/@?&=#]+%usD',
125 static function ($matches) {
126 return urlencode($matches[0]);
127 },
128 $url
129 );
130
131 if ($encodedUrl === null) {
132 return false;
133 }
134
135 $result = parse_url($prefix.$encodedUrl);
136
137 if ($result === false) {
138 return false;
139 }
140
141 return array_map('urldecode', $result);
142 }
143
144 private static function isPathNoSchemeReference(string $url): bool
145 {
146 if ($url === '' || $url[0] === '/' || $url[0] === '?' || $url[0] === '#') {
147 return false;
148 }
149
150 $firstSegment = substr($url, 0, strcspn($url, '/?#'));
151
152 return strpos($firstSegment, ':') === false;
153 }
154
155 /**
156 * @return array{path: string, query?: string, fragment?: string}
157 */
158 private static function parsePathNoSchemeReference(string $url): array
159 {
160 $parts = [];
161
162 if (false !== ($fragmentPosition = strpos($url, '#'))) {
163 $parts['fragment'] = substr($url, $fragmentPosition + 1);
164 $url = substr($url, 0, $fragmentPosition);
165 }
166
167 if (false !== ($queryPosition = strpos($url, '?'))) {
168 $parts['query'] = substr($url, $queryPosition + 1);
169 $url = substr($url, 0, $queryPosition);
170 }
171
172 $parts['path'] = $url;
173
174 return $parts;
175 }
176
177 public function __toString(): string
178 {
179 return self::composeComponents(
180 $this->scheme,
181 $this->getAuthority(),
182 $this->path,
183 $this->query,
184 $this->fragment
185 );
186 }
187
188 /**
189 * Composes a URI reference string from its various components.
190 *
191 * Usually this method does not need to be called manually but instead is used indirectly via
192 * `Psr\Http\Message\UriInterface::__toString`.
193 *
194 * PSR-7 UriInterface treats an empty component the same as a missing component as
195 * getQuery(), getFragment() etc. always return a string. This explains the slight
196 * difference to RFC 3986 Section 5.3.
197 *
198 * Another adjustment is that the authority separator is added even when the authority is missing/empty
199 * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
200 * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
201 * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
202 * that format).
203 *
204 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
205 */
206 public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string
207 {
208 $uri = '';
209
210 // weak type checks to also accept null until we can add scalar type hints
211 if ($scheme != '') {
212 $uri .= $scheme.':';
213 }
214
215 if ($authority != '' || $scheme === 'file') {
216 $uri .= '//'.$authority;
217 }
218
219 if ($authority != '' && $path != '' && $path[0] != '/') {
220 $path = '/'.$path;
221 }
222
223 $uri .= $path;
224
225 if ($query != '') {
226 $uri .= '?'.$query;
227 }
228
229 if ($fragment != '') {
230 $uri .= '#'.$fragment;
231 }
232
233 return $uri;
234 }
235
236 /**
237 * Whether the URI has the default port of the current scheme.
238 *
239 * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
240 * independently of the implementation.
241 */
242 public static function isDefaultPort(UriInterface $uri): bool
243 {
244 return $uri->getPort() === null
245 || (isset(self::DEFAULT_PORTS[$uri->getScheme()]) && $uri->getPort() === self::DEFAULT_PORTS[$uri->getScheme()]);
246 }
247
248 /**
249 * Whether the URI is absolute, i.e. it has a scheme.
250 *
251 * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
252 * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
253 * to another URI, the base URI. Relative references can be divided into several forms:
254 * - network-path references, e.g. '//example.com/path'
255 * - absolute-path references, e.g. '/path'
256 * - relative-path references, e.g. 'subpath'
257 *
258 * @see Uri::isNetworkPathReference
259 * @see Uri::isAbsolutePathReference
260 * @see Uri::isRelativePathReference
261 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4
262 */
263 public static function isAbsolute(UriInterface $uri): bool
264 {
265 return $uri->getScheme() !== '';
266 }
267
268 /**
269 * Whether the URI is a network-path reference.
270 *
271 * A relative reference that begins with two slash characters is termed an network-path reference.
272 *
273 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
274 */
275 public static function isNetworkPathReference(UriInterface $uri): bool
276 {
277 return $uri->getScheme() === '' && $uri->getAuthority() !== '';
278 }
279
280 /**
281 * Whether the URI is a absolute-path reference.
282 *
283 * A relative reference that begins with a single slash character is termed an absolute-path reference.
284 *
285 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
286 */
287 public static function isAbsolutePathReference(UriInterface $uri): bool
288 {
289 return $uri->getScheme() === ''
290 && $uri->getAuthority() === ''
291 && isset($uri->getPath()[0])
292 && $uri->getPath()[0] === '/';
293 }
294
295 /**
296 * Whether the URI is a relative-path reference.
297 *
298 * A relative reference that does not begin with a slash character is termed a relative-path reference.
299 *
300 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
301 */
302 public static function isRelativePathReference(UriInterface $uri): bool
303 {
304 return $uri->getScheme() === ''
305 && $uri->getAuthority() === ''
306 && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
307 }
308
309 /**
310 * Whether the URI is a same-document reference.
311 *
312 * A same-document reference refers to a URI that is, aside from its fragment
313 * component, identical to the base URI. When no base URI is given, only an empty
314 * URI reference (apart from its fragment) is considered a same-document reference.
315 *
316 * @param UriInterface $uri The URI to check
317 * @param UriInterface|null $base An optional base URI to compare against
318 *
319 * @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4
320 */
321 public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool
322 {
323 if ($base !== null) {
324 $uri = UriResolver::resolve($base, $uri);
325
326 return ($uri->getScheme() === $base->getScheme())
327 && ($uri->getAuthority() === $base->getAuthority())
328 && ($uri->getPath() === $base->getPath())
329 && ($uri->getQuery() === $base->getQuery());
330 }
331
332 return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
333 }
334
335 /**
336 * Creates a new URI with a specific query string value removed.
337 *
338 * Any existing query string values that exactly match the provided key are
339 * removed.
340 *
341 * @param UriInterface $uri URI to use as a base.
342 * @param string $key Query string key to remove.
343 */
344 public static function withoutQueryValue(UriInterface $uri, string $key): UriInterface
345 {
346 $result = self::getFilteredQueryString($uri, [$key]);
347
348 return $uri->withQuery(implode('&', $result));
349 }
350
351 /**
352 * Creates a new URI with a specific query string value.
353 *
354 * Any existing query string values that exactly match the provided key are
355 * removed and replaced with the given key value pair.
356 *
357 * A value of null will set the query string key without a value, e.g. "key"
358 * instead of "key=value".
359 *
360 * @param UriInterface $uri URI to use as a base.
361 * @param string $key Key to set.
362 * @param string|null $value Value to set
363 */
364 public static function withQueryValue(UriInterface $uri, string $key, ?string $value): UriInterface
365 {
366 $result = self::getFilteredQueryString($uri, [$key]);
367
368 $result[] = self::generateQueryString($key, $value);
369
370 return $uri->withQuery(implode('&', $result));
371 }
372
373 /**
374 * Creates a new URI with multiple specific query string values.
375 *
376 * It has the same behavior as withQueryValue() but for an associative array of key => value.
377 *
378 * @param UriInterface $uri URI to use as a base.
379 * @param (string|null)[] $keyValueArray Associative array of key and values
380 */
381 public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface
382 {
383 $result = self::getFilteredQueryString($uri, array_keys($keyValueArray));
384
385 foreach ($keyValueArray as $key => $value) {
386 $result[] = self::generateQueryString((string) $key, $value !== null ? self::stringifyQueryValue($value) : null);
387 }
388
389 return $uri->withQuery(implode('&', $result));
390 }
391
392 /**
393 * Stringifies a non-null query value, deprecating non-string values that
394 * guzzlehttp/psr7 3.0 will reject. Non-finite floats are normalized to the
395 * strings PHP coerces them to, as implicit coercion of NAN emits a warning
396 * on PHP 8.5.
397 *
398 * @param mixed $value
399 */
400 private static function stringifyQueryValue($value): string
401 {
402 if (!is_string($value)) {
403 \trigger_deprecation(
404 'guzzlehttp/psr7',
405 '2.12',
406 'Passing %s to Uri::withQueryValues() is deprecated; cast it to a string. guzzlehttp/psr7 3.0 will only accept string or null query values.',
407 \gettype($value)
408 );
409
410 if (is_float($value) && !is_finite($value)) {
411 return is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
412 }
413 }
414
415 return (string) $value;
416 }
417
418 /**
419 * Creates a URI from a hash of `parse_url` components.
420 *
421 * @see https://www.php.net/manual/en/function.parse-url.php
422 *
423 * @throws MalformedUriException If the components do not form a valid URI.
424 */
425 public static function fromParts(array $parts): UriInterface
426 {
427 $uri = new self();
428 try {
429 $uri->applyParts($parts);
430 $uri->validateState();
431 } catch (MalformedUriException $e) {
432 throw $e;
433 } catch (\InvalidArgumentException $e) {
434 throw new MalformedUriException($e->getMessage(), 0, $e);
435 }
436
437 return $uri;
438 }
439
440 /**
441 * @throws \InvalidArgumentException If the host is invalid.
442 *
443 * @internal
444 */
445 public static function assertValidHost(string $host): void
446 {
447 if ($host === '') {
448 return;
449 }
450
451 // Reject control characters and URI authority delimiters so getHost()
452 // cannot disagree with the on-wire authority.
453 $invalidHost = preg_match('/[\x00-\x20\x7F\/\?#@\\\\]/', $host);
454
455 if ($invalidHost === false) {
456 throw new \RuntimeException('Unable to validate URI host: '.preg_last_error_msg());
457 }
458
459 if ($invalidHost === 1) {
460 throw new \InvalidArgumentException(sprintf('Invalid host: "%s"', $host));
461 }
462
463 if (strpos($host, '[') !== false || strpos($host, ']') !== false) {
464 if ($host[0] !== '[' || substr($host, -1) !== ']') {
465 throw new \InvalidArgumentException(sprintf('Invalid host: "%s"', $host));
466 }
467
468 return;
469 }
470
471 if (strpos($host, ':') !== false) {
472 throw new \InvalidArgumentException(sprintf('Invalid host: "%s"', $host));
473 }
474 }
475
476 public function getScheme(): string
477 {
478 return $this->scheme;
479 }
480
481 public function getAuthority(): string
482 {
483 $authority = $this->host;
484 if ($this->userInfo !== '') {
485 $authority = $this->userInfo.'@'.$authority;
486 }
487
488 if ($this->port !== null) {
489 $authority .= ':'.$this->port;
490 }
491
492 return $authority;
493 }
494
495 public function getUserInfo(): string
496 {
497 return $this->userInfo;
498 }
499
500 public function getHost(): string
501 {
502 return $this->host;
503 }
504
505 public function getPort(): ?int
506 {
507 return $this->port;
508 }
509
510 public function getPath(): string
511 {
512 return $this->path;
513 }
514
515 public function getQuery(): string
516 {
517 return $this->query;
518 }
519
520 public function getFragment(): string
521 {
522 return $this->fragment;
523 }
524
525 public function withScheme($scheme): UriInterface
526 {
527 $scheme = $this->filterScheme($scheme);
528
529 if ($this->scheme === $scheme) {
530 return $this;
531 }
532
533 $new = clone $this;
534 $new->scheme = $scheme;
535 $new->removeDefaultPort();
536 $new->validateState();
537
538 return $new;
539 }
540
541 public function withUserInfo($user, $password = null): UriInterface
542 {
543 $info = $this->filterUserInfoComponent($user);
544 if ($password !== null) {
545 $info .= ':'.$this->filterUserInfoComponent($password);
546 }
547
548 if ($this->userInfo === $info) {
549 return $this;
550 }
551
552 $new = clone $this;
553 $new->userInfo = $info;
554 $new->validateState();
555
556 return $new;
557 }
558
559 public function withHost($host): UriInterface
560 {
561 $host = $this->filterHost($host);
562
563 if ($this->host === $host) {
564 return $this;
565 }
566
567 $new = clone $this;
568 $new->host = $host;
569 $new->validateState();
570
571 return $new;
572 }
573
574 public function withPort($port): UriInterface
575 {
576 if ($port !== null && !\is_int($port)) {
577 \trigger_deprecation(
578 'guzzlehttp/psr7',
579 '2.11',
580 'Passing %s to UriInterface::withPort() is deprecated; guzzlehttp/psr7 3.0 requires int|null.',
581 \get_debug_type($port)
582 );
583 }
584
585 $port = $this->filterPort($port);
586
587 if ($this->port === $port) {
588 return $this;
589 }
590
591 $new = clone $this;
592 $new->port = $port;
593 $new->removeDefaultPort();
594 $new->validateState();
595
596 return $new;
597 }
598
599 public function withPath($path): UriInterface
600 {
601 $path = $this->filterPath($path);
602
603 if ($this->path === $path) {
604 return $this;
605 }
606
607 $new = clone $this;
608 $new->path = $path;
609 $new->validateState();
610
611 return $new;
612 }
613
614 public function withQuery($query): UriInterface
615 {
616 $query = $this->filterQueryAndFragment($query);
617
618 if ($this->query === $query) {
619 return $this;
620 }
621
622 $new = clone $this;
623 $new->query = $query;
624
625 return $new;
626 }
627
628 public function withFragment($fragment): UriInterface
629 {
630 $fragment = $this->filterQueryAndFragment($fragment);
631
632 if ($this->fragment === $fragment) {
633 return $this;
634 }
635
636 $new = clone $this;
637 $new->fragment = $fragment;
638
639 return $new;
640 }
641
642 public function jsonSerialize(): string
643 {
644 return $this->__toString();
645 }
646
647 /**
648 * Apply parse_url parts to a URI.
649 *
650 * @param array $parts Array of parse_url parts to apply.
651 */
652 private function applyParts(array $parts): void
653 {
654 $this->scheme = isset($parts['scheme'])
655 ? $this->filterScheme($parts['scheme'])
656 : '';
657 $this->userInfo = isset($parts['user'])
658 ? $this->filterUserInfoComponent($parts['user'])
659 : '';
660 $this->host = isset($parts['host'])
661 ? $this->filterHost($parts['host'])
662 : '';
663 $this->port = isset($parts['port'])
664 ? $this->filterPort($parts['port'])
665 : null;
666 $this->path = isset($parts['path'])
667 ? $this->filterPath($parts['path'])
668 : '';
669 $this->query = isset($parts['query'])
670 ? $this->filterQueryAndFragment($parts['query'])
671 : '';
672 $this->fragment = isset($parts['fragment'])
673 ? $this->filterQueryAndFragment($parts['fragment'])
674 : '';
675 if (isset($parts['pass'])) {
676 $this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']);
677 }
678
679 $this->removeDefaultPort();
680 }
681
682 /**
683 * @param mixed $scheme
684 *
685 * @throws \InvalidArgumentException If the scheme is invalid.
686 */
687 private function filterScheme($scheme): string
688 {
689 if (!is_string($scheme)) {
690 throw new \InvalidArgumentException('Scheme must be a string');
691 }
692
693 $scheme = \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
694
695 if ($scheme !== '' && !preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme)) {
696 \trigger_deprecation(
697 'guzzlehttp/psr7',
698 '2.11',
699 '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.',
700 $scheme
701 );
702 }
703
704 return $scheme;
705 }
706
707 /**
708 * @param mixed $component
709 *
710 * @throws \InvalidArgumentException If the user info is invalid.
711 */
712 private function filterUserInfoComponent($component): string
713 {
714 if (!is_string($component)) {
715 throw new \InvalidArgumentException('User info must be a string');
716 }
717
718 return $this->filterComponent(
719 '/(?:[^%'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.']+|%(?![A-Fa-f0-9]{2}))/',
720 $component,
721 'Unable to filter URI user info'
722 );
723 }
724
725 /**
726 * @param mixed $host
727 *
728 * @throws \InvalidArgumentException If the host is invalid.
729 */
730 private function filterHost($host): string
731 {
732 if (!is_string($host)) {
733 throw new \InvalidArgumentException('Host must be a string');
734 }
735
736 $host = \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
737 self::assertValidHost($host);
738
739 return $host;
740 }
741
742 /**
743 * @param mixed $port
744 *
745 * @throws \InvalidArgumentException If the port is invalid.
746 */
747 private function filterPort($port): ?int
748 {
749 if ($port === null) {
750 return null;
751 }
752
753 $port = (int) $port;
754 if (0 > $port || 0xFFFF < $port) {
755 throw new \InvalidArgumentException(
756 sprintf('Invalid port: %d. Must be between 0 and 65535', $port)
757 );
758 }
759
760 return $port;
761 }
762
763 /**
764 * @param (string|int)[] $keys
765 *
766 * @return string[]
767 */
768 private static function getFilteredQueryString(UriInterface $uri, array $keys): array
769 {
770 $current = $uri->getQuery();
771
772 if ($current === '') {
773 return [];
774 }
775
776 $decodedKeys = array_map(function ($k): string {
777 return rawurldecode((string) $k);
778 }, $keys);
779
780 return array_filter(explode('&', $current), function ($part) use ($decodedKeys) {
781 return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true);
782 });
783 }
784
785 private static function generateQueryString(string $key, ?string $value): string
786 {
787 // Query string separators ("=", "&") and literal plus signs ("+") within the
788 // key or value need to be encoded
789 // (while preventing double-encoding) before setting the query string. All other
790 // chars that need percent-encoding will be encoded by withQuery().
791 $queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT);
792
793 if ($value !== null) {
794 $queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT);
795 }
796
797 return $queryString;
798 }
799
800 private function removeDefaultPort(): void
801 {
802 if ($this->port !== null && self::isDefaultPort($this)) {
803 $this->port = null;
804 }
805 }
806
807 /**
808 * Filters the path of a URI
809 *
810 * @param mixed $path
811 *
812 * @throws \InvalidArgumentException If the path is invalid.
813 */
814 private function filterPath($path): string
815 {
816 if (!is_string($path)) {
817 throw new \InvalidArgumentException('Path must be a string');
818 }
819
820 return $this->filterComponent(
821 '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
822 $path,
823 'Unable to filter URI path'
824 );
825 }
826
827 /**
828 * Filters the query string or fragment of a URI.
829 *
830 * @param mixed $str
831 *
832 * @throws \InvalidArgumentException If the query or fragment is invalid.
833 */
834 private function filterQueryAndFragment($str): string
835 {
836 if (!is_string($str)) {
837 throw new \InvalidArgumentException('Query and fragment must be a string');
838 }
839
840 return $this->filterComponent(
841 '/(?:[^'.Rfc3986::CHAR_UNRESERVED.Rfc3986::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
842 $str,
843 'Unable to filter URI query or fragment'
844 );
845 }
846
847 private function filterComponent(string $pattern, string $component, string $context): string
848 {
849 $filtered = preg_replace_callback($pattern, [$this, 'rawurlencodeMatchZero'], $component);
850
851 if ($filtered === null) {
852 throw new \RuntimeException($context.': '.preg_last_error_msg());
853 }
854
855 return $filtered;
856 }
857
858 private function rawurlencodeMatchZero(array $match): string
859 {
860 return rawurlencode($match[0]);
861 }
862
863 private function validateState(): void
864 {
865 if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
866 $this->host = self::HTTP_DEFAULT_HOST;
867 }
868
869 if ($this->getAuthority() === '') {
870 if (0 === strpos($this->path, '//')) {
871 throw new MalformedUriException('The path of a URI without an authority must not start with two slashes "//"');
872 }
873 if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
874 throw new MalformedUriException('A relative URI must not have a path beginning with a segment containing a colon');
875 }
876 }
877 }
878 }