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