Giter Club home page Giter Club logo

psr7's Introduction

PSR-7 Message Implementation

This repository contains a full PSR-7 message implementation, several stream decorators, and some helpful functionality like query string parsing.

CI Static analysis

Features

This package comes with a number of stream implementations and stream decorators.

Installation

composer require guzzlehttp/psr7

Version Guidance

Version Status PHP Version
1.x Security fixes only >=5.4,<8.1
2.x Latest >=7.2.5,<8.4

AppendStream

GuzzleHttp\Psr7\AppendStream

Reads from multiple streams, one after the other.

use GuzzleHttp\Psr7;

$a = Psr7\Utils::streamFor('abc, ');
$b = Psr7\Utils::streamFor('123.');
$composed = new Psr7\AppendStream([$a, $b]);

$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));

echo $composed; // abc, 123. Above all listen to me.

BufferStream

GuzzleHttp\Psr7\BufferStream

Provides a buffer stream that can be written to fill a buffer, and read from to remove bytes from the buffer.

This stream returns a "hwm" metadata value that tells upstream consumers what the configured high water mark of the stream is, or the maximum preferred size of the buffer.

use GuzzleHttp\Psr7;

// When more than 1024 bytes are in the buffer, it will begin returning
// false to writes. This is an indication that writers should slow down.
$buffer = new Psr7\BufferStream(1024);

CachingStream

The CachingStream is used to allow seeking over previously read bytes on non-seekable streams. This can be useful when transferring a non-seekable entity body fails due to needing to rewind the stream (for example, resulting from a redirect). Data that is read from the remote stream will be buffered in a PHP temp stream so that previously read bytes are cached first in memory, then on disk.

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
$stream = new Psr7\CachingStream($original);

$stream->read(1024);
echo $stream->tell();
// 1024

$stream->seek(0);
echo $stream->tell();
// 0

DroppingStream

GuzzleHttp\Psr7\DroppingStream

Stream decorator that begins dropping data once the size of the underlying stream becomes too full.

use GuzzleHttp\Psr7;

// Create an empty stream
$stream = Psr7\Utils::streamFor();

// Start dropping data when the stream has more than 10 bytes
$dropping = new Psr7\DroppingStream($stream, 10);

$dropping->write('01234567890123456789');
echo $stream; // 0123456789

FnStream

GuzzleHttp\Psr7\FnStream

Compose stream implementations based on a hash of functions.

Allows for easy testing and extension of a provided stream without needing to create a concrete class for a simple extension point.

use GuzzleHttp\Psr7;

$stream = Psr7\Utils::streamFor('hi');
$fnStream = Psr7\FnStream::decorate($stream, [
    'rewind' => function () use ($stream) {
        echo 'About to rewind - ';
        $stream->rewind();
        echo 'rewound!';
    }
]);

$fnStream->rewind();
// Outputs: About to rewind - rewound!

InflateStream

GuzzleHttp\Psr7\InflateStream

Uses PHP's zlib.inflate filter to inflate zlib (HTTP deflate, RFC1950) or gzipped (RFC1952) content.

This stream decorator converts the provided stream to a PHP stream resource, then appends the zlib.inflate filter. The stream is then converted back to a Guzzle stream resource to be used as a Guzzle stream.

LazyOpenStream

GuzzleHttp\Psr7\LazyOpenStream

Lazily reads or writes to a file that is opened only after an IO operation take place on the stream.

use GuzzleHttp\Psr7;

$stream = new Psr7\LazyOpenStream('/path/to/file', 'r');
// The file has not yet been opened...

echo $stream->read(10);
// The file is opened and read from only when needed.

LimitStream

GuzzleHttp\Psr7\LimitStream

