source: externals/php/vendor/guzzlehttp/psr7/README.md@ e498070

Last change on this file since e498070 was 01a620f, checked in by Joachim Langenbach <joachim.langenbach@…>, 11 years ago

Removed submodules for php externals and use composer to provide them and versioned them afterwards

  • Property mode set to 100644
File size: 15.0 KB
Line 
1# PSR-7 Message Implementation
2
3This repository contains a partial [PSR-7](http://www.php-fig.org/psr/psr-7/)
4message implementation, several stream decorators, and some helpful
5functionality like query string parsing. Currently missing
6ServerRequestInterface and UploadedFileInterface; a pull request for these features is welcome.
7
8
9# Stream implementation
10
11This package comes with a number of stream implementations and stream
12decorators.
13
14
15## AppendStream
16
17`GuzzleHttp\Psr7\AppendStream`
18
19Reads from multiple streams, one after the other.
20
21```php
22use GuzzleHttp\Psr7;
23
24$a = Psr7\stream_for('abc, ');
25$b = Psr7\stream_for('123.');
26$composed = new Psr7\AppendStream([$a, $b]);
27
28$composed->addStream(Psr7\stream_for(' Above all listen to me').
29
30echo $composed(); // abc, 123. Above all listen to me.
31```
32
33
34## BufferStream
35
36`GuzzleHttp\Psr7\BufferStream`
37
38Provides a buffer stream that can be written to to fill a buffer, and read
39from to remove bytes from the buffer.
40
41This stream returns a "hwm" metadata value that tells upstream consumers
42what the configured high water mark of the stream is, or the maximum
43preferred size of the buffer.
44
45```php
46use GuzzleHttp\Psr7;
47
48// When more than 1024 bytes are in the buffer, it will begin returning
49// false to writes. This is an indication that writers should slow down.
50$buffer = new Psr7\BufferStream(1024);
51```
52
53
54## CachingStream
55
56The CachingStream is used to allow seeking over previously read bytes on
57non-seekable streams. This can be useful when transferring a non-seekable
58entity body fails due to needing to rewind the stream (for example, resulting
59from a redirect). Data that is read from the remote stream will be buffered in
60a PHP temp stream so that previously read bytes are cached first in memory,
61then on disk.
62
63```php
64use GuzzleHttp\Psr7;
65
66$original = Psr7\stream_for(fopen('http://www.google.com', 'r'));
67$stream = new Psr7\CachingStream($original);
68
69$stream->read(1024);
70echo $stream->tell();
71// 1024
72
73$stream->seek(0);
74echo $stream->tell();
75// 0
76```
77
78
79## DroppingStream
80
81`GuzzleHttp\Psr7\DroppingStream`
82
83Stream decorator that begins dropping data once the size of the underlying
84stream becomes too full.
85
86```php
87use GuzzleHttp\Psr7;
88
89// Create an empty stream
90$stream = Psr7\stream_for();
91
92// Start dropping data when the stream has more than 10 bytes
93$dropping = new Psr7\DroppingStream($stream, 10);
94
95$stream->write('01234567890123456789');
96echo $stream; // 0123456789
97```
98
99
100## FnStream
101
102`GuzzleHttp\Psr7\FnStream`
103
104Compose stream implementations based on a hash of functions.
105
106Allows for easy testing and extension of a provided stream without needing to
107to create a concrete class for a simple extension point.
108
109```php
110
111use GuzzleHttp\Psr7;
112
113$stream = Psr7\stream_for('hi');
114$fnStream = Psr7\FnStream::decorate($stream, [
115 'rewind' => function () use ($stream) {
116 echo 'About to rewind - ';
117 $stream->rewind();
118 echo 'rewound!';
119 }
120]);
121
122$fnStream->rewind();
123// Outputs: About to rewind - rewound!
124```
125
126
127## InflateStream
128
129`GuzzleHttp\Psr7\InflateStream`
130
131Uses PHP's zlib.inflate filter to inflate deflate or gzipped content.
132
133This stream decorator skips the first 10 bytes of the given stream to remove
134the gzip header, converts the provided stream to a PHP stream resource,
135then appends the zlib.inflate filter. The stream is then converted back
136to a Guzzle stream resource to be used as a Guzzle stream.
137
138
139## LazyOpenStream
140
141`GuzzleHttp\Psr7\LazyOpenStream`
142
143Lazily reads or writes to a file that is opened only after an IO operation
144take place on the stream.
145
146```php
147use GuzzleHttp\Psr7;
148
149$stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
150// The file has not yet been opened...
151
152echo $stream->read(10);
153// The file is opened and read from only when needed.
154```
155
156
157## LimitStream
158
159`GuzzleHttp\Psr7\LimitStream`
160
161LimitStream can be used to read a subset or slice of an existing stream object.
162This can be useful for breaking a large file into smaller pieces to be sent in
163chunks (e.g. Amazon S3's multipart upload API).
164
165```php
166use GuzzleHttp\Psr7;
167
168$original = Psr7\stream_for(fopen('/tmp/test.txt', 'r+'));
169echo $original->getSize();
170// >>> 1048576
171
172// Limit the size of the body to 1024 bytes and start reading from byte 2048
173$stream = new Psr7\LimitStream($original, 1024, 2048);
174echo $stream->getSize();
175// >>> 1024
176echo $stream->tell();
177// >>> 0
178```
179
180
181## MultipartStream
182
183`GuzzleHttp\Psr7\MultipartStream`
184
185Stream that when read returns bytes for a streaming multipart or
186multipart/form-data stream.
187
188
189## NoSeekStream
190
191`GuzzleHttp\Psr7\NoSeekStream`
192
193NoSeekStream wraps a stream and does not allow seeking.
194
195```php
196use GuzzleHttp\Psr7;
197
198$original = Psr7\stream_for('foo');
199$noSeek = new Psr7\NoSeekStream($original);
200
201echo $noSeek->read(3);
202// foo
203var_export($noSeek->isSeekable());
204// false
205$noSeek->seek(0);
206var_export($noSeek->read(3));
207// NULL
208```
209
210
211## PumpStream
212
213`GuzzleHttp\Psr7\PumpStream`
214
215Provides a read only stream that pumps data from a PHP callable.
216
217When invoking the provided callable, the PumpStream will pass the amount of
218data requested to read to the callable. The callable can choose to ignore
219this value and return fewer or more bytes than requested. Any extra data
220returned by the provided callable is buffered internally until drained using
221the read() function of the PumpStream. The provided callable MUST return
222false when there is no more data to read.
223
224
225## Implementing stream decorators
226
227Creating a stream decorator is very easy thanks to the
228`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that
229implement `Psr\Http\Message\StreamInterface` by proxying to an underlying
230stream. Just `use` the `StreamDecoratorTrait` and implement your custom
231methods.
232
233For example, let's say we wanted to call a specific function each time the last
234byte is read from a stream. This could be implemented by overriding the
235`read()` method.
236
237```php
238use Psr\Http\Message\StreamInterface;
239use GuzzleHttp\Psr7\StreamDecoratorTrait;
240
241class EofCallbackStream implements StreamInterface
242{
243 use StreamDecoratorTrait;
244
245 private $callback;
246
247 public function __construct(StreamInterface $stream, callable $cb)
248 {
249 $this->stream = $stream;
250 $this->callback = $cb;
251 }
252
253 public function read($length)
254 {
255 $result = $this->stream->read($length);
256
257 // Invoke the callback when EOF is hit.
258 if ($this->eof()) {
259 call_user_func($this->callback);
260 }
261
262 return $result;
263 }
264}
265```
266
267This decorator could be added to any existing stream and used like so:
268
269```php
270use GuzzleHttp\Psr7;
271
272$original = Psr7\stream_for('foo');
273
274$eofStream = new EofCallbackStream($original, function () {
275 echo 'EOF!';
276});
277
278$eofStream->read(2);
279$eofStream->read(1);
280// echoes "EOF!"
281$eofStream->seek(0);
282$eofStream->read(3);
283// echoes "EOF!"
284```
285
286
287## PHP StreamWrapper
288
289You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a
290PSR-7 stream as a PHP stream resource.
291
292Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP
293stream from a PSR-7 stream.
294
295```php
296use GuzzleHttp\Psr7\StreamWrapper;
297
298$stream = GuzzleHttp\Psr7\stream_for('hello!');
299$resource = StreamWrapper::getResource($stream);
300echo fread($resource, 6); // outputs hello!
301```
302
303
304# Function API
305
306There are various functions available under the `GuzzleHttp\Psr7` namespace.
307
308
309## `function str`
310
311`function str(MessageInterface $message)`
312
313Returns the string representation of an HTTP message.
314
315```php
316$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
317echo GuzzleHttp\Psr7\str($request);
318```
319
320
321## `function uri_for`
322
323`function uri_for($uri)`
324
325This function accepts a string or `Psr\Http\Message\UriInterface` and returns a
326UriInterface for the given value. If the value is already a `UriInterface`, it
327is returned as-is.
328
329```php
330$uri = GuzzleHttp\Psr7\uri_for('http://example.com');
331assert($uri === GuzzleHttp\Psr7\uri_for($uri));
332```
333
334
335## `function stream_for`
336
337`function stream_for($resource = '', array $options = [])`
338
339Create a new stream based on the input type.
340
341Options is an associative array that can contain the following keys:
342
343* - metadata: Array of custom metadata.
344* - size: Size of the stream.
345
346This method accepts the following `$resource` types:
347
348- `Psr\Http\Message\StreamInterface`: Returns the value as-is.
349- `string`: Creates a stream object that uses the given string as the contents.
350- `resource`: Creates a stream object that wraps the given PHP stream resource.
351- `Iterator`: If the provided value implements `Iterator`, then a read-only
352 stream object will be created that wraps the given iterable. Each time the
353 stream is read from, data from the iterator will fill a buffer and will be
354 continuously called until the buffer is equal to the requested read size.
355 Subsequent read calls will first read from the buffer and then call `next`
356 on the underlying iterator until it is exhausted.
357- `object` with `__toString()`: If the object has the `__toString()` method,
358 the object will be cast to a string and then a stream will be returned that
359 uses the string value.
360- `NULL`: When `null` is passed, an empty stream object is returned.
361- `callable` When a callable is passed, a read-only stream object will be
362 created that invokes the given callable. The callable is invoked with the
363 number of suggested bytes to read. The callable can return any number of
364 bytes, but MUST return `false` when there is no more data to return. The
365 stream object that wraps the callable will invoke the callable until the
366 number of requested bytes are available. Any additional bytes will be
367 buffered and used in subsequent reads.
368
369```php
370$stream = GuzzleHttp\Psr7\stream_for('foo');
371$stream = GuzzleHttp\Psr7\stream_for(fopen('/path/to/file', 'r'));
372
373$generator function ($bytes) {
374 for ($i = 0; $i < $bytes; $i++) {
375 yield ' ';
376 }
377}
378
379$stream = GuzzleHttp\Psr7\stream_for($generator(100));
380```
381
382
383## `function parse_header`
384
385`function parse_header($header)`
386
387Parse an array of header values containing ";" separated data into an array of
388associative arrays representing the header key value pair data of the header.
389When a parameter does not contain a value, but just contains a key, this
390function will inject a key with a '' string value.
391
392
393## `function normalize_header`
394
395`function normalize_header($header)`
396
397Converts an array of header values that may contain comma separated headers
398into an array of headers with no comma separated values.
399
400
401## `function modify_request`
402
403`function modify_request(RequestInterface $request, array $changes)`
404
405Clone and modify a request with the given changes. This method is useful for
406reducing the number of clones needed to mutate a message.
407
408The changes can be one of:
409
410- method: (string) Changes the HTTP method.
411- set_headers: (array) Sets the given headers.
412- remove_headers: (array) Remove the given headers.
413- body: (mixed) Sets the given body.
414- uri: (UriInterface) Set the URI.
415- query: (string) Set the query string value of the URI.
416- version: (string) Set the protocol version.
417
418
419## `function rewind_body`
420
421`function rewind_body(MessageInterface $message)`
422
423Attempts to rewind a message body and throws an exception on failure. The body
424of the message will only be rewound if a call to `tell()` returns a value other
425than `0`.
426
427
428## `function try_fopen`
429
430`function try_fopen($filename, $mode)`
431
432Safely opens a PHP stream resource using a filename.
433
434When fopen fails, PHP normally raises a warning. This function adds an error
435handler that checks for errors and throws an exception instead.
436
437
438## `function copy_to_string`
439
440`function copy_to_string(StreamInterface $stream, $maxLen = -1)`
441
442Copy the contents of a stream into a string until the given number of bytes
443have been read.
444
445
446## `function copy_to_stream`
447
448`function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)`
449
450Copy the contents of a stream into another stream until the given number of
451bytes have been read.
452
453
454## `function hash`
455
456`function hash(StreamInterface $stream, $algo, $rawOutput = false)`
457
458Calculate a hash of a Stream. This method reads the entire stream to calculate
459a rolling hash (based on PHP's hash_init functions).
460
461
462## `function readline`
463
464`function readline(StreamInterface $stream, $maxLength = null)`
465
466Read a line from the stream up to the maximum allowed buffer length.
467
468
469## `function parse_request`
470
471`function parse_request($message)`
472
473Parses a request message string into a request object.
474
475
476## `function parse_response`
477
478`function parse_response($message)`
479
480Parses a response message string into a response object.
481
482
483## `function parse_query`
484
485`function parse_query($str, $urlEncoding = true)`
486
487Parse a query string into an associative array.
488
489If multiple values are found for the same key, the value of that key value pair
490will become an array. This function does not parse nested PHP style arrays into
491an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed into
492`['foo[a]' => '1', 'foo[b]' => '2']`).
493
494
495## `function build_query`
496
497`function build_query(array $params, $encoding = PHP_QUERY_RFC3986)`
498
499Build a query string from an array of key value pairs.
500
501This function can use the return value of parseQuery() to build a query string.
502This function does not modify the provided keys when an array is encountered
503(like http_build_query would).
504
505
506## `function mimetype_from_filename`
507
508`function mimetype_from_filename($filename)`
509
510Determines the mimetype of a file by looking at its extension.
511
512
513## `function mimetype_from_extension`
514
515`function mimetype_from_extension($extension)`
516
517Maps a file extensions to a mimetype.
518
519
520# Static URI methods
521
522The `GuzzleHttp\Psr7\Uri` class has several static methods to manipulate URIs.
523
524
525## `GuzzleHttp\Psr7\Uri::removeDotSegments`
526
527`public static function removeDotSegments($path) -> UriInterface`
528
529Removes dot segments from a path and returns the new path.
530
531See http://tools.ietf.org/html/rfc3986#section-5.2.4
532
533
534## `GuzzleHttp\Psr7\Uri::resolve`
535
536`public static function resolve(UriInterface $base, $rel) -> UriInterface`
537
538Resolve a base URI with a relative URI and return a new URI.
539
540See http://tools.ietf.org/html/rfc3986#section-5
541
542
543## `GuzzleHttp\Psr7\Uri::withQueryValue`
544
545`public static function withQueryValue(UriInterface $uri, $key, $value) -> UriInterface`
546
547Create a new URI with a specific query string value.
548
549Any existing query string values that exactly match the provided key are
550removed and replaced with the given key value pair.
551
552Note: this function will convert "=" to "%3D" and "&" to "%26".
553
554
555## `GuzzleHttp\Psr7\Uri::withoutQueryValue`
556
557`public static function withoutQueryValue(UriInterface $uri, $key, $value) -> UriInterface`
558
559Create a new URI with a specific query string value removed.
560
561Any existing query string values that exactly match the provided key are
562removed.
563
564Note: this function will convert "=" to "%3D" and "&" to "%26".
565
566
567## `GuzzleHttp\Psr7\Uri::fromParts`
568
569`public static function fromParts(array $parts) -> UriInterface`
570
571Create a `GuzzleHttp\Psr7\Uri` object from a hash of `parse_url` parts.
572
573
574# Not Implemented
575
576A few aspects of PSR-7 are not implemented in this project. A pull request for
577any of these features is welcome:
578
579- `Psr\Http\Message\ServerRequestInterface`
580- `Psr\Http\Message\UploadedFileInterface`
Note: See TracBrowser for help on using the repository browser.