BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / push / vendor / guzzlehttp / psr7 / README.md

README.md

README.md 31.0 KiB Download Raw

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

VersionStatusPHP Version
1.xEOL (2024-06-30)>=5.4,<8.2
2.xLatest>=7.2.5,<8.7

See UPGRADING.md for notes on upgrading from 1.x to 2.0.

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
// 0 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 callables.

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.

Each multipart element must contain a name and contents key. contents may be any non-array value accepted by GuzzleHttp\Psr7\Utils::streamFor(), including closures and invokable objects. Array contents are recursively expanded into nested form fields.

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 suggested number of bytes 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 or null when there is no more data to read.

Userland callables that declare no parameters are tolerated by PHP, but length-aware callables remain the recommended formal shape.

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, bool $treatBoolsAsInts = true): 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::asciiToLower

public static function asciiToLower(string $string): string

Converts ASCII uppercase letters in a string to lowercase.

Unlike strtolower(), which honors LC_CTYPE before PHP 8.2, the conversion is locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol elements require.

GuzzleHttp\Psr7\Utils::asciiToUpper

public static function asciiToUpper(string $string): string

Converts ASCII lowercase letters in a string to uppercase.

Unlike strtoupper(), which honors LC_CTYPE before PHP 8.2, the conversion is locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol elements require.

GuzzleHttp\Psr7\Utils::asciiUcFirst

public static function asciiUcFirst(string $string): string

Converts the first character of a string to uppercase when it is an ASCII lowercase letter.

Unlike ucfirst(), which honors LC_CTYPE before PHP 8.2, the conversion is locale-independent and leaves every non-ASCII byte unchanged, as HTTP protocol elements require.

GuzzleHttp\Psr7\Utils::caselessContains

public static function caselessContains(string $haystack, string $needle): bool

Checks whether the haystack contains the needle, comparing ASCII letters case-insensitively and without locale sensitivity.

GuzzleHttp\Psr7\Utils::caselessEquals

public static function caselessEquals(string $left, string $right): bool

Checks whether two strings are equal, comparing ASCII letters case-insensitively and without locale sensitivity.

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.

The copy stops if the destination write() returns 0, for example a BufferStream at its high water mark or a full DroppingStream. For a guaranteed full copy, use a normal writable stream such as a file or php://temp stream.

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. Present non-null values are converted with

GuzzleHttp\Psr7\Utils::streamFor(), including scalar values, resources, streams, iterators, callable arrays, closures, invokable objects, and objects with __toString(). String inputs remain literal bodies.

  • 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::redactUserInfo

public static function redactUserInfo(UriInterface $uri): UriInterface

Redact the password in the user info part of a URI.

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 array, closure, or invokable object is passed and

no earlier resource or object rule applies, a read-only stream object will be created that invokes the given callable. The callable is invoked with the suggested number of bytes to read. The callable can return fewer or more bytes than requested, but MUST return false or null when there is no more data to return. Any additional bytes will be buffered and used in subsequent reads. String inputs are always treated as string bodies, even when they name callable functions.

$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.

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.

Two URLs are cross-origin when their scheme, host, or effective port differ. Host comparison is case-insensitive, and missing ports use the default port for http or https. Other schemes do not receive implicit default ports.

This helper only compares URI origins. It does not implement redirect handling or credential policy.

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.

When the resolved path is a relative-path reference whose first segment contains a colon, which would be mistaken for a scheme name (RFC 3986 Section 4.2), it is prefixed with ./, e.g. ./a:b.

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.

When a normalization rewrites the path of a relative-path reference so that its first segment contains a colon, which would be mistaken for a scheme name (RFC 3986 Section 4.2), the path is prefixed with ./ instead of throwing, e.g. a%41: becomes ./aA: as aA: would be an absolute URI with the scheme aa.

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 security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see Security Policy 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.

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