LimitStream can be used to read a subset or slice of an existing stream object. This can be useful for breaking a large file into smaller pieces to be sent in chunks (e.g. Amazon S3's multipart upload API).

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
echo $original->getSize();
// >>> 1048576

// Limit the size of the body to 1024 bytes and start reading from byte 2048
$stream = new Psr7\LimitStream($original, 1024, 2048);
echo $stream->getSize();
// >>> 1024
echo $stream->tell();
// >>> 0

MultipartStream

GuzzleHttp\Psr7\MultipartStream

Stream that when read returns bytes for a streaming multipart or multipart/form-data stream.

NoSeekStream

GuzzleHttp\Psr7\NoSeekStream

NoSeekStream wraps a stream and does not allow seeking.

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor('foo');
$noSeek = new Psr7\NoSeekStream($original);

echo $noSeek->read(3);
// foo
var_export($noSeek->isSeekable());
// false
$noSeek->seek(0);
var_export($noSeek->read(3));
// NULL

PumpStream

GuzzleHttp\Psr7\PumpStream

Provides a read only stream that pumps data from a PHP callable.

When invoking the provided callable, the PumpStream will pass the amount of data requested to read to the callable. The callable can choose to ignore this value and return fewer or more bytes than requested. Any extra data returned by the provided callable is buffered internally until drained using the read() function of the PumpStream. The provided callable MUST return false when there is no more data to read.

Implementing stream decorators

Creating a stream decorator is very easy thanks to the GuzzleHttp\Psr7\StreamDecoratorTrait. This trait provides methods that implement Psr\Http\Message\StreamInterface by proxying to an underlying stream. Just use the StreamDecoratorTrait and implement your custom methods.

For example, let's say we wanted to call a specific function each time the last byte is read from a stream. This could be implemented by overriding the read() method.

use Psr\Http\Message\StreamInterface;
use GuzzleHttp\Psr7\StreamDecoratorTrait;

class EofCallbackStream implements StreamInterface
{
    use StreamDecoratorTrait;

    private $callback;

    private $stream;

    public function __construct(StreamInterface $stream, callable $cb)
    {
        $this->stream = $stream;
        $this->callback = $cb;
    }

    public function read($length)
    {
        $result = $this->stream->read($length);

        // Invoke the callback when EOF is hit.
        if ($this->eof()) {
            ($this->callback)();
        }

        return $result;
    }
}

This decorator could be added to any existing stream and used like so:

use GuzzleHttp\Psr7;

$original = Psr7\Utils::streamFor('foo');

$eofStream = new EofCallbackStream($original, function () {
    echo 'EOF!';
});

$eofStream->read(2);
$eofStream->read(1);
// echoes "EOF!"
$eofStream->seek(0);
$eofStream->read(3);
// echoes "EOF!"

PHP StreamWrapper

You can use the GuzzleHttp\Psr7\StreamWrapper class if you need to use a PSR-7 stream as a PHP stream resource.

Use the GuzzleHttp\Psr7\StreamWrapper::getResource() method to create a PHP stream from a PSR-7 stream.

use GuzzleHttp\Psr7\StreamWrapper;

$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
$resource = StreamWrapper::getResource($stream);
echo fread($resource, 6); // outputs hello!

Static API

There are various static methods available under the GuzzleHttp\Psr7 namespace.

GuzzleHttp\Psr7\Message::toString

public static function toString(MessageInterface $message): string

Returns the string representation of an HTTP message.

$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
echo GuzzleHttp\Psr7\Message::toString($request);

GuzzleHttp\Psr7\Message::bodySummary

public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null

Get a short summary of the message body.

Will return null if the response is not printable.

GuzzleHttp\Psr7\Message::rewindBody

public static function rewindBody(MessageInterface $message): void

Attempts to rewind a message body and throws an exception on failure.

The body of the message will only be rewound if a call to tell() returns a value other than 0.

GuzzleHttp\Psr7\Message::parseMessage

public static function parseMessage(string $message): array

Parses an HTTP message into an associative array.

The array contains the "start-line" key containing the start line of the message, "headers" key containing an associative array of header array values, and a "body" key containing the body of the message.

GuzzleHttp\Psr7\Message::parseRequestUri

public static function parseRequestUri(string $path, array $headers): string

Constructs a URI for an HTTP request message.

GuzzleHttp\Psr7\Message::parseRequest

public static function parseRequest(string $message): Request

Parses a request message string into a request object.

GuzzleHttp\Psr7\Message::parseResponse

public static function parseResponse(string $message): Response

Parses a response message string into a response object.

GuzzleHttp\Psr7\Header::parse

public static function parse(string|array $header): array

Parse an array of header values containing ";" separated data into an array of associative arrays representing the header key value pair data of the header. When a parameter does not contain a value, but just contains a key, this function will inject a key with a '' string value.

GuzzleHttp\Psr7\Header::splitList

public static function splitList(string|string[] $header): string[]

Splits a HTTP header defined to contain a comma-separated list into each individual value:

$knownEtags = Header::splitList($request->getHeader('if-none-match'));

Example headers include accept, cache-control and if-none-match.

GuzzleHttp\Psr7\Header::normalize (deprecated)

public static function normalize(string|array $header): array

Header::normalize() is deprecated in favor of Header::splitList() which performs the same operation with a cleaned up API and improved documentation.

Converts an array of header values that may contain comma separated headers into an array of headers with no comma separated values.

GuzzleHttp\Psr7\Query::parse

public static function parse(string $str, int|bool $urlEncoding = true): array

Parse a query string into an associative array.

If multiple values are found for the same key, the value of that key value pair will become an array. This function does not parse nested PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will be parsed into ['foo[a]' => '1', 'foo[b]' => '2']).

GuzzleHttp\Psr7\Query::build

public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string

Build a query string from an array of key value pairs.

This function can use the return value of parse() to build a query string. This function does not modify the provided keys when an array is encountered (like http_build_query() would).

GuzzleHttp\Psr7\Utils::caselessRemove

public static function caselessRemove(iterable<string> $keys, $keys, array $data): array

Remove the items given by the keys, case insensitively from the data.

GuzzleHttp\Psr7\Utils::copyToStream

public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void

Copy the contents of a stream into another stream until the given number of bytes have been read.

GuzzleHttp\Psr7\Utils::copyToString

public static function copyToString(StreamInterface $stream, int $maxLen = -1): string

Copy the contents of a stream into a string until the given number of bytes have been read.

GuzzleHttp\Psr7\Utils::hash

public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string

Calculate a hash of a stream.

This method reads the entire stream to calculate a rolling hash, based on PHP's hash_init functions.

GuzzleHttp\Psr7\Utils::modifyRequest

public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface

Clone and modify a request with the given changes.

