UriNormalizer.php 8.1 KB

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