UriNormalizer.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. declare(strict_types=1);
  3. namespace GuzzleHttp\Psr7;
  4. use Psr\Http\Message\UriInterface;
  5. /**
  6. * Provides methods to normalize and compare URIs.
  7. *
  8. * @author Tobias Schultze
  9. *
  10. * @link https://tools.ietf.org/html/rfc3986#section-6
  11. */
  12. final class UriNormalizer
  13. {
  14. /**
  15. * Default normalizations which only include the ones that preserve semantics.
  16. */
  17. public const PRESERVING_NORMALIZATIONS =
  18. self::CAPITALIZE_PERCENT_ENCODING |
  19. self::DECODE_UNRESERVED_CHARACTERS |
  20. self::CONVERT_EMPTY_PATH |
  21. self::REMOVE_DEFAULT_HOST |
  22. self::REMOVE_DEFAULT_PORT |
  23. self::REMOVE_DOT_SEGMENTS;
  24. /**
  25. * All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
  26. *
  27. * Example: http://example.org/a%c2%b1b → http://example.org/a%C2%B1b
  28. */
  29. public const CAPITALIZE_PERCENT_ENCODING = 1;
  30. /**
  31. * Decodes percent-encoded octets of unreserved characters.
  32. *
  33. * For consistency, percent-encoded octets in the ranges of ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39),
  34. * hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and,
  35. * when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.
  36. *
  37. * Example: http://example.org/%7Eusern%61me/ → http://example.org/~username/
  38. */
  39. public const DECODE_UNRESERVED_CHARACTERS = 2;
  40. /**
  41. * Converts the empty path to "/" for http and https URIs.
  42. *
  43. * Example: http://example.org → http://example.org/
  44. */
  45. public const CONVERT_EMPTY_PATH = 4;
  46. /**
  47. * Removes the default host of the given URI scheme from the URI.
  48. *
  49. * Only the "file" scheme defines the default host "localhost".
  50. * All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile`
  51. * are equivalent according to RFC 3986. The first format is not accepted
  52. * by PHPs stream functions and thus already normalized implicitly to the
  53. * second format in the Uri class. See `GuzzleHttp\Psr7\Uri::composeComponents`.
  54. *
  55. * Example: file://localhost/myfile → file:///myfile
  56. */
  57. public const REMOVE_DEFAULT_HOST = 8;
  58. /**
  59. * Removes the default port of the given URI scheme from the URI.
  60. *
  61. * Example: http://example.org:80/ → http://example.org/
  62. */
  63. public const REMOVE_DEFAULT_PORT = 16;
  64. /**
  65. * Removes unnecessary dot-segments.
  66. *
  67. * Dot-segments in relative-path references are not removed as it would
  68. * change the semantics of the URI reference.
  69. *
  70. * Example: http://example.org/../a/b/../c/./d.html → http://example.org/a/c/d.html
  71. */
  72. public const REMOVE_DOT_SEGMENTS = 32;
  73. /**
  74. * Paths which include two or more adjacent slashes are converted to one.
  75. *
  76. * Webservers usually ignore duplicate slashes and treat those URIs equivalent.
  77. * But in theory those URIs do not need to be equivalent. So this normalization
  78. * may change the semantics. Encoded slashes (%2F) are not removed.
  79. *
  80. * Example: http://example.org//foo///bar.html → http://example.org/foo/bar.html
  81. */
  82. public const REMOVE_DUPLICATE_SLASHES = 64;
  83. /**
  84. * Sort query parameters with their values in alphabetical order.
  85. *
  86. * However, the order of parameters in a URI may be significant (this is not defined by the standard).
  87. * So this normalization is not safe and may change the semantics of the URI.
  88. *
  89. * Example: ?lang=en&article=fred → ?article=fred&lang=en
  90. *
  91. * Note: The sorting is neither locale nor Unicode aware (the URI query does not get decoded at all) as the
  92. * purpose is to be able to compare URIs in a reproducible way, not to have the params sorted perfectly.
  93. */
  94. public const SORT_QUERY_PARAMETERS = 128;
  95. /**
  96. * Returns a normalized URI.
  97. *
  98. * The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
  99. * This methods adds additional normalizations that can be configured with the $flags parameter.
  100. *
  101. * PSR-7 UriInterface cannot distinguish between an empty component and a missing component as
  102. * getQuery(), getFragment() etc. always return a string. This means the URIs "/?#" and "/" are
  103. * treated equivalent which is not necessarily true according to RFC 3986. But that difference
  104. * is highly uncommon in reality. So this potential normalization is implied in PSR-7 as well.
  105. *
  106. * @param UriInterface $uri The URI to normalize
  107. * @param int $flags A bitmask of normalizations to apply, see constants
  108. *
  109. * @link https://tools.ietf.org/html/rfc3986#section-6.2
  110. */
  111. public static function normalize(UriInterface $uri, int $flags = self::PRESERVING_NORMALIZATIONS): UriInterface
  112. {
  113. if ($flags & self::CAPITALIZE_PERCENT_ENCODING) {
  114. $uri = self::capitalizePercentEncoding($uri);
  115. }
  116. if ($flags & self::DECODE_UNRESERVED_CHARACTERS) {
  117. $uri = self::decodeUnreservedCharacters($uri);
  118. }
  119. if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
  120. ($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
  121. ) {
  122. $uri = $uri->withPath('/');
  123. }
  124. if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') {
  125. $uri = $uri->withHost('');
  126. }
  127. if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) {
  128. $uri = $uri->withPort(null);
  129. }
  130. if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) {
  131. $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath()));
  132. }
  133. if ($flags & self::REMOVE_DUPLICATE_SLASHES) {
  134. $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath()));
  135. }
  136. if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') {
  137. $queryKeyValues = explode('&', $uri->getQuery());
  138. sort($queryKeyValues);
  139. $uri = $uri->withQuery(implode('&', $queryKeyValues));
  140. }
  141. return $uri;
  142. }
  143. /**
  144. * Whether two URIs can be considered equivalent.
  145. *
  146. * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also
  147. * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be
  148. * resolved against the same base URI. If this is not the case, determination of equivalence or difference of
  149. * relative references does not mean anything.
  150. *
  151. * @param UriInterface $uri1 An URI to compare
  152. * @param UriInterface $uri2 An URI to compare
  153. * @param int $normalizations A bitmask of normalizations to apply, see constants
  154. *
  155. * @link https://tools.ietf.org/html/rfc3986#section-6.1
  156. */
  157. public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool
  158. {
  159. return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations);
  160. }
  161. private static function capitalizePercentEncoding(UriInterface $uri): UriInterface
  162. {
  163. $regex = '/(?:%[A-Fa-f0-9]{2})++/';
  164. $callback = function (array $match) {
  165. return strtoupper($match[0]);
  166. };
  167. return
  168. $uri->withPath(
  169. preg_replace_callback($regex, $callback, $uri->getPath())
  170. )->withQuery(
  171. preg_replace_callback($regex, $callback, $uri->getQuery())
  172. );
  173. }
  174. private static function decodeUnreservedCharacters(UriInterface $uri): UriInterface
  175. {
  176. $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i';
  177. $callback = function (array $match) {
  178. return rawurldecode($match[0]);
  179. };
  180. return
  181. $uri->withPath(
  182. preg_replace_callback($regex, $callback, $uri->getPath())
  183. )->withQuery(
  184. preg_replace_callback($regex, $callback, $uri->getQuery())
  185. );
  186. }
  187. private function __construct()
  188. {
  189. // cannot be instantiated
  190. }
  191. }