This method is useful for reducing the number of clones needed to mutate a message.

  • method: (string) Changes the HTTP method.
  • set_headers: (array) Sets the given headers.
  • remove_headers: (array) Remove the given headers.
  • body: (mixed) Sets the given body.
  • uri: (UriInterface) Set the URI.
  • query: (string) Set the query string value of the URI.
  • version: (string) Set the protocol version.

GuzzleHttp\Psr7\Utils::readLine

public static function readLine(StreamInterface $stream, ?int $maxLength = null): string

Read a line from the stream up to the maximum allowed buffer length.

GuzzleHttp\Psr7\Utils::streamFor

public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface

Create a new stream based on the input type.

Options is an associative array that can contain the following keys:

  • metadata: Array of custom metadata.
  • size: Size of the stream.

This method accepts the following $resource types:

  • Psr\Http\Message\StreamInterface: Returns the value as-is.
  • string: Creates a stream object that uses the given string as the contents.
  • resource: Creates a stream object that wraps the given PHP stream resource.
  • Iterator: If the provided value implements Iterator, then a read-only stream object will be created that wraps the given iterable. Each time the stream is read from, data from the iterator will fill a buffer and will be continuously called until the buffer is equal to the requested read size. Subsequent read calls will first read from the buffer and then call next on the underlying iterator until it is exhausted.
  • object with __toString(): If the object has the __toString() method, the object will be cast to a string and then a stream will be returned that uses the string value.
  • NULL: When null is passed, an empty stream object is returned.
  • callable When a callable is passed, a read-only stream object will be created that invokes the given callable. The callable is invoked with the number of suggested bytes to read. The callable can return any number of bytes, but MUST return false when there is no more data to return. The stream object that wraps the callable will invoke the callable until the number of requested bytes are available. Any additional bytes will be buffered and used in subsequent reads.
$stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));

$generator = function ($bytes) {
    for ($i = 0; $i < $bytes; $i++) {
        yield ' ';
    }
}

$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));

GuzzleHttp\Psr7\Utils::tryFopen

public static function tryFopen(string $filename, string $mode): resource

Safely opens a PHP stream resource using a filename.

When fopen fails, PHP normally raises a warning. This function adds an error handler that checks for errors and throws an exception instead.

GuzzleHttp\Psr7\Utils::tryGetContents

public static function tryGetContents(resource $stream): string

Safely gets the contents of a given stream.

When stream_get_contents fails, PHP normally raises a warning. This function adds an error handler that checks for errors and throws an exception instead.

GuzzleHttp\Psr7\Utils::uriFor

public static function uriFor(string|UriInterface $uri): UriInterface

Returns a UriInterface for the given value.

This function accepts a string or UriInterface and returns a UriInterface for the given value. If the value is already a UriInterface, it is returned as-is.

GuzzleHttp\Psr7\MimeType::fromFilename

public static function fromFilename(string $filename): string|null

Determines the mimetype of a file by looking at its extension.

GuzzleHttp\Psr7\MimeType::fromExtension

public static function fromExtension(string $extension): string|null

Maps a file extensions to a mimetype.

Upgrading from Function API

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:

Original Function Replacement Method
str Message::toString
uri_for Utils::uriFor
stream_for Utils::streamFor
parse_header Header::parse
normalize_header Header::normalize
modify_request Utils::modifyRequest
rewind_body Message::rewindBody
try_fopen Utils::tryFopen
copy_to_string Utils::copyToString
copy_to_stream Utils::copyToStream
hash Utils::hash
readline Utils::readLine
parse_request Message::parseRequest
parse_response Message::parseResponse
parse_query Query::parse
build_query Query::build
mimetype_from_filename MimeType::fromFilename
mimetype_from_extension MimeType::fromExtension
_parse_message Message::parseMessage
_parse_request_uri Message::parseRequestUri
get_message_body_summary Message::bodySummary
_caseless_remove Utils::caselessRemove

Additional URI Methods

Aside from the standard Psr\Http\Message\UriInterface implementation in form of the GuzzleHttp\Psr7\Uri class, this library also provides additional functionality when working with URIs as static methods.

URI Types

An instance of Psr\Http\Message\UriInterface can either be an absolute URI or a relative reference. An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, the base URI. Relative references can be divided into several forms according to RFC 3986 Section 4.2:

  • network-path references, e.g. //example.com/path
  • absolute-path references, e.g. /path
  • relative-path references, e.g. subpath

The following methods can be used to identify the type of the URI.

GuzzleHttp\Psr7\Uri::isAbsolute

public static function isAbsolute(UriInterface $uri): bool

Whether the URI is absolute, i.e. it has a scheme.

GuzzleHttp\Psr7\Uri::isNetworkPathReference

public static function isNetworkPathReference(UriInterface $uri): bool

Whether the URI is a network-path reference. A relative reference that begins with two slash characters is termed an network-path reference.

GuzzleHttp\Psr7\Uri::isAbsolutePathReference

public static function isAbsolutePathReference(UriInterface $uri): bool

Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is termed an absolute-path reference.

GuzzleHttp\Psr7\Uri::isRelativePathReference

public static function isRelativePathReference(UriInterface $uri): bool

Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is termed a relative-path reference.

GuzzleHttp\Psr7\Uri::isSameDocumentReference

public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool

Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its fragment component, identical to the base URI. When no base URI is given, only an empty URI reference (apart from its fragment) is considered a same-document reference.

URI Components

