Debian Codegraph @

vendor/guzzlehttp/psr7/README.md

raw
1 # PSR-7 Message Implementation
2
3 This repository contains a full [PSR-7](https://www.php-fig.org/psr/psr-7/)
4 message implementation, several stream decorators, and some helpful
5 functionality like query string parsing.
6
7 ![CI](https://github.com/guzzle/psr7/workflows/CI/badge.svg)
8 ![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg)
9
10
11 ## Features
12
13 This package comes with a number of stream implementations and stream
14 decorators.
15
16
17 ## Installation
18
19 ```shell
20 composer require guzzlehttp/psr7
21 ```
22
23 ## Version Guidance
24
25 | Version | Status | PHP Version |
26 |---------|---------------------|--------------|
27 | 1.x | EOL (2024-06-30) | >=5.4,<8.2 |
28 | 2.x | Latest | >=7.2.5,<8.6 |
29
30 See [UPGRADING.md](UPGRADING.md) for notes on upgrading from 1.x to 2.0.
31
32
33 ## AppendStream
34
35 `GuzzleHttp\Psr7\AppendStream`
36
37 Reads from multiple streams, one after the other.
38
39 ```php
40 use GuzzleHttp\Psr7;
41
42 $a = Psr7\Utils::streamFor('abc, ');
43 $b = Psr7\Utils::streamFor('123.');
44 $composed = new Psr7\AppendStream([$a, $b]);
45
46 $composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));
47
48 echo $composed; // abc, 123. Above all listen to me.
49 ```
50
51
52 ## BufferStream
53
54 `GuzzleHttp\Psr7\BufferStream`
55
56 Provides a buffer stream that can be written to fill a buffer, and read
57 from to remove bytes from the buffer.
58
59 This stream returns a "hwm" metadata value that tells upstream consumers
60 what the configured high water mark of the stream is, or the maximum
61 preferred size of the buffer.
62
63 ```php
64 use GuzzleHttp\Psr7;
65
66 // When more than 1024 bytes are in the buffer, it will begin returning
67 // 0 to writes. This is an indication that writers should slow down.
68 $buffer = new Psr7\BufferStream(1024);
69 ```
70
71
72 ## CachingStream
73
74 The CachingStream is used to allow seeking over previously read bytes on
75 non-seekable streams. This can be useful when transferring a non-seekable
76 entity body fails due to needing to rewind the stream (for example, resulting
77 from a redirect). Data that is read from the remote stream will be buffered in
78 a PHP temp stream so that previously read bytes are cached first in memory,
79 then on disk.
80
81 ```php
82 use GuzzleHttp\Psr7;
83
84 $original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
85 $stream = new Psr7\CachingStream($original);
86
87 $stream->read(1024);
88 echo $stream->tell();
89 // 1024
90
91 $stream->seek(0);
92 echo $stream->tell();
93 // 0
94 ```
95
96
97 ## DroppingStream
98
99 `GuzzleHttp\Psr7\DroppingStream`
100
101 Stream decorator that begins dropping data once the size of the underlying
102 stream becomes too full.
103
104 ```php
105 use GuzzleHttp\Psr7;
106
107 // Create an empty stream
108 $stream = Psr7\Utils::streamFor();
109
110 // Start dropping data when the stream has more than 10 bytes
111 $dropping = new Psr7\DroppingStream($stream, 10);
112
113 $dropping->write('01234567890123456789');
114 echo $stream; // 0123456789
115 ```
116
117
118 ## FnStream
119
120 `GuzzleHttp\Psr7\FnStream`
121
122 Compose stream implementations based on a hash of callables.
123
124 Allows for easy testing and extension of a provided stream without needing
125 to create a concrete class for a simple extension point.
126
127 ```php
128
129 use GuzzleHttp\Psr7;
130
131 $stream = Psr7\Utils::streamFor('hi');
132 $fnStream = Psr7\FnStream::decorate($stream, [
133 'rewind' => function () use ($stream) {
134 echo 'About to rewind - ';
135 $stream->rewind();
136 echo 'rewound!';
137 }
138 ]);
139
140 $fnStream->rewind();
141 // Outputs: About to rewind - rewound!
142 ```
143
144
145 ## InflateStream
146
147 `GuzzleHttp\Psr7\InflateStream`
148
149 Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content.
150
151 This stream decorator converts the provided stream to a PHP stream resource,
152 then appends the zlib.inflate filter. The stream is then converted back
153 to a Guzzle stream resource to be used as a Guzzle stream.
154
155
156 ## LazyOpenStream
157
158 `GuzzleHttp\Psr7\LazyOpenStream`
159
160 Lazily reads or writes to a file that is opened only after an IO operation
161 take place on the stream.
162
163 ```php
164 use GuzzleHttp\Psr7;
165
166 $stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
167 // The file has not yet been opened...
168
169 echo $stream->read(10);
170 // The file is opened and read from only when needed.
171 ```
172
173
174 ## LimitStream
175
176 `GuzzleHttp\Psr7\LimitStream`
177
178 LimitStream can be used to read a subset or slice of an existing stream object.
179 This can be useful for breaking a large file into smaller pieces to be sent in
180 chunks (e.g. Amazon S3's multipart upload API).
181
182 ```php
183 use GuzzleHttp\Psr7;
184
185 $original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
186 echo $original->getSize();
187 // >>> 1048576
188
189 // Limit the size of the body to 1024 bytes and start reading from byte 2048
190 $stream = new Psr7\LimitStream($original, 1024, 2048);
191 echo $stream->getSize();
192 // >>> 1024
193 echo $stream->tell();
194 // >>> 0
195 ```
196
197
198 ## MultipartStream
199
200 `GuzzleHttp\Psr7\MultipartStream`
201
202 Stream that when read returns bytes for a streaming multipart or
203 multipart/form-data stream.
204
205 Each multipart element must contain a `name` and `contents` key. `contents` may
206 be any non-array value accepted by `GuzzleHttp\Psr7\Utils::streamFor()`,
207 including closures and invokable objects. Array contents are recursively
208 expanded into nested form fields.
209
210
211 ## NoSeekStream
212
213 `GuzzleHttp\Psr7\NoSeekStream`
214
215 NoSeekStream wraps a stream and does not allow seeking.
216
217 ```php
218 use GuzzleHttp\Psr7;
219
220 $original = Psr7\Utils::streamFor('foo');
221 $noSeek = new Psr7\NoSeekStream($original);
222
223 echo $noSeek->read(3);
224 // foo
225 var_export($noSeek->isSeekable());
226 // false
227 $noSeek->seek(0);
228 var_export($noSeek->read(3));
229 // NULL
230 ```
231
232
233 ## PumpStream
234
235 `GuzzleHttp\Psr7\PumpStream`
236
237 Provides a read only stream that pumps data from a PHP callable.
238
239 When invoking the provided callable, the PumpStream will pass the suggested
240 number of bytes to read to the callable. The callable can choose to ignore
241 this value and return fewer or more bytes than requested. Any extra data
242 returned by the provided callable is buffered internally until drained using
243 the read() function of the PumpStream. The provided callable MUST return
244 false or null when there is no more data to read.
245
246 Userland callables that declare no parameters are tolerated by PHP, but
247 length-aware callables remain the recommended formal shape.
248
249
250 ## Implementing stream decorators
251
252 Creating a stream decorator is very easy thanks to the
253 `GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that
254 implement `Psr\Http\Message\StreamInterface` by proxying to an underlying
255 stream. Just `use` the `StreamDecoratorTrait` and implement your custom
256 methods.
257
258 For example, let's say we wanted to call a specific function each time the last
259 byte is read from a stream. This could be implemented by overriding the
260 `read()` method.
261
262 ```php
263 use Psr\Http\Message\StreamInterface;
264 use GuzzleHttp\Psr7\StreamDecoratorTrait;
265
266 class EofCallbackStream implements StreamInterface
267 {
268 use StreamDecoratorTrait;
269
270 private $callback;
271
272 private $stream;
273
274 public function __construct(StreamInterface $stream, callable $cb)
275 {
276 $this->stream = $stream;
277 $this->callback = $cb;
278 }
279
280 public function read($length)
281 {
282 $result = $this->stream->read($length);
283
284 // Invoke the callback when EOF is hit.
285 if ($this->eof()) {
286 ($this->callback)();
287 }
288
289 return $result;
290 }
291 }
292 ```
293
294 This decorator could be added to any existing stream and used like so:
295
296 ```php
297 use GuzzleHttp\Psr7;
298
299 $original = Psr7\Utils::streamFor('foo');
300
301 $eofStream = new EofCallbackStream($original, function () {
302 echo 'EOF!';
303 });
304
305 $eofStream->read(2);
306 $eofStream->read(1);
307 // echoes "EOF!"
308 $eofStream->seek(0);
309 $eofStream->read(3);
310 // echoes "EOF!"
311 ```
312
313
314 ## PHP StreamWrapper
315
316 You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a
317 PSR-7 stream as a PHP stream resource.
318
319 Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP
320 stream from a PSR-7 stream.
321
322 ```php
323 use GuzzleHttp\Psr7\StreamWrapper;
324
325 $stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
326 $resource = StreamWrapper::getResource($stream);
327 echo fread($resource, 6); // outputs hello!
328 ```
329
330
331 # Static API
332
333 There are various static methods available under the `GuzzleHttp\Psr7` namespace.
334
335
336 ## `GuzzleHttp\Psr7\Message::toString`
337
338 `public static function toString(MessageInterface $message): string`
339
340 Returns the string representation of an HTTP message.
341
342 ```php
343 $request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
344 echo GuzzleHttp\Psr7\Message::toString($request);
345 ```
346
347
348 ## `GuzzleHttp\Psr7\Message::bodySummary`
349
350 `public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null`
351
352 Get a short summary of the message body.
353
354 Will return `null` if the response is not printable.
355
356
357 ## `GuzzleHttp\Psr7\Message::rewindBody`
358
359 `public static function rewindBody(MessageInterface $message): void`
360
361 Attempts to rewind a message body and throws an exception on failure.
362
363 The body of the message will only be rewound if a call to `tell()`
364 returns a value other than `0`.
365
366
367 ## `GuzzleHttp\Psr7\Message::parseMessage`
368
369 `public static function parseMessage(string $message): array`
370
371 Parses an HTTP message into an associative array.
372
373 The array contains the "start-line" key containing the start line of
374 the message, "headers" key containing an associative array of header
375 array values, and a "body" key containing the body of the message.
376
377
378 ## `GuzzleHttp\Psr7\Message::parseRequestUri`
379
380 `public static function parseRequestUri(string $path, array $headers): string`
381
382 Constructs a URI for an HTTP request message.
383
384
385 ## `GuzzleHttp\Psr7\Message::parseRequest`
386
387 `public static function parseRequest(string $message): Request`
388
389 Parses a request message string into a request object.
390
391
392 ## `GuzzleHttp\Psr7\Message::parseResponse`
393
394 `public static function parseResponse(string $message): Response`
395
396 Parses a response message string into a response object.
397
398
399 ## `GuzzleHttp\Psr7\Header::parse`
400
401 `public static function parse(string|array $header): array`
402
403 Parse an array of header values containing ";" separated data into an
404 array of associative arrays representing the header key value pair data
405 of the header. When a parameter does not contain a value, but just
406 contains a key, this function will inject a key with a '' string value.
407
408
409 ## `GuzzleHttp\Psr7\Header::splitList`
410
411 `public static function splitList(string|string[] $header): string[]`
412
413 Splits a HTTP header defined to contain a comma-separated list into
414 each individual value:
415
416 ```
417 $knownEtags = Header::splitList($request->getHeader('if-none-match'));
418 ```
419
420 Example headers include `accept`, `cache-control` and `if-none-match`.
421
422
423 ## `GuzzleHttp\Psr7\Header::normalize` (deprecated)
424
425 `public static function normalize(string|array $header): array`
426
427 `Header::normalize()` is deprecated in favor of [`Header::splitList()`](README.md#guzzlehttppsr7headersplitlist)
428 which performs the same operation with a cleaned up API and improved
429 documentation.
430
431 Converts an array of header values that may contain comma separated
432 headers into an array of headers with no comma separated values.
433
434
435 ## `GuzzleHttp\Psr7\Query::parse`
436
437 `public static function parse(string $str, int|bool $urlEncoding = true): array`
438
439 Parse a query string into an associative array.
440
441 If multiple values are found for the same key, the value of that key
442 value pair will become an array. This function does not parse nested
443 PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
444 will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
445
446
447 ## `GuzzleHttp\Psr7\Query::build`
448
449 `public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string`
450
451 Build a query string from an array of key value pairs.
452
453 This function can use the return value of `parse()` to build a query
454 string. This function does not modify the provided keys when an array is
455 encountered (like `http_build_query()` would).
456
457
458 ## `GuzzleHttp\Psr7\Utils::caselessRemove`
459
460 `public static function caselessRemove(iterable<string> $keys, $keys, array $data): array`
461
462 Remove the items given by the keys, case insensitively from the data.
463
464
465 ## `GuzzleHttp\Psr7\Utils::copyToStream`
466
467 `public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void`
468
469 Copy the contents of a stream into another stream until the given number
470 of bytes have been read.
471
472 The copy stops if the destination `write()` returns 0, for example a
473 `BufferStream` at its high water mark or a full `DroppingStream`. For a
474 guaranteed full copy, use a normal writable stream such as a file or
475 `php://temp` stream.
476
477
478 ## `GuzzleHttp\Psr7\Utils::copyToString`
479
480 `public static function copyToString(StreamInterface $stream, int $maxLen = -1): string`
481
482 Copy the contents of a stream into a string until the given number of
483 bytes have been read.
484
485
486 ## `GuzzleHttp\Psr7\Utils::hash`
487
488 `public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string`
489
490 Calculate a hash of a stream.
491
492 This method reads the entire stream to calculate a rolling hash, based on
493 PHP's `hash_init` functions.
494
495
496 ## `GuzzleHttp\Psr7\Utils::modifyRequest`
497
498 `public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface`
499
500 Clone and modify a request with the given changes.
501
502 This method is useful for reducing the number of clones needed to mutate
503 a message.
504
505 - method: (string) Changes the HTTP method.
506 - set_headers: (array) Sets the given headers.
507 - remove_headers: (array) Remove the given headers.
508 - body: (mixed) Sets the given body. Present non-null values are converted with
509 `GuzzleHttp\Psr7\Utils::streamFor()`, including scalar values, resources,
510 streams, iterators, callable arrays, closures, invokable objects, and
511 objects with `__toString()`. String inputs remain literal bodies.
512 - uri: (UriInterface) Set the URI.
513 - query: (string) Set the query string value of the URI.
514 - version: (string) Set the protocol version.
515
516
517 ## `GuzzleHttp\Psr7\Utils::readLine`
518
519 `public static function readLine(StreamInterface $stream, ?int $maxLength = null): string`
520
521 Read a line from the stream up to the maximum allowed buffer length.
522
523
524 ## `GuzzleHttp\Psr7\Utils::redactUserInfo`
525
526 `public static function redactUserInfo(UriInterface $uri): UriInterface`
527
528 Redact the password in the user info part of a URI.
529
530
531 ## `GuzzleHttp\Psr7\Utils::streamFor`
532
533 `public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
534
535 Create a new stream based on the input type.
536
537 Options is an associative array that can contain the following keys:
538
539 - metadata: Array of custom metadata.
540 - size: Size of the stream.
541
542 This method accepts the following `$resource` types:
543
544 - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
545 - `string`: Creates a stream object that uses the given string as the contents.
546 - `resource`: Creates a stream object that wraps the given PHP stream resource.
547 - `Iterator`: If the provided value implements `Iterator`, then a read-only
548 stream object will be created that wraps the given iterable. Each time the
549 stream is read from, data from the iterator will fill a buffer and will be
550 continuously called until the buffer is equal to the requested read size.
551 Subsequent read calls will first read from the buffer and then call `next`
552 on the underlying iterator until it is exhausted.
553 - `object` with `__toString()`: If the object has the `__toString()` method,
554 the object will be cast to a string and then a stream will be returned that
555 uses the string value.
556 - `NULL`: When `null` is passed, an empty stream object is returned.
557 - `callable`: When a callable array, closure, or invokable object is passed and
558 no earlier resource or object rule applies, a read-only stream object will be
559 created that invokes the given callable. The callable is invoked with the
560 suggested number of bytes to read. The callable can return fewer or more bytes
561 than requested, but MUST return `false` or `null` when there is no more data
562 to return. Any additional bytes will be buffered and used in subsequent reads.
563 String inputs are always treated as string bodies, even when they name
564 callable functions.
565
566 ```php
567 $stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
568 $stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));
569
570 $generator = function ($bytes) {
571 for ($i = 0; $i < $bytes; $i++) {
572 yield ' ';
573 }
574 }
575
576 $stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));
577 ```
578
579
580 ## `GuzzleHttp\Psr7\Utils::tryFopen`
581
582 `public static function tryFopen(string $filename, string $mode): resource`
583
584 Safely opens a PHP stream resource using a filename.
585
586 When fopen fails, PHP normally raises a warning. This function adds an
587 error handler that checks for errors and throws an exception instead.
588
589
590 ## `GuzzleHttp\Psr7\Utils::tryGetContents`
591
592 `public static function tryGetContents(resource $stream): string`
593
594 Safely gets the contents of a given stream.
595
596 When stream_get_contents fails, PHP normally raises a warning. This
597 function adds an error handler that checks for errors and throws an
598 exception instead.
599
600
601 ## `GuzzleHttp\Psr7\Utils::uriFor`
602
603 `public static function uriFor(string|UriInterface $uri): UriInterface`
604
605 Returns a UriInterface for the given value.
606
607 This function accepts a string or UriInterface and returns a
608 UriInterface for the given value. If the value is already a
609 UriInterface, it is returned as-is.
610
611
612 ## `GuzzleHttp\Psr7\MimeType::fromFilename`
613
614 `public static function fromFilename(string $filename): string|null`
615
616 Determines the mimetype of a file by looking at its extension.
617
618
619 ## `GuzzleHttp\Psr7\MimeType::fromExtension`
620
621 `public static function fromExtension(string $extension): string|null`
622
623 Maps a file extensions to a mimetype.
624
625
626 # Additional URI Methods
627
628 Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class,
629 this library also provides additional functionality when working with URIs as static methods.
630
631 ## URI Types
632
633 An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference.
634 An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI,
635 the base URI. Relative references can be divided into several forms according to
636 [RFC 3986 Section 4.2](https://datatracker.ietf.org/doc/html/rfc3986#section-4.2):
637
638 - network-path references, e.g. `//example.com/path`
639 - absolute-path references, e.g. `/path`
640 - relative-path references, e.g. `subpath`
641
642 The following methods can be used to identify the type of the URI.
643
644 ### `GuzzleHttp\Psr7\Uri::isAbsolute`
645
646 `public static function isAbsolute(UriInterface $uri): bool`
647
648 Whether the URI is absolute, i.e. it has a scheme.
649
650 ### `GuzzleHttp\Psr7\Uri::isNetworkPathReference`
651
652 `public static function isNetworkPathReference(UriInterface $uri): bool`
653
654 Whether the URI is a network-path reference. A relative reference that begins with two slash characters is
655 termed an network-path reference.
656
657 ### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference`
658
659 `public static function isAbsolutePathReference(UriInterface $uri): bool`
660
661 Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is
662 termed an absolute-path reference.
663
664 ### `GuzzleHttp\Psr7\Uri::isRelativePathReference`
665
666 `public static function isRelativePathReference(UriInterface $uri): bool`
667
668 Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is
669 termed a relative-path reference.
670
671 ### `GuzzleHttp\Psr7\Uri::isSameDocumentReference`
672
673 `public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool`
674
675 Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its
676 fragment component, identical to the base URI. When no base URI is given, only an empty URI reference
677 (apart from its fragment) is considered a same-document reference.
678
679 ## URI Components
680
681 Additional methods to work with URI components.
682
683 ### `GuzzleHttp\Psr7\Uri::isDefaultPort`
684
685 `public static function isDefaultPort(UriInterface $uri): bool`
686
687 Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null
688 or the standard port. This method can be used independently of the implementation.
689
690 ### `GuzzleHttp\Psr7\Uri::composeComponents`
691
692 `public static function composeComponents($scheme, $authority, $path, $query, $fragment): string`
693
694 Composes a URI reference string from its various components according to
695 [RFC 3986 Section 5.3](https://datatracker.ietf.org/doc/html/rfc3986#section-5.3). Usually this method does not need
696 to be called manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
697
698 ### `GuzzleHttp\Psr7\Uri::fromParts`
699
700 `public static function fromParts(array $parts): UriInterface`
701
702 Creates a URI from a hash of [`parse_url`](https://www.php.net/manual/en/function.parse-url.php) components.
703
704
705 ### `GuzzleHttp\Psr7\Uri::withQueryValue`
706
707 `public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface`
708
709 Creates a new URI with a specific query string value. Any existing query string values that exactly match the
710 provided key are removed and replaced with the given key value pair. A value of null will set the query string
711 key without a value, e.g. "key" instead of "key=value".
712
713 ### `GuzzleHttp\Psr7\Uri::withQueryValues`
714
715 `public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface`
716
717 Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an
718 associative array of key => value.
719
720 ### `GuzzleHttp\Psr7\Uri::withoutQueryValue`
721
722 `public static function withoutQueryValue(UriInterface $uri, $key): UriInterface`
723
724 Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the
725 provided key are removed.
726
727 ## Cross-Origin Detection
728
729 `GuzzleHttp\Psr7\UriComparator` provides methods to determine if a modified URL should be considered cross-origin.
730
731 ### `GuzzleHttp\Psr7\UriComparator::isCrossOrigin`
732
733 `public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool`
734
735 Determines if a modified URL should be considered cross-origin with respect to an original URL.
736
737 Two URLs are cross-origin when their scheme, host, or effective port differ. Host comparison is case-insensitive, and missing ports use the default port for `http` or `https`. Other schemes do not receive implicit default ports.
738
739 This helper only compares URI origins. It does not implement redirect handling or credential policy.
740
741 ## Reference Resolution
742
743 `GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according
744 to [RFC 3986 Section 5](https://datatracker.ietf.org/doc/html/rfc3986#section-5). This is for example also what web
745 browsers do when resolving a link in a website based on the current request URI.
746
747 ### `GuzzleHttp\Psr7\UriResolver::resolve`
748
749 `public static function resolve(UriInterface $base, UriInterface $rel): UriInterface`
750
751 Converts the relative URI into a new URI that is resolved against the base URI.
752
753 ### `GuzzleHttp\Psr7\UriResolver::removeDotSegments`
754
755 `public static function removeDotSegments(string $path): string`
756
757 Removes dot segments from a path and returns the new path according to
758 [RFC 3986 Section 5.2.4](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4).
759
760 ### `GuzzleHttp\Psr7\UriResolver::relativize`
761
762 `public static function relativize(UriInterface $base, UriInterface $target): UriInterface`
763
764 Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():
765
766 ```php
767 (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))
768 ```
769
770 One use-case is to use the current request URI as base URI and then generate relative links in your documents
771 to reduce the document size or offer self-contained downloadable document archives.
772
773 ```php
774 $base = new Uri('http://example.com/a/b/');
775 echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'.
776 echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'.
777 echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
778 echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'.
779 ```
780
781 ## Normalization and Comparison
782
783 `GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to
784 [RFC 3986 Section 6](https://datatracker.ietf.org/doc/html/rfc3986#section-6).
785
786 ### `GuzzleHttp\Psr7\UriNormalizer::normalize`
787
788 `public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface`
789
790 Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface.
791 This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask
792 of normalizations to apply. The following normalizations are available:
793
794 - `UriNormalizer::PRESERVING_NORMALIZATIONS`
795
796 Default normalizations which only include the ones that preserve semantics.
797
798 - `UriNormalizer::CAPITALIZE_PERCENT_ENCODING`
799
800 All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.
801
802 Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b`
803
804 - `UriNormalizer::DECODE_UNRESERVED_CHARACTERS`
805
806 Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of
807 ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should
808 not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved
809 characters by URI normalizers.
810
811 Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/`
812
813 - `UriNormalizer::CONVERT_EMPTY_PATH`
814
815 Converts the empty path to "/" for http and https URIs.
816
817 Example: `http://example.org` → `http://example.org/`
818
819 - `UriNormalizer::REMOVE_DEFAULT_HOST`
820
821 Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host
822 "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to
823 RFC 3986.
824
825 Example: `file://localhost/myfile` → `file:///myfile`
826
827 - `UriNormalizer::REMOVE_DEFAULT_PORT`
828
829 Removes the default port of the given URI scheme from the URI.
830
831 Example: `http://example.org:80/` → `http://example.org/`
832
833 - `UriNormalizer::REMOVE_DOT_SEGMENTS`
834
835 Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would
836 change the semantics of the URI reference.
837
838 Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html`
839
840 - `UriNormalizer::REMOVE_DUPLICATE_SLASHES`
841
842 Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes
843 and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization
844 may change the semantics. Encoded slashes (%2F) are not removed.
845
846 Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html`
847
848 - `UriNormalizer::SORT_QUERY_PARAMETERS`
849
850 Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be
851 significant (this is not defined by the standard). So this normalization is not safe and may change the semantics
852 of the URI.
853
854 Example: `?lang=en&article=fred` → `?article=fred&lang=en`
855
856 ### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent`
857
858 `public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool`
859
860 Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given
861 `$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent.
862 This of course assumes they will be resolved against the same base URI. If this is not the case, determination of
863 equivalence or difference of relative references does not mean anything.
864
865
866 ## Security
867
868 If you discover a security vulnerability within this package, please send an email to [email protected]. 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.
869
870
871 ## License
872
873 Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
874
875
876 ## For Enterprise
877
878 Available as part of the Tidelift Subscription
879
880 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)