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.

872 lines
28 KiB

2 years ago
  1. # PSR-7 Message Implementation
  2. This repository contains a full [PSR-7](https://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::splitList`
  242. `public static function splitList(string|string[] $header): string[]`
  243. Splits a HTTP header defined to contain a comma-separated list into
  244. each individual value:
  245. ```
  246. $knownEtags = Header::splitList($request->getHeader('if-none-match'));
  247. ```
  248. Example headers include `accept`, `cache-control` and `if-none-match`.
  249. ## `GuzzleHttp\Psr7\Header::normalize` (deprecated)
  250. `public static function normalize(string|array $header): array`
  251. `Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist)
  252. which performs the same operation with a cleaned up API and improved
  253. documentation.
  254. Converts an array of header values that may contain comma separated
  255. headers into an array of headers with no comma separated values.
  256. ## `GuzzleHttp\Psr7\Query::parse`
  257. `public static function parse(string $str, int|bool $urlEncoding = true): array`
  258. Parse a query string into an associative array.
  259. If multiple values are found for the same key, the value of that key
  260. value pair will become an array. This function does not parse nested
  261. PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
  262. will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
  263. ## `GuzzleHttp\Psr7\Query::build`
  264. `public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string`
  265. Build a query string from an array of key value pairs.
  266. This function can use the return value of `parse()` to build a query
  267. string. This function does not modify the provided keys when an array is
  268. encountered (like `http_build_query()` would).
  269. ## `GuzzleHttp\Psr7\Utils::caselessRemove`
  270. `public static function caselessRemove(iterable<string> $keys, $keys, array $data): array`
  271. Remove the items given by the keys, case insensitively from the data.
  272. ## `GuzzleHttp\Psr7\Utils::copyToStream`
  273. `public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void`
  274. Copy the contents of a stream into another stream until the given number
  275. of bytes have been read.
  276. ## `GuzzleHttp\Psr7\Utils::copyToString`
  277. `public static function copyToString(StreamInterface $stream, int $maxLen = -1): string`
  278. Copy the contents of a stream into a string until the given number of
  279. bytes have been read.
  280. ## `GuzzleHttp\Psr7\Utils::hash`
  281. `public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string`
  282. Calculate a hash of a stream.
  283. This method reads the entire stream to calculate a rolling hash, based on
  284. PHP's `hash_init` functions.
  285. ## `GuzzleHttp\Psr7\Utils::modifyRequest`
  286. `public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface`
  287. Clone and modify a request with the given changes.
  288. This method is useful for reducing the number of clones needed to mutate
  289. a message.
  290. - method: (string) Changes the HTTP method.
  291. - set_headers: (array) Sets the given headers.
  292. - remove_headers: (array) Remove the given headers.
  293. - body: (mixed) Sets the given body.
  294. - uri: (UriInterface) Set the URI.
  295. - query: (string) Set the query string value of the URI.
  296. - version: (string) Set the protocol version.
  297. ## `GuzzleHttp\Psr7\Utils::readLine`
  298. `public static function readLine(StreamInterface $stream, int $maxLength = null): string`
  299. Read a line from the stream up to the maximum allowed buffer length.
  300. ## `GuzzleHttp\Psr7\Utils::streamFor`
  301. `public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
  302. Create a new stream based on the input type.
  303. Options is an associative array that can contain the following keys:
  304. - metadata: Array of custom metadata.
  305. - size: Size of the stream.
  306. This method accepts the following `$resource` types:
  307. - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
  308. - `string`: Creates a stream object that uses the given string as the contents.
  309. - `resource`: Creates a stream object that wraps the given PHP stream resource.
  310. - `Iterator`: If the provided value implements `Iterator`, then a read-only
  311. stream object will be created that wraps the given iterable. Each time the
  312. stream is read from, data from the iterator will fill a buffer and will be
  313. continuously called until the buffer is equal to the requested read size.
  314. Subsequent read calls will first read from the buffer and then call `next`
  315. on the underlying iterator until it is exhausted.
  316. - `object` with `__toString()`: If the object has the `__toString()` method,
  317. the object will be cast to a string and then a stream will be returned that
  318. uses the string value.
  319. - `NULL`: When `null` is passed, an empty stream object is returned.
  320. - `callable` When a callable is passed, a read-only stream object will be
  321. created that invokes the given callable. The callable is invoked with the
  322. number of suggested bytes to read. The callable can return any number of
  323. bytes, but MUST return `false` when there is no more data to return. The
  324. stream object that wraps the callable will invoke the callable until the
  325. number of requested bytes are available. Any additional bytes will be
  326. buffered and used in subsequent reads.
  327. ```php
  328. $stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
  329. $stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));
  330. $generator = function ($bytes) {
  331. for ($i = 0; $i < $bytes; $i++) {
  332. yield ' ';
  333. }
  334. }
  335. $stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));
  336. ```
  337. ## `GuzzleHttp\Psr7\Utils::tryFopen`
  338. `public static function tryFopen(string $filename, string $mode): resource`
  339. Safely opens a PHP stream resource using a filename.
  340. When fopen fails, PHP normally raises a warning. This function adds an
  341. error handler that checks for errors and throws an exception instead.
  342. ## `GuzzleHttp\Psr7\Utils::tryGetContents`
  343. `public static function tryGetContents(resource $stream): string`
  344. Safely gets the contents of a given stream.
  345. When stream_get_contents fails, PHP normally raises a warning. This
  346. function adds an error handler that checks for errors and throws an
  347. exception instead.
  348. ## `GuzzleHttp\Psr7\Utils::uriFor`
  349. `public static function uriFor(string|UriInterface $uri): UriInterface`
  350. Returns a UriInterface for the given value.
  351. This function accepts a string or UriInterface and returns a
  352. UriInterface for the given value. If the value is already a
  353. UriInterface, it is returned as-is.
  354. ## `GuzzleHttp\Psr7\MimeType::fromFilename`
  355. `public static function fromFilename(string $filename): string|null`
  356. Determines the mimetype of a file by looking at its extension.
  357. ## `GuzzleHttp\Psr7\MimeType::fromExtension`
  358. `public static function fromExtension(string $extension): string|null`
  359. Maps a file extensions to a mimetype.
  360. ## Upgrading from Function API
  361. 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:
  362. | Original Function | Replacement Method |
  363. |----------------|----------------|
  364. | `str` | `Message::toString` |
  365. | `uri_for` | `Utils::uriFor` |
  366. | `stream_for` | `Utils::streamFor` |
  367. | `parse_header` | `Header::parse` |
  368. | `normalize_header` | `Header::normalize` |
  369. | `modify_request` | `Utils::modifyRequest` |
  370. | `rewind_body` | `Message::rewindBody` |
  371. | `try_fopen` | `Utils::tryFopen` |
  372. | `copy_to_string` | `Utils::copyToString` |
  373. | `copy_to_stream` | `Utils::copyToStream` |
  374. | `hash` | `Utils::hash` |
  375. | `readline` | `Utils::readLine` |
  376. | `parse_request` | `Message::parseRequest` |
  377. | `parse_response` | `Message::parseResponse` |
  378. | `parse_query` | `Query::parse` |
  379. | `build_query` | `Query::build` |
  380. | `mimetype_from_filename` | `MimeType::fromFilename` |
  381. | `mimetype_from_extension` | `MimeType::fromExtension` |
  382. | `_parse_message` | `Message::parseMessage` |
  383. | `_parse_request_uri` | `Message::parseRequestUri` |
  384. | `get_message_body_summary` | `Message::bodySummary` |
  385. | `_caseless_remove` | `Utils::caselessRemove` |
  386. # Additional URI Methods
  387. Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class,
  388. this library also provides additional functionality when working with URIs as static methods.
  389. ## URI Types
  390. An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference.
  391. An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI,
  392. the base URI. Relative references can be divided into several forms according to
  393. [RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2):
  394. - network-path references, e.g. `//example.com/path`
  395. - absolute-path references, e.g. `/path`
  396. - relative-path references, e.g. `subpath`
  397. The following methods can be used to identify the type of the URI.
  398. ### `GuzzleHttp\Psr7\Uri::isAbsolute`
  399. `public static function isAbsolute(UriInterface $uri): bool`
  400. Whether the URI is absolute, i.e. it has a scheme.
  401. ### `GuzzleHttp\Psr7\Uri::isNetworkPathReference`
  402. `public static function isNetworkPathReference(UriInterface $uri): bool`
  403. Whether the URI is a network-path reference. A relative reference that begins with two slash characters is
  404. termed an network-path reference.
  405. ### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference`
  406. `public static function isAbsolutePathReference(UriInterface $uri): bool`
  407. Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is
  408. termed an absolute-path reference.
  409. ### `GuzzleHttp\Psr7\Uri::isRelativePathReference`
  410. `public static function isRelativePathReference(UriInterface $uri): bool`
  411. Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is
  412. termed a relative-path reference.
  413. ### `GuzzleHttp\Psr7\Uri::isSameDocumentReference`
  414. `public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool`
  415. Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its
  416. fragment component, identical to the base URI. When no base URI is given, only an empty URI reference
  417. (apart from its fragment) is considered a same-document reference.
  418. ## URI Components
  419. Additional methods to work with URI components.
  420. ### `GuzzleHttp\Psr7\Uri::isDefaultPort`
  421. `public static function isDefaultPort(UriInterface $uri): bool`
  422. Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null
  423. or the standard port. This method can be used independently of the implementation.
  424. ### `GuzzleHttp\Psr7\Uri::composeComponents`
  425. `public static function composeComponents($scheme, $authority, $path, $query, $fragment): string`
  426. Composes a URI reference string from its various components according to
  427. [RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called
  428. manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
  429. ### `GuzzleHttp\Psr7\Uri::fromParts`
  430. `public static function fromParts(array $parts): UriInterface`
  431. Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components.
  432. ### `GuzzleHttp\Psr7\Uri::withQueryValue`
  433. `public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface`
  434. Creates a new URI with a specific query string value. Any existing query string values that exactly match the
  435. provided key are removed and replaced with the given key value pair. A value of null will set the query string
  436. key without a value, e.g. "key" instead of "key=value".
  437. ### `GuzzleHttp\Psr7\Uri::withQueryValues`
  438. `public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface`
  439. Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an
  440. associative array of key => value.
  441. ### `GuzzleHttp\Psr7\Uri::withoutQueryValue`
  442. `public static function withoutQueryValue(UriInterface $uri, $key): UriInterface`
  443. Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the
  444. provided key are removed.
  445. ## Cross-Origin Detection
  446. `GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin.
  447. ### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin`
  448. `public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool`
  449. Determines if a modified URL should be considered cross-origin with respect to an original URL.
  450. ## Reference Resolution
  451. `GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according
  452. to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers
  453. do when resolving a link in a website based on the current request URI.
  454. ### `GuzzleHttp\Psr7\UriResolver::resolve`
  455. `public static function resolve(UriInterface $base, UriInterface $rel): UriInterface`
  456. Converts the relative URI into a new URI that is resolved against the base URI.
  457. ### `GuzzleHttp\Psr7\UriResolver::removeDotSegments`
  458. `public static function removeDotSegments(string $path): string`
  459. Removes dot segments from a path and returns the new path according to
  460. [RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4).
  461. ### `GuzzleHttp\Psr7\UriResolver::relativize`
  462. `public static function relativize(UriInterface $base, UriInterface $target): UriInterface`
  463. Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():
  464. ```php
  465. (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
  466. ```
  467. One use-case is to use the current request URI as base URI and then generate relative links in your documents
  468. to reduce the document size or offer self-contained downloadable document archives.
  469. ```php
  470. $base = new Uri('http://example.com/a/b/');
  471. echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
  472. echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
  473. echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
  474. echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
  475. ```
  476. ## Normalization and Comparison
  477. `GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to
  478. [RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6).
  479. ### `GuzzleHttp\Psr7\UriNormalizer::normalize`
  480. `public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface`
  481. Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
  482. This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask
  483. of normalizations to apply. The following normalizations are available:
  484. - `UriNormalizer::PRESERVING_NORMALIZATIONS`
  485. Default normalizations which only include the ones that preserve semantics.
  486. - `UriNormalizer::CAPITALIZE_PERCENT_ENCODING`
  487. All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
  488. Example: `http://example.org/a%c2%b1b``http://example.org/a%C2%B1b`
  489. - `UriNormalizer::DECODE_UNRESERVED_CHARACTERS`
  490. Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of
  491. ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should
  492. not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved
  493. characters by URI normalizers.
  494. Example: `http://example.org/%7Eusern%61me/``http://example.org/~username/`
  495. - `UriNormalizer::CONVERT_EMPTY_PATH`
  496. Converts the empty path to "/" for http and https URIs.
  497. Example: `http://example.org``http://example.org/`
  498. - `UriNormalizer::REMOVE_DEFAULT_HOST`
  499. Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host
  500. "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to
  501. RFC 3986.
  502. Example: `file://localhost/myfile``file:///myfile`
  503. - `UriNormalizer::REMOVE_DEFAULT_PORT`
  504. Removes the default port of the given URI scheme from the URI.
  505. Example: `http://example.org:80/``http://example.org/`
  506. - `UriNormalizer::REMOVE_DOT_SEGMENTS`
  507. Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would
  508. change the semantics of the URI reference.
  509. Example: `http://example.org/../a/b/../c/./d.html``http://example.org/a/c/d.html`
  510. - `UriNormalizer::REMOVE_DUPLICATE_SLASHES`
  511. Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes
  512. and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization
  513. may change the semantics. Encoded slashes (%2F) are not removed.
  514. Example: `http://example.org//foo///bar.html``http://example.org/foo/bar.html`
  515. - `UriNormalizer::SORT_QUERY_PARAMETERS`
  516. Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be
  517. significant (this is not defined by the standard). So this normalization is not safe and may change the semantics
  518. of the URI.
  519. Example: `?lang=en&article=fred``?article=fred&lang=en`
  520. ### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent`
  521. `public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool`
  522. Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given
  523. `$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent.
  524. This of course assumes they will be resolved against the same base URI. If this is not the case, determination of
  525. equivalence or difference of relative references does not mean anything.
  526. ## Version Guidance
  527. | Version | Status | PHP Version |
  528. |---------|----------------|------------------|
  529. | 1.x | Security fixes | >=5.4,<8.1 |
  530. | 2.x | Latest | ^7.2.5 \|\| ^8.0 |
  531. ## Security
  532. If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information.
  533. ## License
  534. Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
  535. ## For Enterprise
  536. Available as part of the Tidelift Subscription
  537. The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)