Additional methods to work with URI components.

GuzzleHttp\Psr7\Uri::isDefaultPort

public static function isDefaultPort(UriInterface $uri): bool

Whether the URI has the default port of the current scheme. Psr\Http\Message\UriInterface::getPort may return null or the standard port. This method can be used independently of the implementation.

GuzzleHttp\Psr7\Uri::composeComponents

public static function composeComponents($scheme, $authority, $path, $query, $fragment): string

Composes a URI reference string from its various components according to RFC 3986 Section 5.3. Usually this method does not need to be called manually but instead is used indirectly via Psr\Http\Message\UriInterface::__toString.

GuzzleHttp\Psr7\Uri::fromParts

public static function fromParts(array $parts): UriInterface

Creates a URI from a hash of parse_url components.

GuzzleHttp\Psr7\Uri::withQueryValue

public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface

Creates a new URI with a specific query string value. Any existing query string values that exactly match the provided key are removed and replaced with the given key value pair. A value of null will set the query string key without a value, e.g. "key" instead of "key=value".

GuzzleHttp\Psr7\Uri::withQueryValues

public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface

Creates a new URI with multiple query string values. It has the same behavior as withQueryValue() but for an associative array of key => value.

GuzzleHttp\Psr7\Uri::withoutQueryValue

public static function withoutQueryValue(UriInterface $uri, $key): UriInterface

Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the provided key are removed.

Cross-Origin Detection

GuzzleHttp\Psr7\UriComparator provides methods to determine if a modified URL should be considered cross-origin.

GuzzleHttp\Psr7\UriComparator::isCrossOrigin

public static function isCrossOrigin(UriInterface $original, UriInterface $modified): bool

Determines if a modified URL should be considered cross-origin with respect to an original URL.

Reference Resolution

GuzzleHttp\Psr7\UriResolver provides methods to resolve a URI reference in the context of a base URI according to RFC 3986 Section 5. This is for example also what web browsers do when resolving a link in a website based on the current request URI.

GuzzleHttp\Psr7\UriResolver::resolve

public static function resolve(UriInterface $base, UriInterface $rel): UriInterface

Converts the relative URI into a new URI that is resolved against the base URI.

GuzzleHttp\Psr7\UriResolver::removeDotSegments

public static function removeDotSegments(string $path): string

Removes dot segments from a path and returns the new path according to RFC 3986 Section 5.2.4.

GuzzleHttp\Psr7\UriResolver::relativize

public static function relativize(UriInterface $base, UriInterface $target): UriInterface

Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve():

(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target))

One use-case is to use the current request URI as base URI and then generate relative links in your documents to reduce the document size or offer self-contained downloadable document archives.

$base = new Uri('http://example.com/a/b/');
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c'));  // prints 'c'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y'));  // prints '../x/y'.
echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'.
echo UriResolver::relativize($base, new Uri('http://example.org/a/b/'));   // prints '//example.org/a/b/'.

Normalization and Comparison

GuzzleHttp\Psr7\UriNormalizer provides methods to normalize and compare URIs according to RFC 3986 Section 6.

GuzzleHttp\Psr7\UriNormalizer::normalize

