File indexing completed on 2025-01-26 05:29:13

0001 <?php
0002 namespace GuzzleHttp\Psr7;
0003 
0004 use Psr\Http\Message\UriInterface;
0005 
0006 /**
0007  * Provides methods to normalize and compare URIs.
0008  *
0009  * @author Tobias Schultze
0010  *
0011  * @link https://tools.ietf.org/html/rfc3986#section-6
0012  */
0013 final class UriNormalizer
0014 {
0015     /**
0016      * Default normalizations which only include the ones that preserve semantics.
0017      *
0018      * self::CAPITALIZE_PERCENT_ENCODING | self::DECODE_UNRESERVED_CHARACTERS | self::CONVERT_EMPTY_PATH |
0019      * self::REMOVE_DEFAULT_HOST | self::REMOVE_DEFAULT_PORT | self::REMOVE_DOT_SEGMENTS
0020      */
0021     const PRESERVING_NORMALIZATIONS = 63;
0022 
0023     /**
0024      * All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
0025      *
0026      * Example: http://example.org/a%c2%b1bhttp://example.org/a%C2%B1b
0027      */
0028     const CAPITALIZE_PERCENT_ENCODING = 1;
0029 
0030     /**
0031      * Decodes percent-encoded octets of unreserved characters.
0032      *
0033      * For consistency, percent-encoded octets in the ranges of ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39),
0034      * hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and,
0035      * when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.
0036      *
0037      * Example: http://example.org/%7Eusern%61me/http://example.org/~username/
0038      */
0039     const DECODE_UNRESERVED_CHARACTERS = 2;
0040 
0041     /**
0042      * Converts the empty path to "/" for http and https URIs.
0043      *
0044      * Example: http://example.orghttp://example.org/
0045      */
0046     const CONVERT_EMPTY_PATH = 4;
0047 
0048     /**
0049      * Removes the default host of the given URI scheme from the URI.
0050      *
0051      * Only the "file" scheme defines the default host "localhost".
0052      * All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile`
0053      * are equivalent according to RFC 3986. The first format is not accepted
0054      * by PHPs stream functions and thus already normalized implicitly to the
0055      * second format in the Uri class. See `GuzzleHttp\Psr7\Uri::composeComponents`.
0056      *
0057      * Example: file://localhost/myfile → file:///myfile
0058      */
0059     const REMOVE_DEFAULT_HOST = 8;
0060 
0061     /**
0062      * Removes the default port of the given URI scheme from the URI.
0063      *
0064      * Example: http://example.org:80/http://example.org/
0065      */
0066     const REMOVE_DEFAULT_PORT = 16;
0067 
0068     /**
0069      * Removes unnecessary dot-segments.
0070      *
0071      * Dot-segments in relative-path references are not removed as it would
0072      * change the semantics of the URI reference.
0073      *
0074      * Example: http://example.org/../a/b/../c/./d.htmlhttp://example.org/a/c/d.html
0075      */
0076     const REMOVE_DOT_SEGMENTS = 32;
0077 
0078     /**
0079      * Paths which include two or more adjacent slashes are converted to one.
0080      *
0081      * Webservers usually ignore duplicate slashes and treat those URIs equivalent.
0082      * But in theory those URIs do not need to be equivalent. So this normalization
0083      * may change the semantics. Encoded slashes (%2F) are not removed.
0084      *
0085      * Example: http://example.org//foo///bar.htmlhttp://example.org/foo/bar.html
0086      */
0087     const REMOVE_DUPLICATE_SLASHES = 64;
0088 
0089     /**
0090      * Sort query parameters with their values in alphabetical order.
0091      *
0092      * However, the order of parameters in a URI may be significant (this is not defined by the standard).
0093      * So this normalization is not safe and may change the semantics of the URI.
0094      *
0095      * Example: ?lang=en&article=fred → ?article=fred&lang=en
0096      *
0097      * Note: The sorting is neither locale nor Unicode aware (the URI query does not get decoded at all) as the
0098      * purpose is to be able to compare URIs in a reproducible way, not to have the params sorted perfectly.
0099      */
0100     const SORT_QUERY_PARAMETERS = 128;
0101 
0102     /**
0103      * Returns a normalized URI.
0104      *
0105      * The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
0106      * This methods adds additional normalizations that can be configured with the $flags parameter.
0107      *
0108      * PSR-7 UriInterface cannot distinguish between an empty component and a missing component as
0109      * getQuery(), getFragment() etc. always return a string. This means the URIs "/?#" and "/" are
0110      * treated equivalent which is not necessarily true according to RFC 3986. But that difference
0111      * is highly uncommon in reality. So this potential normalization is implied in PSR-7 as well.
0112      *
0113      * @param UriInterface $uri   The URI to normalize
0114      * @param int          $flags A bitmask of normalizations to apply, see constants
0115      *
0116      * @return UriInterface The normalized URI
0117      * @link https://tools.ietf.org/html/rfc3986#section-6.2
0118      */
0119     public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS)
0120     {
0121         if ($flags & self::CAPITALIZE_PERCENT_ENCODING) {
0122             $uri = self::capitalizePercentEncoding($uri);
0123         }
0124 
0125         if ($flags & self::DECODE_UNRESERVED_CHARACTERS) {
0126             $uri = self::decodeUnreservedCharacters($uri);
0127         }
0128 
0129         if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
0130             ($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
0131         ) {
0132             $uri = $uri->withPath('/');
0133         }
0134 
0135         if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') {
0136             $uri = $uri->withHost('');
0137         }
0138 
0139         if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) {
0140             $uri = $uri->withPort(null);
0141         }
0142 
0143         if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) {
0144             $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath()));
0145         }
0146 
0147         if ($flags & self::REMOVE_DUPLICATE_SLASHES) {
0148             $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath()));
0149         }
0150 
0151         if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') {
0152             $queryKeyValues = explode('&', $uri->getQuery());
0153             sort($queryKeyValues);
0154             $uri = $uri->withQuery(implode('&', $queryKeyValues));
0155         }
0156 
0157         return $uri;
0158     }
0159 
0160     /**
0161      * Whether two URIs can be considered equivalent.
0162      *
0163      * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also
0164      * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be
0165      * resolved against the same base URI. If this is not the case, determination of equivalence or difference of
0166      * relative references does not mean anything.
0167      *
0168      * @param UriInterface $uri1           An URI to compare
0169      * @param UriInterface $uri2           An URI to compare
0170      * @param int          $normalizations A bitmask of normalizations to apply, see constants
0171      *
0172      * @return bool
0173      * @link https://tools.ietf.org/html/rfc3986#section-6.1
0174      */
0175     public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS)
0176     {
0177         return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations);
0178     }
0179 
0180     private static function capitalizePercentEncoding(UriInterface $uri)
0181     {
0182         $regex = '/(?:%[A-Fa-f0-9]{2})++/';
0183 
0184         $callback = function (array $match) {
0185             return strtoupper($match[0]);
0186         };
0187 
0188         return
0189             $uri->withPath(
0190                 preg_replace_callback($regex, $callback, $uri->getPath())
0191             )->withQuery(
0192                 preg_replace_callback($regex, $callback, $uri->getQuery())
0193             );
0194     }
0195 
0196     private static function decodeUnreservedCharacters(UriInterface $uri)
0197     {
0198         $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i';
0199 
0200         $callback = function (array $match) {
0201             return rawurldecode($match[0]);
0202         };
0203 
0204         return
0205             $uri->withPath(
0206                 preg_replace_callback($regex, $callback, $uri->getPath())
0207             )->withQuery(
0208                 preg_replace_callback($regex, $callback, $uri->getQuery())
0209             );
0210     }
0211 
0212     private function __construct()
0213     {
0214         // cannot be instantiated
0215     }
0216 }