Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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