public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface

Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. This methods adds additional normalizations that can be configured with the $flags parameter which is a bitmask of normalizations to apply. The following normalizations are available:

  • UriNormalizer::PRESERVING_NORMALIZATIONS

    Default normalizations which only include the ones that preserve semantics.

  • UriNormalizer::CAPITALIZE_PERCENT_ENCODING

    All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized.

    Example: http://example.org/a%c2%b1b โ†’ http://example.org/a%C2%B1b

  • UriNormalizer::DECODE_UNRESERVED_CHARACTERS

    Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of ALPHA (%41โ€“%5A and %61โ€“%7A), DIGIT (%30โ€“%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved characters by URI normalizers.

    Example: http://example.org/%7Eusern%61me/ โ†’ http://example.org/~username/

  • UriNormalizer::CONVERT_EMPTY_PATH

    Converts the empty path to "/" for http and https URIs.

    Example: http://example.org โ†’ http://example.org/

  • UriNormalizer::REMOVE_DEFAULT_HOST

    Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host "localhost". All of file:/myfile, file:///myfile, and file://localhost/myfile are equivalent according to RFC 3986.

    Example: file://localhost/myfile โ†’ file:///myfile

  • UriNormalizer::REMOVE_DEFAULT_PORT

    Removes the default port of the given URI scheme from the URI.

    Example: http://example.org:80/ โ†’ http://example.org/

  • UriNormalizer::REMOVE_DOT_SEGMENTS

    Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would change the semantics of the URI reference.

    Example: http://example.org/../a/b/../c/./d.html โ†’ http://example.org/a/c/d.html

  • UriNormalizer::REMOVE_DUPLICATE_SLASHES

    Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization may change the semantics. Encoded slashes (%2F) are not removed.

    Example: http://example.org//foo///bar.html โ†’ http://example.org/foo/bar.html

  • UriNormalizer::SORT_QUERY_PARAMETERS

    Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be significant (this is not defined by the standard). So this normalization is not safe and may change the semantics of the URI.

    Example: ?lang=en&article=fred โ†’ ?article=fred&lang=en

GuzzleHttp\Psr7\UriNormalizer::isEquivalent

public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool

Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also accepts relative URI references and returns true when they are equivalent. This of course assumes they will be resolved against the same base URI. If this is not the case, determination of equivalence or difference of relative references does not mean anything.

Security

If you discover a security vulnerability within this package, please send an email to [email protected]. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see Security Policy for more information.

License

Guzzle is made available under the MIT License (MIT). Please see License File for more information.

For Enterprise

Available as part of the Tidelift Subscription

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.

psr7's People

Contributors

albe avatar andreskrey avatar andreybolonin avatar barryvdh avatar benmorel avatar carusogabriel avatar gmponos avatar grahamcampbell avatar gzumba avatar hansott avatar ivank avatar jeremeamia avatar jeskew avatar kevinrob avatar kkopachev avatar mapogolions avatar marius-c avatar mtdowling avatar northys avatar nyholm avatar onyn avatar rayrutjes avatar reedy avatar sagikazarmark avatar timwolla avatar tobion avatar trowski avatar uda avatar villfa avatar zyfran avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

psr7's Issues

Is there a way to serialize Response objects?

I need to cache serialized Response objects in a database, but the Stream-based bodies are posing a challenge. Here's a unit test that demonstrates my problem:

public function testTest()
{
  $original = new Response(200, [], 'body');
  $serialized = serialize($original);
  $unserialized = unserialize($serialized);

  $this->assertEquals('body', (string) $original->getBody(), 'Got expected body value from original object.');
  $this->assertEquals('body', (string) $unserialized->getBody(), 'Got expected body value from object after serializing and unserializing.');
}
$ ./vendor/bin/phpunit tests/SerializationTest.php
PHPUnit 4.8.21 by Sebastian Bergmann and contributors.

PHP Warning:  fseek() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 199
PHP Warning:  stream_get_contents() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 94
F
Warning: fseek() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 199

Warning: stream_get_contents() expects parameter 1 to be resource, integer given in /Users/travis.carden/Projects/psr7/src/Stream.php on line 94


Time: 55 ms, Memory: 4.50Mb

There was 1 failure:

1) GuzzleHttp\Tests\Psr7\SerializationTest::testSerialization
Got expected body value from object after serializing and unserializing.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'body'
+''

/Users/travis.carden/Projects/psr7/tests/SerializationTest.php:16

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

Is there any way to make responses serializable? If not, I'll probably just store a string version of the body next to the serialized Response in my cache setter and withResponse() it back into the unserialized Response in my cache getter.

Question

Hi,

I was going through the guzzle code, have a doubt regarding the implementation

$new->headers[strtolower($header)][] = $value;

Doesn't it need to preserve the case sensitivity? See

https://github.com/php-fig/http-message/blob/f3218d1cdf479cd9a65d568f605edbc17c6df82a/src/MessageInterface.php#L118

While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders()

and I am seeing

return $this->headerLines;

public function getHeaders()
{
    return $this->headerLines;
}

I understand it finally is returning the preserved value. But does headerLines in headers is a bit confusing? I wished the variable name is like

public function getHeaders()
{
    return $this->headers;
}

public function getHeaderLines()
{
    return $this->headerLines;
}

Thank you

PHP Fatal error: Method GuzzleHttp\Psr7\Uri::__toString() must not throw an exception

Hello, I'm running into this fatal error with one of my tests:

PHP Fatal error:  Method GuzzleHttp\Psr7\Uri::__toString() must not throw an exception in /path-to/test/TestCase.php on line 0

It appears to stem from a call to GuzzleHttp\Client::getAsync(), though wrapping that call in a try/catch doesn't seem to catch an exception.

Thanks

Serializing Requests

Hello guys,

I want to serialize requests and responses as well.

I found the solution on #53 - but

The \GuzzleHttp\Psr7\str function does a good job indeed, except it doesn't make a difference between HTTP and HTTPS.

<?php

use GuzzleHttp\Psr7\Request;
use function \GuzzleHttp\Psr7\str;

require_once __DIR__ . '/../vendor/autoload.php';

$secureRequest   = new Request('GET', 'https://example.org');
$unsecureRequest = new Request('GET', 'http://example.org');
var_dump(str($secureRequest) === str($unsecureRequest)); // true

This is quite disturbing because when I store a request as string for further use, the request automatically switches to HTTP...

Any ideas?

Thanks,
Ben

LimitStreamTest::testEnsuresPositionCanBeekSeekedTo()

https://github.com/guzzle/psr7/blob/master/tests/LimitStreamTest.php#L52

I don't know if it is a real issue, but do you know, that this test passes only because Psr7\stream_for() creates 'php://temp' stream? Php tries to fseek() to non-existing offset and gets an error there https://github.com/guzzle/psr7/blob/master/src/Stream.php#L200.

But if Psr7\stream_for() called fopen('<path to some file>', 'w');, the test would fail, because

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0.
https://php.net/manual/en/function.fseek.php

$stream = fopen('php://temp', 'r+');
echo fseek($stream, 10) . "\n";      <โ€” -1

$stream = fopen('./fseek.file', 'w');
echo fseek($stream, 10) . "\n";      <โ€” 0

I discovered this, when I tested PSR-7 on HHVM. In HHVM fseek() can go beyond the end-of-line in 'php://temp' streams too, so this test fails. And now I don't know who's problem it is, and is it a problem at all.

