You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

808 lines
26 KiB

3 years ago
  1. # PSR-7 Message Implementation
  2. This repository contains a full [PSR-7](http://www.php-fig.org/psr/psr-7/)
  3. message implementation, several stream decorators, and some helpful
  4. functionality like query string parsing.
  5. ![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg)
  6. ![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg)
  7. # Stream implementation
  8. This package comes with a number of stream implementations and stream
  9. decorators.
  10. ## AppendStream
  11. `GuzzleHttp\Psr7\AppendStream`
  12. Reads from multiple streams, one after the other.
  13. ```php
  14. use GuzzleHttp\Psr7;
  15. $a = Psr7\Utils::streamFor('abc, ');
  16. $b = Psr7\Utils::streamFor('123.');
  17. $composed = new Psr7\AppendStream([$a, $b]);
  18. $composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));
  19. echo $composed; // abc, 123. Above all listen to me.
  20. ```
  21. ## BufferStream
  22. `GuzzleHttp\Psr7\BufferStream`
  23. Provides a buffer stream that can be written to fill a buffer, and read
  24. from to remove bytes from the buffer.
  25. This stream returns a "hwm" metadata value that tells upstream consumers
  26. what the configured high water mark of the stream is, or the maximum
  27. preferred size of the buffer.
  28. ```php
  29. use GuzzleHttp\Psr7;
  30. // When more than 1024 bytes are in the buffer, it will begin returning
  31. // false to writes. This is an indication that writers should slow down.
  32. $buffer = new Psr7\BufferStream(1024);
  33. ```
  34. ## CachingStream
  35. The CachingStream is used to allow seeking over previously read bytes on
  36. non-seekable streams. This can be useful when transferring a non-seekable
  37. entity body fails due to needing to rewind the stream (for example, resulting
  38. from a redirect). Data that is read from the remote stream will be buffered in
  39. a PHP temp stream so that previously read bytes are cached first in memory,
  40. then on disk.
  41. ```php
  42. use GuzzleHttp\Psr7;
  43. $original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
  44. $stream = new Psr7\CachingStream($original);
  45. $stream->read(1024);
  46. echo $stream->tell();
  47. // 1024
  48. $stream->seek(0);
  49. echo $stream->tell();
  50. // 0
  51. ```
  52. ## DroppingStream
  53. `GuzzleHttp\Psr7\DroppingStream`
  54. Stream decorator that begins dropping data once the size of the underlying
  55. stream becomes too full.
  56. ```php
  57. use GuzzleHttp\Psr7;
  58. // Create an empty stream
  59. $stream = Psr7\Utils::streamFor();
  60. // Start dropping data when the stream has more than 10 bytes
  61. $dropping = new Psr7\DroppingStream($stream, 10);
  62. $dropping->write('01234567890123456789');
  63. echo $stream; // 0123456789
  64. ```
  65. ## FnStream
  66. `GuzzleHttp\Psr7\FnStream`
  67. Compose stream implementations based on a hash of functions.
  68. Allows for easy testing and extension of a provided stream without needing
  69. to create a concrete class for a simple extension point.
  70. ```php
  71. use GuzzleHttp\Psr7;
  72. $stream = Psr7\Utils::streamFor('hi');
  73. $fnStream = Psr7\FnStream::decorate($stream, [
  74. 'rewind' => function () use ($stream) {
  75. echo 'About to rewind - ';
  76. $stream->rewind();
  77. echo 'rewound!';
  78. }
  79. ]);
  80. $fnStream->rewind();
  81. // Outputs: About to rewind - rewound!
  82. ```
  83. ## InflateStream
  84. `GuzzleHttp\Psr7\InflateStream`
  85. Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content.
  86. This stream decorator converts the provided stream to a PHP stream resource,
  87. then appends the zlib.inflate filter. The stream is then converted back
  88. to a Guzzle stream resource to be used as a Guzzle stream.
  89. ## LazyOpenStream
  90. `GuzzleHttp\Psr7\LazyOpenStream`
  91. Lazily reads or writes to a file that is opened only after an IO operation
  92. take place on the stream.
  93. ```php
  94. use GuzzleHttp\Psr7;
  95. $stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
  96. // The file has not yet been opened...
  97. echo $stream->read(10);
  98. // The file is opened and read from only when needed.
  99. ```
  100. ## LimitStream
  101. `GuzzleHttp\Psr7\LimitStream`
  102. LimitStream can be used to read a subset or slice of an existing stream object.
  103. This can be useful for breaking a large file into smaller pieces to be sent in
  104. chunks (e.g. Amazon S3's multipart upload API).
  105. ```php
  106. use GuzzleHttp\Psr7;
  107. $original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
  108. echo $original->getSize();
  109. // >>> 1048576
  110. // Limit the size of the body to 1024 bytes and start reading from byte 2048
  111. $stream = new Psr7\LimitStream($original, 1024, 2048);
  112. echo $stream->getSize();
  113. // >>> 1024
  114. echo $stream->tell();
  115. // >>> 0
  116. ```
  117. ## MultipartStream
  118. `GuzzleHttp\Psr7\MultipartStream`
  119. Stream that when read returns bytes for a streaming multipart or
  120. multipart/form-data stream.
  121. ## NoSeekStream
  122. `GuzzleHttp\Psr7\NoSeekStream`
  123. NoSeekStream wraps a stream and does not allow seeking.
  124. ```php
  125. use GuzzleHttp\Psr7;
  126. $original = Psr7\Utils::streamFor('foo');
  127. $noSeek = new Psr7\NoSeekStream($original);
  128. echo $noSeek->read(3);
  129. // foo
  130. var_export($noSeek->isSeekable());
  131. // false
  132. $noSeek->seek(0);
  133. var_export($noSeek->read(3));
  134. // NULL
  135. ```
  136. ## PumpStream
  137. `GuzzleHttp\Psr7\PumpStream`
  138. Provides a read only stream that pumps data from a PHP callable.
  139. When invoking the provided callable, the PumpStream will pass the amount of
  140. data requested to read to the callable. The callable can choose to ignore
  141. this value and return fewer or more bytes than requested. Any extra data
  142. returned by the provided callable is buffered internally until drained using
  143. the read() function of the PumpStream. The provided callable MUST return
  144. false when there is no more data to read.
  145. ## Implementing stream decorators
  146. Creating a stream decorator is very easy thanks to the
  147. `GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that
  148. implement `Psr\Http\Message\StreamInterface` by proxying to an underlying
  149. stream. Just `use` the `StreamDecoratorTrait` and implement your custom
  150. methods.
  151. For example, let's say we wanted to call a specific function each time the last
  152. byte is read from a stream. This could be implemented by overriding the
  153. `read()` method.
  154. ```php
  155. use Psr\Http\Message\StreamInterface;
  156. use GuzzleHttp\Psr7\StreamDecoratorTrait;
  157. class EofCallbackStream implements StreamInterface
  158. {
  159. use StreamDecoratorTrait;
  160. private $callback;
  161. public function __construct(StreamInterface $stream, callable $cb)
  162. {
  163. $this->stream = $stream;
  164. $this->callback = $cb;
  165. }
  166. public function read($length)
  167. {
  168. $result = $this->stream->read($length);
  169. // Invoke the callback when EOF is hit.
  170. if ($this->eof()) {
  171. call_user_func($this->callback);
  172. }
  173. return $result;
  174. }
  175. }
  176. ```
  177. This decorator could be added to any existing stream and used like so:
  178. ```php
  179. use GuzzleHttp\Psr7;
  180. $original = Psr7\Utils::streamFor('foo');
  181. $eofStream = new EofCallbackStream($original, function () {
  182. echo 'EOF!';
  183. });
  184. $eofStream->read(2);
  185. $eofStream->read(1);
  186. // echoes "EOF!"
  187. $eofStream->seek(0);
  188. $eofStream->read(3);
  189. // echoes "EOF!"
  190. ```
  191. ## PHP StreamWrapper
  192. You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a
  193. PSR-7 stream as a PHP stream resource.
  194. Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP
  195. stream from a PSR-7 stream.
  196. ```php
  197. use GuzzleHttp\Psr7\StreamWrapper;
  198. $stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
  199. $resource = StreamWrapper::getResource($stream);
  200. echo fread($resource, 6); // outputs hello!
  201. ```
  202. # Static API
  203. There are various static methods available under the `GuzzleHttp\Psr7` namespace.
  204. ## `GuzzleHttp\Psr7\Message::toString`
  205. `public static function toString(MessageInterface $message): string`
  206. Returns the string representation of an HTTP message.
  207. ```php
  208. $request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
  209. echo GuzzleHttp\Psr7\Message::toString($request);
  210. ```
  211. ## `GuzzleHttp\Psr7\Message::bodySummary`
  212. `public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null`
  213. Get a short summary of the message body.
  214. Will return `null` if the response is not printable.
  215. ## `GuzzleHttp\Psr7\Message::rewindBody`
  216. `public static function rewindBody(MessageInterface $message): void`
  217. Attempts to rewind a message body and throws an exception on failure.
  218. The body of the message will only be rewound if a call to `tell()`
  219. returns a value other than `0`.
  220. ## `GuzzleHttp\Psr7\Message::parseMessage`
  221. `public static function parseMessage(string $message): array`
  222. Parses an HTTP message into an associative array.
  223. The array contains the "start-line" key containing the start line of
  224. the message, "headers" key containing an associative array of header
  225. array values, and a "body" key containing the body of the message.
  226. ## `GuzzleHttp\Psr7\Message::parseRequestUri`
  227. `public static function parseRequestUri(string $path, array $headers): string`
  228. Constructs a URI for an HTTP request message.
  229. ## `GuzzleHttp\Psr7\Message::parseRequest`
  230. `public static function parseRequest(string $message): Request`
  231. Parses a request message string into a request object.
  232. ## `GuzzleHttp\Psr7\Message::parseResponse`
  233. `public static function parseResponse(string $message): Response`
  234. Parses a response message string into a response object.
  235. ## `GuzzleHttp\Psr7\Header::parse`
  236. `public static function parse(string|array $header): array`
  237. Parse an array of header values containing ";" separated data into an
  238. array of associative arrays representing the header key value pair data
  239. of the header. When a parameter does not contain a value, but just
  240. contains a key, this function will inject a key with a '' string value.
  241. ## `GuzzleHttp\Psr7\Header::normalize`
  242. `public static function normalize(string|array $header): array`
  243. Converts an array of header values that may contain comma separated
  244. headers into an array of headers with no comma separated values.
  245. ## `GuzzleHttp\Psr7\Query::parse`
  246. `public static function parse(string $str, int|bool $urlEncoding = true): array`
  247. Parse a query string into an associative array.
  248. If multiple values are found for the same key, the value of that key
  249. value pair will become an array. This function does not parse nested
  250. PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
  251. will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
  252. ## `GuzzleHttp\Psr7\Query::build`
  253. `public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string`
  254. Build a query string from an array of key value pairs.
  255. This function can use the return value of `parse()` to build a query
  256. string. This function does not modify the provided keys when an array is
  257. encountered (like `http_build_query()` would).
  258. ## `GuzzleHttp\Psr7\Utils::caselessRemove`
  259. `public static function caselessRemove(iterable<string> $keys, $keys, array $data): array`
  260. Remove the items given by the keys, case insensitively from the data.
  261. ## `GuzzleHttp\Psr7\Utils::copyToStream`
  262. `public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void`
  263. Copy the contents of a stream into another stream until the given number
  264. of bytes have been read.
  265. ## `GuzzleHttp\Psr7\Utils::copyToString`
  266. `public static function copyToString(StreamInterface $stream, int $maxLen = -1): string`
  267. Copy the contents of a stream into a string until the given number of
  268. bytes have been read.
  269. ## `GuzzleHttp\Psr7\Utils::hash`
  270. `public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string`
  271. Calculate a hash of a stream.
  272. This method reads the entire stream to calculate a rolling hash, based on
  273. PHP's `hash_init` functions.
  274. ## `GuzzleHttp\Psr7\Utils::modifyRequest`
  275. `public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface`
  276. Clone and modify a request with the given changes.
  277. This method is useful for reducing the number of clones needed to mutate
  278. a message.
  279. - method: (string) Changes the HTTP method.
  280. - set_headers: (array) Sets the given headers.
  281. - remove_headers: (array) Remove the given headers.
  282. - body: (mixed) Sets the given body.
  283. - uri: (UriInterface) Set the URI.
  284. - query: (string) Set the query string value of the URI.
  285. - version: (string) Set the protocol version.
  286. ## `GuzzleHttp\Psr7\Utils::readLine`
  287. `public static function readLine(StreamInterface $stream, int $maxLength = null): string`
  288. Read a line from the stream up to the maximum allowed buffer length.
  289. ## `GuzzleHttp\Psr7\Utils::streamFor`
  290. `public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
  291. Create a new stream based on the input type.
  292. Options is an associative array that can contain the following keys:
  293. - metadata: Array of custom metadata.
  294. - size: Size of the stream.
  295. This method accepts the following `$resource` types:
  296. - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
  297. - `string`: Creates a stream object that uses the given string as the contents.
  298. - `resource`: Creates a stream object that wraps the given PHP stream resource.
  299. - `Iterator`: If the provided value implements `Iterator`, then a read-only
  300. stream object will be created that wraps the given iterable. Each time the
  301. stream is read from, data from the iterator will fill a buffer and will be
  302. continuously called until the buffer is equal to the requested read size.
  303. Subsequent read calls will first read from the buffer and then call `next`
  304. on the underlying iterator until it is exhausted.
  305. - `object` with `__toString()`: If the object has the `__toString()` method,
  306. the object will be cast to a string and then a stream will be returned that
  307. uses the string value.
  308. - `NULL`: When `null` is passed, an empty stream object is returned.
  309. - `callable` When a callable is passed, a read-only stream object will be
  310. created that invokes the given callable. The callable is invoked with the
  311. number of suggested bytes to read. The callable can return any number of
  312. bytes, but MUST return `false` when there is no more data to return. The
  313. stream object that wraps the callable will invoke the callable until the
  314. number of requested bytes are available. Any additional bytes will be
  315. buffered and used in subsequent reads.
  316. ```php
  317. $stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
  318. $stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));
  319. $generator = function ($bytes) {
  320. for ($i = 0; $i < $bytes; $i++) {
  321. yield ' ';
  322. }
  323. }
  324. $stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));
  325. ```
  326. ## `GuzzleHttp\Psr7\Utils::tryFopen`
  327. `public static function tryFopen(string $filename, string $mode): resource`
  328. Safely opens a PHP stream resource using a filename.
  329. When fopen fails, PHP normally raises a warning. This function adds an
  330. error handler that checks for errors and throws an exception instead.
  331. ## `GuzzleHttp\Psr7\Utils::uriFor`
  332. `public static function uriFor(string|UriInterface $uri): UriInterface`
  333. Returns a UriInterface for the given value.
  334. This function accepts a string or UriInterface and returns a
  335. UriInterface for the given value. If the value is already a
  336. UriInterface, it is returned as-is.
  337. ## `GuzzleHttp\Psr7\MimeType::fromFilename`
  338. `public static function fromFilename(string $filename): string|null`
  339. Determines the mimetype of a file by looking at its extension.
  340. ## `GuzzleHttp\Psr7\MimeType::fromExtension`
  341. `public static function fromExtension(string $extension): string|null`
  342. Maps a file extensions to a mimetype.
  343. ## Upgrading from Function API
  344. The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API was removed in 2.0.0. A migration table has been provided here for your convenience:
  345. | Original Function | Replacement Method |
  346. |----------------|----------------|
  347. | `str` | `Message::toString` |
  348. | `uri_for` | `Utils::uriFor` |
  349. | `stream_for` | `Utils::streamFor` |
  350. | `parse_header` | `Header::parse` |
  351. | `normalize_header` | `Header::normalize` |
  352. | `modify_request` | `Utils::modifyRequest` |
  353. | `rewind_body` | `Message::rewindBody` |
  354. | `try_fopen` | `Utils::tryFopen` |
  355. | `copy_to_string` | `Utils::copyToString` |
  356. | `copy_to_stream` | `Utils::copyToStream` |
  357. | `hash` | `Utils::hash` |
  358. | `readline` | `Utils::readLine` |
  359. | `parse_request` | `Message::parseRequest` |
  360. | `parse_response` | `Message::parseResponse` |
  361. | `parse_query` | `Query::parse` |
  362. | `build_query` | `Query::build` |
  363. | `mimetype_from_filename` | `MimeType::fromFilename` |
  364. | `mimetype_from_extension` | `MimeType::fromExtension` |
  365. | `_parse_message` | `Message::parseMessage` |
  366. | `_parse_request_uri` | `Message::parseRequestUri` |
  367. | `get_message_body_summary` | `Message::bodySummary` |
  368. | `_caseless_remove` | `Utils::caselessRemove` |
  369. # Additional URI Methods
  370. Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class,
  371. this library also provides additional functionality when working with URIs as static methods.
  372. ## URI Types
  373. An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference.
  374. An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI,
  375. the base URI. Relative references can be divided into several forms according to
  376. [RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2):
  377. - network-path references, e.g. `//example.com/path`
  378. - absolute-path references, e.g. `/path`
  379. - relative-path references, e.g. `subpath`
  380. The following methods can be used to identify the type of the URI.
  381. ### `GuzzleHttp\Psr7\Uri::isAbsolute`
  382. `public static function isAbsolute(UriInterface $uri): bool`
  383. Whether the URI is absolute, i.e. it has a scheme.
  384. ### `GuzzleHttp\Psr7\Uri::isNetworkPathReference`
  385. `public static function isNetworkPathReference(UriInterface $uri): bool`
  386. Whether the URI is a network-path reference. A relative reference that begins with two slash characters is
  387. termed an network-path reference.
  388. ### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference`
  389. `public static function isAbsolutePathReference(UriInterface $uri): bool`
  390. Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is
  391. termed an absolute-path reference.
  392. ### `GuzzleHttp\Psr7\Uri::isRelativePathReference`
  393. `public static function isRelativePathReference(UriInterface $uri): bool`
  394. Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is
  395. termed a relative-path reference.
  396. ### `GuzzleHttp\Psr7\Uri::isSameDocumentReference`
  397. `public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool`
  398. Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its
  399. fragment component, identical to the base URI. When no base URI is given, only an empty URI reference
  400. (apart from its fragment) is considered a same-document reference.
  401. ## URI Components
  402. Additional methods to work with URI components.
  403. ### `GuzzleHttp\Psr7\Uri::isDefaultPort`
  404. `public static function isDefaultPort(UriInterface $uri): bool`
  405. Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null
  406. or the standard port. This method can be used independently of the implementation.
  407. ### `GuzzleHttp\Psr7\Uri::composeComponents`
  408. `public static function composeComponents($scheme, $authority, $path, $query, $fragment): string`
  409. Composes a URI reference string from its various components according to
  410. [RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called
  411. manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
  412. ### `GuzzleHttp\Psr7\Uri::fromParts`
  413. `public static function fromParts(array $parts): UriInterface`
  414. Creates a URI from a hash of [`parse_url`](http://php.net/manual/en/function.parse-url.php) components.
  415. ### `GuzzleHttp\Psr7\Uri::withQueryValue`
  416. `public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface`
  417. Creates a new URI with a specific query string value. Any existing query string values that exactly match the
  418. provided key are removed and replaced with the given key value pair. A value of null will set the query string
  419. key without a value, e.g. "key" instead of "key=value".
  420. ### `GuzzleHttp\Psr7\Uri::withQueryValues`
  421. `public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface`
  422. Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an
  423. associative array of key => value.
  424. ### `GuzzleHttp\Psr7\Uri::withoutQueryValue`
  425. `public static function withoutQueryValue(UriInterface $uri, $key): UriInterface`
  426. Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the
  427. provided key are removed.
  428. ## Reference Resolution
  429. `GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according
  430. to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers
  431. do when resolving a link in a website based on the current request URI.
  432. ### `GuzzleHttp\Psr7\UriResolver::resolve`
  433. `public static function resolve(UriInterface $base, UriInterface $rel): UriInterface`
  434. Converts the relative URI into a new URI that is resolved against the base URI.
  435. ### `GuzzleHttp\Psr7\UriResolver::removeDotSegments`
  436. `public static function removeDotSegments(string $path): string`
  437. Removes dot segments from a path and returns the new path according to
  438. [RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4).
  439. ### `GuzzleHttp\Psr7\UriResolver::relativize`
  440. `public static function relativize(UriInterface $base, UriInterface $target): UriInterface`
  441. Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():
  442. ```php
  443. (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
  444. ```
  445. One use-case is to use the current request URI as base URI and then generate relative links in your documents
  446. to reduce the document size or offer self-contained downloadable document archives.
  447. ```php
  448. $base = new Uri('http://example.com/a/b/');
  449. echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
  450. echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
  451. echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
  452. echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
  453. ```
  454. ## Normalization and Comparison
  455. `GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to
  456. [RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6).
  457. ### `GuzzleHttp\Psr7\UriNormalizer::normalize`
  458. `public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface`
  459. Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
  460. This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask
  461. of normalizations to apply. The following normalizations are available:
  462. - `UriNormalizer::PRESERVING_NORMALIZATIONS`
  463. Default normalizations which only include the ones that preserve semantics.
  464. - `UriNormalizer::CAPITALIZE_PERCENT_ENCODING`
  465. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
  466. Example: `http://example.org/a%c2%b1b``http://example.org/a%C2%B1b`
  467. - `UriNormalizer::DECODE_UNRESERVED_CHARACTERS`
  468. Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of
  469. ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should
  470. not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved
  471. characters by URI normalizers.
  472. Example: `http://example.org/%7Eusern%61me/``http://example.org/~username/`
  473. - `UriNormalizer::CONVERT_EMPTY_PATH`
  474. Converts the empty path to "/" for http and https URIs.
  475. Example: `http://example.org``http://example.org/`
  476. - `UriNormalizer::REMOVE_DEFAULT_HOST`
  477. Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host
  478. "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to
  479. RFC 3986.
  480. Example: `file://localhost/myfile``file:///myfile`
  481. - `UriNormalizer::REMOVE_DEFAULT_PORT`
  482. Removes the default port of the given URI scheme from the URI.
  483. Example: `http://example.org:80/``http://example.org/`
  484. - `UriNormalizer::REMOVE_DOT_SEGMENTS`
  485. Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would
  486. change the semantics of the URI reference.
  487. Example: `http://example.org/../a/b/../c/./d.html``http://example.org/a/c/d.html`
  488. - `UriNormalizer::REMOVE_DUPLICATE_SLASHES`
  489. Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes
  490. and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization
  491. may change the semantics. Encoded slashes (%2F) are not removed.
  492. Example: `http://example.org//foo///bar.html``http://example.org/foo/bar.html`
  493. - `UriNormalizer::SORT_QUERY_PARAMETERS`
  494. Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be
  495. significant (this is not defined by the standard). So this normalization is not safe and may change the semantics
  496. of the URI.
  497. Example: `?lang=en&article=fred``?article=fred&lang=en`
  498. ### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent`
  499. `public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool`
  500. Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given
  501. `$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent.
  502. This of course assumes they will be resolved against the same base URI. If this is not the case, determination of
  503. equivalence or difference of relative references does not mean anything.