Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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