Tested on Ubuntu 14.04, php 5.5.26, hhvm 3.9.1

InflateStream doesn't appear to allow incremental reading

Couldn't read incrementally from an InflateStream:

$content = fopen(__DIR__.'/InflateStreamTestData.txt.gz', 'rb');
$a = Psr7\stream_for($content);
$b = new InflateStream($a);
$this->assertEquals('Nulla voluptate qui consectetur cillum consectetur.', $b->read(51));

Is this a miss-use of the API? Or is this a bug? Missing feature?

If one of the later, please provide direction so I can work on the pull request.

Test case here: patsplat@daac696

cURL error 3

a composer update broke our use of guzzlehttp, when updating to psr7 1.3.1
forcing our composer.json file to install 1.3.0 got it working for us again.

the exception thrown is:
"cURL error 3: malformed (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)"

the url is like http://10.10.20.20:2080/api/cars/1

edit: broken with commit 889f21e

Relative URI > Can't parse_url if colon is present

When using relative URIs they are sent to the Uri constructor and parse_url is called to extract information from them.

Conditions:
If the path contains a colon.
...and what comes after the colon character must be numeric.
...and number of numeric characters after the colon is < 6.
...in other words if it "kinda looks like a port number"...
...and there are no query parameters.
...and there is no fragment.
...and there are no previous occurrences of the colon sign.

