UriResolver.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\UriInterface;
  5. /**
  6. * Resolves a URI reference in the context of a base URI and the opposite way.
  7. *
  8. * @author Tobias Schultze
  9. *
  10. * @link https://tools.ietf.org/html/rfc3986#section-5
  11. */
  12. final class UriResolver
  13. {
  14. /**
  15. * Removes dot segments from a path and returns the new path.
  16. *
  17. * @link http://tools.ietf.org/html/rfc3986#section-5.2.4
  18. */
  19. public static function removeDotSegments(string $path): string
  20. {
  21. if ($path === '' || $path === '/') {
  22. return $path;
  23. }
  24. $results = [];
  25. $segments = explode('/', $path);
  26. foreach ($segments as $segment) {
  27. if ($segment === '..') {
  28. array_pop($results);
  29. } elseif ($segment !== '.') {
  30. $results[] = $segment;
  31. }
  32. }
  33. $newPath = implode('/', $results);
  34. if ($path[0] === '/' && (!isset($newPath[0]) || $newPath[0] !== '/')) {
  35. // Re-add the leading slash if necessary for cases like "/.."
  36. $newPath = '/' . $newPath;
  37. } elseif ($newPath !== '' && ($segment === '.' || $segment === '..')) {
  38. // Add the trailing slash if necessary
  39. // If newPath is not empty, then $segment must be set and is the last segment from the foreach
  40. $newPath .= '/';
  41. }
  42. return $newPath;
  43. }
  44. /**
  45. * Converts the relative URI into a new URI that is resolved against the base URI.
  46. *
  47. * @link http://tools.ietf.org/html/rfc3986#section-5.2
  48. */
  49. public static function resolve(UriInterface $base, UriInterface $rel): UriInterface
  50. {
  51. if ((string) $rel === '') {
  52. // we can simply return the same base URI instance for this same-document reference
  53. return $base;
  54. }
  55. if ($rel->getScheme() != '') {
  56. return $rel->withPath(self::removeDotSegments($rel->getPath()));
  57. }
  58. if ($rel->getAuthority() != '') {
  59. $targetAuthority = $rel->getAuthority();
  60. $targetPath = self::removeDotSegments($rel->getPath());
  61. $targetQuery = $rel->getQuery();
  62. } else {
  63. $targetAuthority = $base->getAuthority();
  64. if ($rel->getPath() === '') {
  65. $targetPath = $base->getPath();
  66. $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery();
  67. } else {
  68. if ($rel->getPath()[0] === '/') {
  69. $targetPath = $rel->getPath();
  70. } else {
  71. if ($targetAuthority != '' && $base->getPath() === '') {
  72. $targetPath = '/' . $rel->getPath();
  73. } else {
  74. $lastSlashPos = strrpos($base->getPath(), '/');
  75. if ($lastSlashPos === false) {
  76. $targetPath = $rel->getPath();
  77. } else {
  78. $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath();
  79. }
  80. }
  81. }
  82. $targetPath = self::removeDotSegments($targetPath);
  83. $targetQuery = $rel->getQuery();
  84. }
  85. }
  86. return new Uri(Uri::composeComponents(
  87. $base->getScheme(),
  88. $targetAuthority,
  89. $targetPath,
  90. $targetQuery,
  91. $rel->getFragment()
  92. ));
  93. }
  94. /**
  95. * Returns the target URI as a relative reference from the base URI.
  96. *
  97. * This method is the counterpart to resolve():
  98. *
  99. * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
  100. *
  101. * One use-case is to use the current request URI as base URI and then generate relative links in your documents
  102. * to reduce the document size or offer self-contained downloadable document archives.
  103. *
  104. * $base = new Uri('http://example.com/a/b/');
  105. * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
  106. * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
  107. * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
  108. * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
  109. *
  110. * This method also accepts a target that is already relative and will try to relativize it further. Only a
  111. * relative-path reference will be returned as-is.
  112. *
  113. * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well
  114. */
  115. public static function relativize(UriInterface $base, UriInterface $target): UriInterface
  116. {
  117. if ($target->getScheme() !== '' &&
  118. ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
  119. ) {
  120. return $target;
  121. }
  122. if (Uri::isRelativePathReference($target)) {
  123. // As the target is already highly relative we return it as-is. It would be possible to resolve
  124. // the target with `$target = self::resolve($base, $target);` and then try make it more relative
  125. // by removing a duplicate query. But let's not do that automatically.
  126. return $target;
  127. }
  128. if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) {
  129. return $target->withScheme('');
  130. }
  131. // We must remove the path before removing the authority because if the path starts with two slashes, the URI
  132. // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also
  133. // invalid.
  134. $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost('');
  135. if ($base->getPath() !== $target->getPath()) {
  136. return $emptyPathUri->withPath(self::getRelativePath($base, $target));
  137. }
  138. if ($base->getQuery() === $target->getQuery()) {
  139. // Only the target fragment is left. And it must be returned even if base and target fragment are the same.
  140. return $emptyPathUri->withQuery('');
  141. }
  142. // If the base URI has a query but the target has none, we cannot return an empty path reference as it would
  143. // inherit the base query component when resolving.
  144. if ($target->getQuery() === '') {
  145. $segments = explode('/', $target->getPath());
  146. /** @var string $lastSegment */
  147. $lastSegment = end($segments);
  148. return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment);
  149. }
  150. return $emptyPathUri;
  151. }
  152. private static function getRelativePath(UriInterface $base, UriInterface $target): string
  153. {
  154. $sourceSegments = explode('/', $base->getPath());
  155. $targetSegments = explode('/', $target->getPath());
  156. array_pop($sourceSegments);
  157. $targetLastSegment = array_pop($targetSegments);
  158. foreach ($sourceSegments as $i => $segment) {
  159. if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) {
  160. unset($sourceSegments[$i], $targetSegments[$i]);
  161. } else {
  162. break;
  163. }
  164. }
  165. $targetSegments[] = $targetLastSegment;
  166. $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments);
  167. // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./".
  168. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  169. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name.
  170. if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) {
  171. $relativePath = "./$relativePath";
  172. } elseif ('/' === $relativePath[0]) {
  173. if ($base->getAuthority() != '' && $base->getPath() === '') {
  174. // In this case an extra slash is added by resolve() automatically. So we must not add one here.
  175. $relativePath = ".$relativePath";
  176. } else {
  177. $relativePath = "./$relativePath";
  178. }
  179. }
  180. return $relativePath;
  181. }
  182. private function __construct()
  183. {
  184. // cannot be instantiated
  185. }
  186. }