vendor/guzzlehttp/psr7/src/Uri.php

884 lines · 26661 bytes

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