...then parse_url will fail to recognize the path component and return false

    // Psr\Http\Message\UriInterface\Uri

    public function __construct($uri = '')
    {
        if ($uri != null) {
            $parts = parse_url($uri);
        ....

    }

    ...

    public static function resolve(UriInterface $base, $rel)
    {
        ...

        if (!($rel instanceof UriInterface)) {
            $rel = new self($rel);
        }

        ....

    }

You can reproduce the issue via:

$client = new GuzzleHttp\Client(['base_uri' => 'http://example.com:90/']);
$client->request('get', '/a/b/c/d/e:12345');

Array Parameter not working

I have this code

$data = array( 'File-Name' => $file_name, 'Mime-Type' => 'application/pdf', 'File' => $sourcePath ); $multipartStream = new MultipartStream($data);

but I'm getting an error of
Catchable fatal error: Argument 2 passed to GuzzleHttp\Psr7\MultipartStream::addElement() must be of the type array, string given, called in /Applications/MAMP/htdocs/adobesignwp/wp-content/plugins/Gravity2PDF/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php on line 70 and defined in /Applications/MAMP/htdocs/adobesignwp/wp-content/plugins/Gravity2PDF/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php on line 79

Function GuzzleHttp\Psr7\parse_request($message) doesn't support absolute URI's.

I was wondering why parse_request doesn't support absolute URI's. Request like this fail:

GET https://www.google.com HTTP/1.1

The regex explicity requires a starting slash after the keyword:

if (!preg_match('/^[a-zA-Z]+\s+\/.*/', $data['start-line'])) {
    throw new \InvalidArgumentException('Invalid request string');
}

Are there any objections to support absolute URI's as well? I'm trying to build a php proxy server using reactphp/http (which uses guzzle/psr7) and it doesn't work because of this. If no objections I can create a PR.

Best,
Nicolas

psr7 StreamWrapper

It is not issue, it is rather a question. Why not add this functionality (StreamWrapper) in the very class of the stream? These classes, in fact, are wrapper?

public function __call($name, $arguments)
    {
        if (false !== strpos($name, 'stream_')) {
            $name = substr($name, 7);
        }
        $method = strtolower(str_replace('_', '', $name));
        if (! method_exists($this, $method)) {
            throw new InvalidArgumentException(
                sprintf('Method "%s" doesn\'t exist', $name)
            );
        }
        return call_user_func_array([$this, $method], $arguments);
    }

I'd like Uri to be a little more explicit with port numbers

When doing the following, I'd expect it to return 80.

$uri = new Uri('http://example.com/foo/bar');
return $uri->getPort();

Or if not then I should very much expect it when doing this.

$uri = new Uri('http://example.com/foo/bar');
return $uri->withPort(80)->getPort();

UriResolver does not look at host when scheme is present

When resolving a path for a base url, the combination of the guzzle package and this one results in the host not being set at all.

To explain: the buildUri method in the Guzzle Client always ensures a scheme. So if you have the following base/rel uri:

$base = new Uri('http://example.org');
$rel = new Uri('/foo'); # does not have a scheme

If you request $rel with Guzzle, and you have middleware that uses the resolve method to make a proper uri out of the two:

# in middleware, $rel now has a scheme added by Guzzle
$uri = Uri::resolve($base, $rel);

You would expect this to yield http://example.org/foo, yet the resolver checks for a scheme in $rel and if so, assumes the host is set and returns the normalized $rel without looking at the base uri:

psr7/src/UriResolver.php

Lines 69 to 71 in 64862e8

if ($rel->getScheme() != '') {
return $rel->withPath(self::removeDotSegments($rel->getPath()));
}

Which results in a uri without a host. Now I don't think it's incorrect that the scheme is added by Guzzle, which is why I create the issue in this repo instead. I think the resolve method should check for both scheme and host in the if statement I linked here above.

Unable to read response's body contents

Commit 45054d9#diff-f89246dce7e387482b2c6c584a5e7e9dR97 have introduced a bug by comparing $body with empty string.

I did not dug too deeply to find out the real reason of wrong behavior, but I guess it is caused by implicit calling of GuzzleHttp\Psr7\Stream::__toString() in order to cast object to string to make a comparison.

How to reproduce

        $client = new \GuzzleHttp\Client(['base_uri' => 'https://google.com.ua/']);
        $response = $client->request('GET');
        $html = $response->getBody()->getContents();

What is expected

$html contains a response HTML

What do we have instead

$html is an empty string

Patch?

Rolling back that line to if ($body !== null) fixes the problem. Not sure whether it is a proper fix.

Environment

PHP 5.6.20
Ubuntu 16.04
guzzle/psr7@dev-master

Function that sends header and body with stream support on the basis of a ResponseInterface

This is my try for a function that sends header and body with stream support on the basis of a ResponseInterface:

<?php
/**
* @param ResponseInterface $response
*/
function out(ResponseInterface $response)
{
    header(sprintf('%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase()));

    foreach ($response->getHeaders() as $name => $values) {
        foreach ($values as $value) {
            header(sprintf('%s: %s', $name, $value), false);
        }
    }

    stream_copy_to_stream(StreamWrapper::getResource($response->getBody()), fopen('php://output', 'w'));
}

I think this could be a nice contribution to your functions.php. If you agree, I am going to create a PR.

Uri::createUriString is invalid for URIs lacking an "authority"

In RFC3986 section 3, a valid absolute URI which contains no authority can be written like this: urn:example:animal:ferret:nose. In this case, the URI scheme is urn, and the path is example:animal:ferret:nose:

var_dump(parse_url('urn:example:animal:ferret:nose'));
array(2) {
  ["scheme"]=>
  string(3) "urn"
  ["path"]=>
  string(26) "example:animal:ferret:nose"
}

Problem
The Uri::createUriString function appends // to ANY scheme, when it should only be appending if the authority exists. As a result, the string becomes urn:///example:animal:ferret:nose

Solution
Before appending //, ensure $authority is not empty. Before prepending / to $path, ensure $authority is not empty.

Update README

ServerRequestInterface and UploadedFileInterface have been added. So the README part "Not Implemented" can be removed.

Next Release

Is another tag planned in the near future. It's also necessary for people using old versions of composer.

Warning when calling `read` method of Stream class with 0 length

Hi.
I write API and I use behat to test it.
I'm getting Warning: fread(): Length parameter must be greater than 0 in vendor/guzzlehttp/psr7/src/Stream.php line 211 for every response with empty body.

I made quick fix for that line like

return $length > 0 ? fread($this->stream, $length) : '';

PHP: 7.0.8
guzzlehttp/psr7: 1.3.1

parse_query() not work correct when a query string contains an array

I found an issue about \GuzzleHttp\Psr7\parse_query() not work correct when a query string contains an array.

My english is not good, so try to use an example to explain this issue,
and please to comfirm the different behavior, thanks.

For example:

// According to https://github.com/guzzle/guzzle/blob/master/src/Client.php#L350
// Generate a query string
$query = [
    'foo' => ['item1', 'item2', 'item3'],
];
$queryString = http_build_query($query, null, '&', PHP_QUERY_RFC3986);

// Parse the query string by PHP build-in parse_str()
// @see http://php.net/manual/en/function.parse-str.php
$parseStrResult = [];
parse_str($queryString, $parseStrResult);

// Show the different between parse_str() and parse_query()
$queries = [
    'query_string' => $queryString,
    'origin_query' => $originQuery,
    'parse_str' => $parseStrResult,
    'parse_query'  => \GuzzleHttp\Psr7\parse_query($queryString),
    'parse_query_with_rfc3986'  => \GuzzleHttp\Psr7\parse_query($queryString, PHP_QUERY_RFC3986),
    'parse_query_with_rfc1738'  => \GuzzleHttp\Psr7\parse_query($queryString, PHP_QUERY_RFC1738),
];
print_r($queries);

the output:

Array                                                                                                                                                                               [12/21256]
(
    [query_string] => foo%5B0%5D=item1&foo%5B1%5D=item2&foo%5B2%5D=item3
    [origin_query] => Array
        (
            [foo] => Array
                (
                    [0] => item1
                    [1] => item2
                    [2] => item3
                )

        )

    [parse_str] => Array
        (
            [foo] => Array
                (
                    [0] => item1
                    [1] => item2
                    [2] => item3
                )

        )

    [parse_query] => Array
        (
            [foo[0]] => item1
            [foo[1]] => item2
            [foo[2]] => item3
        )

    [parse_query_with_rfc3986] => Array
        (
            [foo[0]] => item1
            [foo[1]] => item2
            [foo[2]] => item3
        )

    [parse_query_with_rfc1738] => Array
        (
            [foo[0]] => item1
            [foo[1]] => item2
            [foo[2]] => item3
        )

)

GuzzleHttp\Psr7\Response Abstract Error

I'm getting the below message when interacting with Guzzle:

[Symfony\Component\Debug\Exception\FatalErrorException]                                                                                                                                  
  Class GuzzleHttp\Psr7\Response contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Psr\Http\Message\ResponseInterface::setPostField)

Read/Write detection doesnt work correctly for resources from gzopen

When opening a file with gzopen it is possible to specify some extra options, compression level, etc

When a Stream is created it detects readable/writable checking the mode with $readWriteHash which doesn't have entries for all possible modes, eg 'rb9' or wb2.

This results in the Stream being incorrectly marked as neither readable or writable.

I would be happy to make a pull request, but thinking about the best solution. It would be possible to add all the variations to $readWriteHash, but maybe some string manipulation is better option.

Request has invalid documentation or invalid constructor handling

According to https://github.com/guzzle/psr7/blob/master/src/Request.php#L28-L29 the Request class can be created using

<?php
$request = new Request(null, null);

However, the UriInterface validation will cause that to throw an InvalidArgumentException. See https://github.com/guzzle/psr7/blob/master/src/Request.php#L43-L49

Looking at the PSR-7 definition for RequestInterface, neither getMethod or getUri may return anything but a string and UriInterface respectively. My gut feeling is that the documentation should then be considered invalid.

CURL CA certificate, where to set?

This library is being included by Google Cloud API and I am getting errors about there being no CA Cert. Fair enough.

However, I have no idea where I can set the location of the certificate, or how to state that I don't want ot use one.

I've had to kludge the library and set all CA Cert settings to false - obviously no the best idea.

Stream::getSize() should return null with popen streams

Hello,

I am trying to work with popen streams like this:

$stream = \GuzzleHttp\Psr7\stream_for(
    popen(
        'ls', 'r'
    )
);

But $stream->getSize() always returns 0 which causes problems with the Slim framework (see slimphp/Slim#1838).

PSR-7 says that getSize() should return null when the size is unknown, which seems to be the case here.

str function is not rewinding the body

If I use the function str(MessageInterface $message) I have to manually rewind the body of the message.

I am just wondering. Is this the desirable behaviour? I was expecting that it would automatically rewind the message body.

Stream::getContents() unexpected behavior

Hello, I hit one problem when use instance of GuzzleHttp\Psr7\Stream.

echo $response->getBody()->getContents();

method returns me empty string, although the logger show me correct response.

The problem was that the logger use (string) $response->getBody() and we seek to the end of stream.

Should we seek back before returns content?

public function getContents()
{
    $this->rewind();
    $contents = stream_get_contents($this->stream);

    if ($contents === false) {
        throw new \RuntimeException('Unable to read stream contents');
    }

    return $contents;
}

Seems __toString() can call getContent().

Psr7\readline has trouble with non-native EOLs

The condition to check if we got to the end of the line in readline is defined as:

if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
// ...

It will work properly if the stream was generated by a server, which uses the same type of line endings as the system on which the stream is being processed.

For example: an application running on a Linux server returns a stream using \n as EOL. readline is used to read this stream on a Windows server, where PHP_EOL === "\r\n". Because $byte == "\r\n" will never be true, readline will read the whole stream (or to $maxLength, if provided) instead of only the first line.

improve `MessageTrait::SetHeaders()`

  • There is code duplication with withAddedHeader() (difference being the usage of clone) - bad for maintainability
  • It should probably be based on withHeader(), judging by the name & usages

Invalid resource type: integer

Hey,

Any particular reason why stream_for function does not accept an integer ?

It throws that exception when using a parameter like:

[
    'name' => 'event',
    'contents' =>  '1'
]

Implementation ServerRequestInterface

// Message class implements the Message Interface
class Message implements MessageInterface {
    //put code
}
// Server Request class is an abstract basis for the request
abstract class ServerRequest extends Message implements ServerRequestInterface {
    //put code
}
// Request class inherits and provides the USER (according to PSR) access to all methods
class Request extends ServerRequest implements  RequestInterface {
    // put code
}

see https://github.com/KpuTuK/Neiron/tree/master/src/Neiron/Components/Http

Handling fopen url resources in PHP 7

Something has changed between PHP 7 and PHP 5 in terms of handling fopen resources in multipart transfers via GuzzleHttpClient. Files need to be proxied via local file first otherwise requests seem to be different between php versions.

Looks like an invalid chunked body problem

withParentHeader should not be visible?

Request overrides the withHeader method declared in MessageTrait, so the original one is aliased to withParentHeader.

Shouldn't it be protected or private?

copy_to_stream() should return count of copied bytes

The function copy_to_stream() should return the count of copied bytes. Like the PHP function stream_copy_to_stream() does.

Current workaround is to use copy_to_string() and check the length of the returned string but this does not play well for large amounts of data.

Please tag a version 1.1.1

I do need that feature of conditionally loading the global functions due to messed up autoloading on my side.

StreamWrapper::stream_cast()

I'm using dropbox-sdk to upload files to the dropbox storage. This lib uses CURLOPT_INFILE curl option with resource as value to send file.
https://github.com/dropbox/dropbox-sdk-php/blob/master/lib/Dropbox/Client.php#L291
It assumes that StreamWrapper::stream_cast() must be implemented.

I decided extend \GuzzleHttp\Psr7\StreamWrapper class to add stream_cast() method but I found that I can't get stream resource which should return stream_cast().

I created such hack, but I'm not really happy with it:

public function stream_cast($cast_as)
{
    $clonedStream = clone($this->stream);
    return $clonedStream->detach();
}

What do you think about implementation of StreamWrapper::stream_cast() method?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.