2 namespace GuzzleHttp\Psr7;
4 use Psr\Http\Message\UriInterface;
7 * PSR-7 URI implementation.
9 * @author Michael Dowling
10 * @author Tobias Schultze
11 * @author Matthew Weier O'Phinney
13 class Uri implements UriInterface
16 * Absolute http and https URIs require a host per RFC 7230 Section 2.7
17 * but in generic URIs the host can be empty. So for http(s) URIs
18 * we apply this default host when no host is given yet to form a
21 const HTTP_DEFAULT_HOST = 'localhost';
23 private static $defaultPorts = [
37 private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
38 private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
39 private static $replaceQuery = ['=' => '%3D', '&' => '%26'];
41 /** @var string Uri scheme. */
44 /** @var string Uri user info. */
45 private $userInfo = '';
47 /** @var string Uri host. */
50 /** @var int|null Uri port. */
53 /** @var string Uri path. */
56 /** @var string Uri query string. */
59 /** @var string Uri fragment. */
60 private $fragment = '';
63 * @param string $uri URI to parse
65 public function __construct($uri = '')
67 // weak type check to also accept null until we can add scalar type hints
69 $parts = parse_url($uri);
70 if ($parts === false) {
71 throw new \InvalidArgumentException("Unable to parse URI: $uri");
73 $this->applyParts($parts);
77 public function __toString()
79 return self::composeComponents(
81 $this->getAuthority(),
89 * Composes a URI reference string from its various components.
91 * Usually this method does not need to be called manually but instead is used indirectly via
92 * `Psr\Http\Message\UriInterface::__toString`.
94 * PSR-7 UriInterface treats an empty component the same as a missing component as
95 * getQuery(), getFragment() etc. always return a string. This explains the slight
96 * difference to RFC 3986 Section 5.3.
98 * Another adjustment is that the authority separator is added even when the authority is missing/empty
99 * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with
100 * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But
101 * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
104 * @param string $scheme
105 * @param string $authority
106 * @param string $path
107 * @param string $query
108 * @param string $fragment
112 * @link https://tools.ietf.org/html/rfc3986#section-5.3
114 public static function composeComponents($scheme, $authority, $path, $query, $fragment)
118 // weak type checks to also accept null until we can add scalar type hints
120 $uri .= $scheme . ':';
123 if ($authority != ''|| $scheme === 'file') {
124 $uri .= '//' . $authority;
130 $uri .= '?' . $query;
133 if ($fragment != '') {
134 $uri .= '#' . $fragment;
141 * Whether the URI has the default port of the current scheme.
143 * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used
144 * independently of the implementation.
146 * @param UriInterface $uri
150 public static function isDefaultPort(UriInterface $uri)
152 return $uri->getPort() === null
153 || (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]);
157 * Whether the URI is absolute, i.e. it has a scheme.
159 * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true
160 * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative
161 * to another URI, the base URI. Relative references can be divided into several forms:
162 * - network-path references, e.g. '//example.com/path'
163 * - absolute-path references, e.g. '/path'
164 * - relative-path references, e.g. 'subpath'
166 * @param UriInterface $uri
169 * @see Uri::isNetworkPathReference
170 * @see Uri::isAbsolutePathReference
171 * @see Uri::isRelativePathReference
172 * @link https://tools.ietf.org/html/rfc3986#section-4
174 public static function isAbsolute(UriInterface $uri)
176 return $uri->getScheme() !== '';
180 * Whether the URI is a network-path reference.
182 * A relative reference that begins with two slash characters is termed an network-path reference.
184 * @param UriInterface $uri
187 * @link https://tools.ietf.org/html/rfc3986#section-4.2
189 public static function isNetworkPathReference(UriInterface $uri)
191 return $uri->getScheme() === '' && $uri->getAuthority() !== '';
195 * Whether the URI is a absolute-path reference.
197 * A relative reference that begins with a single slash character is termed an absolute-path reference.
199 * @param UriInterface $uri
202 * @link https://tools.ietf.org/html/rfc3986#section-4.2
204 public static function isAbsolutePathReference(UriInterface $uri)
206 return $uri->getScheme() === ''
207 && $uri->getAuthority() === ''
208 && isset($uri->getPath()[0])
209 && $uri->getPath()[0] === '/';
213 * Whether the URI is a relative-path reference.
215 * A relative reference that does not begin with a slash character is termed a relative-path reference.
217 * @param UriInterface $uri
220 * @link https://tools.ietf.org/html/rfc3986#section-4.2
222 public static function isRelativePathReference(UriInterface $uri)
224 return $uri->getScheme() === ''
225 && $uri->getAuthority() === ''
226 && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/');
230 * Whether the URI is a same-document reference.
232 * A same-document reference refers to a URI that is, aside from its fragment
233 * component, identical to the base URI. When no base URI is given, only an empty
234 * URI reference (apart from its fragment) is considered a same-document reference.
236 * @param UriInterface $uri The URI to check
237 * @param UriInterface|null $base An optional base URI to compare against
240 * @link https://tools.ietf.org/html/rfc3986#section-4.4
242 public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
244 if ($base !== null) {
245 $uri = UriResolver::resolve($base, $uri);
247 return ($uri->getScheme() === $base->getScheme())
248 && ($uri->getAuthority() === $base->getAuthority())
249 && ($uri->getPath() === $base->getPath())
250 && ($uri->getQuery() === $base->getQuery());
253 return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === '';
257 * Removes dot segments from a path and returns the new path.
259 * @param string $path
263 * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead.
264 * @see UriResolver::removeDotSegments
266 public static function removeDotSegments($path)
268 return UriResolver::removeDotSegments($path);
272 * Converts the relative URI into a new URI that is resolved against the base URI.
274 * @param UriInterface $base Base URI
275 * @param string|UriInterface $rel Relative URI
277 * @return UriInterface
279 * @deprecated since version 1.4. Use UriResolver::resolve instead.
280 * @see UriResolver::resolve
282 public static function resolve(UriInterface $base, $rel)
284 if (!($rel instanceof UriInterface)) {
285 $rel = new self($rel);
288 return UriResolver::resolve($base, $rel);
292 * Creates a new URI with a specific query string value removed.
294 * Any existing query string values that exactly match the provided key are
297 * @param UriInterface $uri URI to use as a base.
298 * @param string $key Query string key to remove.
300 * @return UriInterface
302 public static function withoutQueryValue(UriInterface $uri, $key)
304 $current = $uri->getQuery();
305 if ($current === '') {
309 $decodedKey = rawurldecode($key);
310 $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) {
311 return rawurldecode(explode('=', $part)[0]) !== $decodedKey;
314 return $uri->withQuery(implode('&', $result));
318 * Creates a new URI with a specific query string value.
320 * Any existing query string values that exactly match the provided key are
321 * removed and replaced with the given key value pair.
323 * A value of null will set the query string key without a value, e.g. "key"
324 * instead of "key=value".
326 * @param UriInterface $uri URI to use as a base.
327 * @param string $key Key to set.
328 * @param string|null $value Value to set
330 * @return UriInterface
332 public static function withQueryValue(UriInterface $uri, $key, $value)
334 $current = $uri->getQuery();
336 if ($current === '') {
339 $decodedKey = rawurldecode($key);
340 $result = array_filter(explode('&', $current), function ($part) use ($decodedKey) {
341 return rawurldecode(explode('=', $part)[0]) !== $decodedKey;
345 // Query string separators ("=", "&") within the key or value need to be encoded
346 // (while preventing double-encoding) before setting the query string. All other
347 // chars that need percent-encoding will be encoded by withQuery().
348 $key = strtr($key, self::$replaceQuery);
350 if ($value !== null) {
351 $result[] = $key . '=' . strtr($value, self::$replaceQuery);
356 return $uri->withQuery(implode('&', $result));
360 * Creates a URI from a hash of `parse_url` components.
362 * @param array $parts
364 * @return UriInterface
365 * @link http://php.net/manual/en/function.parse-url.php
367 * @throws \InvalidArgumentException If the components do not form a valid URI.
369 public static function fromParts(array $parts)
372 $uri->applyParts($parts);
373 $uri->validateState();
378 public function getScheme()
380 return $this->scheme;
383 public function getAuthority()
385 $authority = $this->host;
386 if ($this->userInfo !== '') {
387 $authority = $this->userInfo . '@' . $authority;
390 if ($this->port !== null) {
391 $authority .= ':' . $this->port;
397 public function getUserInfo()
399 return $this->userInfo;
402 public function getHost()
407 public function getPort()
412 public function getPath()
417 public function getQuery()
422 public function getFragment()
424 return $this->fragment;
427 public function withScheme($scheme)
429 $scheme = $this->filterScheme($scheme);
431 if ($this->scheme === $scheme) {
436 $new->scheme = $scheme;
437 $new->removeDefaultPort();
438 $new->validateState();
443 public function withUserInfo($user, $password = null)
446 if ($password != '') {
447 $info .= ':' . $password;
450 if ($this->userInfo === $info) {
455 $new->userInfo = $info;
456 $new->validateState();
461 public function withHost($host)
463 $host = $this->filterHost($host);
465 if ($this->host === $host) {
471 $new->validateState();
476 public function withPort($port)
478 $port = $this->filterPort($port);
480 if ($this->port === $port) {
486 $new->removeDefaultPort();
487 $new->validateState();
492 public function withPath($path)
494 $path = $this->filterPath($path);
496 if ($this->path === $path) {
502 $new->validateState();
507 public function withQuery($query)
509 $query = $this->filterQueryAndFragment($query);
511 if ($this->query === $query) {
516 $new->query = $query;
521 public function withFragment($fragment)
523 $fragment = $this->filterQueryAndFragment($fragment);
525 if ($this->fragment === $fragment) {
530 $new->fragment = $fragment;
536 * Apply parse_url parts to a URI.
538 * @param array $parts Array of parse_url parts to apply.
540 private function applyParts(array $parts)
542 $this->scheme = isset($parts['scheme'])
543 ? $this->filterScheme($parts['scheme'])
545 $this->userInfo = isset($parts['user']) ? $parts['user'] : '';
546 $this->host = isset($parts['host'])
547 ? $this->filterHost($parts['host'])
549 $this->port = isset($parts['port'])
550 ? $this->filterPort($parts['port'])
552 $this->path = isset($parts['path'])
553 ? $this->filterPath($parts['path'])
555 $this->query = isset($parts['query'])
556 ? $this->filterQueryAndFragment($parts['query'])
558 $this->fragment = isset($parts['fragment'])
559 ? $this->filterQueryAndFragment($parts['fragment'])
561 if (isset($parts['pass'])) {
562 $this->userInfo .= ':' . $parts['pass'];
565 $this->removeDefaultPort();
569 * @param string $scheme
573 * @throws \InvalidArgumentException If the scheme is invalid.
575 private function filterScheme($scheme)
577 if (!is_string($scheme)) {
578 throw new \InvalidArgumentException('Scheme must be a string');
581 return strtolower($scheme);
585 * @param string $host
589 * @throws \InvalidArgumentException If the host is invalid.
591 private function filterHost($host)
593 if (!is_string($host)) {
594 throw new \InvalidArgumentException('Host must be a string');
597 return strtolower($host);
601 * @param int|null $port
605 * @throws \InvalidArgumentException If the port is invalid.
607 private function filterPort($port)
609 if ($port === null) {
614 if (1 > $port || 0xffff < $port) {
615 throw new \InvalidArgumentException(
616 sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
623 private function removeDefaultPort()
625 if ($this->port !== null && self::isDefaultPort($this)) {
631 * Filters the path of a URI
633 * @param string $path
637 * @throws \InvalidArgumentException If the path is invalid.
639 private function filterPath($path)
641 if (!is_string($path)) {
642 throw new \InvalidArgumentException('Path must be a string');
645 return preg_replace_callback(
646 '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
647 [$this, 'rawurlencodeMatchZero'],
653 * Filters the query string or fragment of a URI.
659 * @throws \InvalidArgumentException If the query or fragment is invalid.
661 private function filterQueryAndFragment($str)
663 if (!is_string($str)) {
664 throw new \InvalidArgumentException('Query and fragment must be a string');
667 return preg_replace_callback(
668 '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
669 [$this, 'rawurlencodeMatchZero'],
674 private function rawurlencodeMatchZero(array $match)
676 return rawurlencode($match[0]);
679 private function validateState()
681 if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) {
682 $this->host = self::HTTP_DEFAULT_HOST;
685 if ($this->getAuthority() === '') {
686 if (0 === strpos($this->path, '//')) {
687 throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"');
689 if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) {
690 throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon');
692 } elseif (isset($this->path[0]) && $this->path[0] !== '/') {
694 'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' .
695 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.',
698 $this->path = '/'. $this->path;
699 //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty');