save
This commit is contained in:
Vendored
+76
@@ -0,0 +1,76 @@
|
||||
# Agent Guidelines
|
||||
|
||||
## Code and tooling
|
||||
|
||||
- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer
|
||||
only under a PHP 7.4.x runtime; never run either tool under any other PHP
|
||||
major.minor version.
|
||||
- Use fully qualified `#[\SensitiveParameter]` on concrete executable
|
||||
parameters when their established role normally carries a secret,
|
||||
credential-bearing aggregate, or confidential Guzzle-owned container, and
|
||||
the active frame can throw or invoke throwing code.
|
||||
- Repeat the attribute on every qualifying owned caller, callee, concrete trait
|
||||
method, and closure parameter. Do not add it to interfaces, abstract-only
|
||||
declarations, pure/no-realistic-throw helpers, assignment-only sites,
|
||||
arbitrary generic payloads, or completed non-recoverable derivatives.
|
||||
- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and
|
||||
the parameter on the following line, expand the complete parameter list, and
|
||||
never add a comma after the final parameter. Native trace redaction starts on
|
||||
PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured
|
||||
variables, return values, or the separate backtrace `$this`/`object`.
|
||||
- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`;
|
||||
never rely on the default characters.
|
||||
- Handle `preg_*` engine failures: when the result is used as data, test for
|
||||
`false` or `null` and throw a `\RuntimeException` including
|
||||
`preg_last_error_msg()`; boolean validation guards must compare strictly, such
|
||||
as `=== 1`, so an engine failure can only ever fail closed. Diagnostic
|
||||
escaping is the narrow exception: use a deterministic bytewise fallback rather
|
||||
than throwing, so it cannot obscure the original exception.
|
||||
- Anchor validation patterns to the true end of input with the `D` modifier or
|
||||
`\z`; a bare `$` accepts a trailing newline.
|
||||
- Never embed raw control bytes in exception messages and other diagnostics;
|
||||
escape or redact the offending value first.
|
||||
- Helper classes that expose only public static methods are `final` and have a
|
||||
private constructor.
|
||||
- Resist native PHP serialization when a class holds live state (streams,
|
||||
resources, handles, callbacks, credentials) or when magic methods such as
|
||||
`__destruct()` have side effects that untrusted unserialized data could
|
||||
redirect, as with the file and session write fixes in Guzzle's persisting
|
||||
cookie jars. Plain data holders, such as Guzzle's in-memory cookie jar, remain
|
||||
serializable.
|
||||
- To resist, `__serialize()` and `__unserialize()` both throw
|
||||
`\LogicException(static::class.' should never be serialized')` and its
|
||||
unserialized counterpart, usually via the `@internal` `NonSerializableTrait`.
|
||||
Where a `__destruct()` has such a side effect, it is enabled only by the
|
||||
constructor and disabled in `__wakeup()` and `__unserialize()` before
|
||||
throwing, so the protection holds even if the exception is swallowed.
|
||||
- In general, numeric inputs should not accept non-finite floats. In situations
|
||||
where they are accepted and we need to cast to a string, we should branch on
|
||||
`\is_finite($value)`, using `(string) $value` for the finite case and
|
||||
`\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise.
|
||||
- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or
|
||||
other locale-sensitive case functions; use the locale-independent
|
||||
`GuzzleHttp\Psr7\Utils::asciiToLower()`, `asciiToUpper()`,
|
||||
`caselessEquals()`, and `caselessContains()` helpers instead.
|
||||
- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of
|
||||
the target branch and an `UPGRADING.md` note when the behavior differs between
|
||||
major versions.
|
||||
|
||||
## Contributor references
|
||||
|
||||
- Read the [exception guidelines](docs/contributing/exception-guidelines.md)
|
||||
before deciding which exception a change should throw.
|
||||
- Read the
|
||||
[cURL connection reuse reference](docs/contributing/curl-connection-reuse.md)
|
||||
before working on the cURL handlers or connection reuse and sharing behavior.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never
|
||||
split a markdown link or an inline code span across a line break; a line that
|
||||
cannot be broken may exceed the limit. Avoid em dashes.
|
||||
- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is
|
||||
deliberately word-for-word identical, including boilerplate copied verbatim
|
||||
between related functions, so apply the same edit to every copy. Only
|
||||
formatting and linking may differ, such as a docs link becoming a PHPDoc
|
||||
`@see` tag; the wording must never drift.
|
||||
+2403
File diff suppressed because it is too large
Load Diff
Vendored
+1
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com>
|
||||
Copyright (c) 2012 Jeremy Lindblom <jeremeamia@gmail.com>
|
||||
Copyright (c) 2014 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
Copyright (c) 2015 Márk Sági-Kazár <mark.sagikazar@gmail.com>
|
||||
Copyright (c) 2015 Tobias Schultze <webmaster@tubo-world.de>
|
||||
Copyright (c) 2016 Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
Copyright (c) 2016 George Mponos <gmponos@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+95
@@ -0,0 +1,95 @@
|
||||

|
||||
|
||||
# Guzzle, PHP HTTP Client
|
||||
|
||||
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
|
||||
trivial to integrate with web services.
|
||||
|
||||
- Simple interface for building query strings, POST requests, streaming large
|
||||
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
|
||||
etc...
|
||||
- Can send both synchronous and asynchronous requests using the same interface.
|
||||
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
|
||||
to utilize other PSR-7 compatible libraries with Guzzle.
|
||||
- Supports PSR-18, allowing interoperability with other PSR-18 HTTP clients.
|
||||
- Abstracts away the underlying HTTP transport, allowing you to write
|
||||
environment and transport agnostic code; i.e., no hard dependency on cURL,
|
||||
PHP streams, sockets, or non-blocking event loops.
|
||||
- Middleware system allows you to augment and compose client behavior.
|
||||
|
||||
## Installation
|
||||
|
||||
The recommended way to install Guzzle is through
|
||||
[Composer](https://getcomposer.org/).
|
||||
|
||||
```bash
|
||||
composer require guzzlehttp/guzzle
|
||||
```
|
||||
|
||||
## Version Guidance
|
||||
|
||||
| Version | Status | PHP Version |
|
||||
|---------|--------------|--------------|
|
||||
| 8.5 | Latest | >=7.4,<8.7 |
|
||||
| 7.16 | Maintenance | >=7.2.5,<8.7 |
|
||||
| 6.5 | End of Life | >=5.5,<8.0 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```php
|
||||
$client = new \GuzzleHttp\Client();
|
||||
$response = $client->request('GET', 'https://api.example.com/users/123');
|
||||
|
||||
echo $response->getStatusCode(); // 200
|
||||
echo $response->getHeaderLine('content-type'); // 'application/json'
|
||||
echo $response->getBody(); // '{"id": 123, "name": "Ada"}'
|
||||
```
|
||||
|
||||
For more examples, see the [Quick Start](docs/quick-start.md).
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Quick Start](docs/quick-start.md)
|
||||
- [Overview](docs/overview.md)
|
||||
- [Request Options](docs/request-options.md)
|
||||
- [Uploading Data](docs/uploading-data.md)
|
||||
- [Cookies](docs/cookies.md)
|
||||
- [Exceptions](docs/exceptions.md)
|
||||
- [Guzzle and PSR-7](docs/guzzle-and-psr-7.md)
|
||||
- [Handlers](docs/handlers.md)
|
||||
- [Middleware](docs/middleware.md)
|
||||
- [Testing Guzzle Clients](docs/testing-guzzle-clients.md)
|
||||
- [FAQ](docs/faq.md)
|
||||
- [Package Ecosystem](docs/package-ecosystem.md)
|
||||
- [Upgrade Guide](UPGRADING.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
|
||||
We use GitHub issues only to discuss bugs and new features. For support, use
|
||||
[Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle), the
|
||||
[#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on
|
||||
[PHP-HTTP Slack](https://slack.httplug.io/), or
|
||||
[Gitter](https://gitter.im/guzzle/guzzle).
|
||||
|
||||
## 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 by the security maintainers listed in the
|
||||
[Security Policy](https://github.com/guzzle/guzzle/security/policy). Please do
|
||||
not disclose security-related issues publicly until a fix has been announced.
|
||||
|
||||
## License
|
||||
|
||||
Guzzle is made available under the MIT License (MIT). Please see
|
||||
[License File](LICENSE) 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.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
+2785
File diff suppressed because it is too large
Load Diff
+132
@@ -0,0 +1,132 @@
|
||||
{
|
||||
"name": "guzzlehttp/guzzle",
|
||||
"description": "Guzzle is a PHP HTTP client library",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"framework",
|
||||
"http",
|
||||
"rest",
|
||||
"web service",
|
||||
"curl",
|
||||
"client",
|
||||
"HTTP client",
|
||||
"PSR-7",
|
||||
"PSR-18"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
},
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
},
|
||||
{
|
||||
"name": "Jeremy Lindblom",
|
||||
"email": "jeremeamia@gmail.com",
|
||||
"homepage": "https://github.com/jeremeamia"
|
||||
},
|
||||
{
|
||||
"name": "George Mponos",
|
||||
"email": "gmponos@gmail.com",
|
||||
"homepage": "https://github.com/gmponos"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Nyholm",
|
||||
"email": "tobias.nyholm@gmail.com",
|
||||
"homepage": "https://github.com/Nyholm"
|
||||
},
|
||||
{
|
||||
"name": "Márk Sági-Kazár",
|
||||
"email": "mark.sagikazar@gmail.com",
|
||||
"homepage": "https://github.com/sagikazarmark"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Schultze",
|
||||
"email": "webmaster@tubo-world.de",
|
||||
"homepage": "https://github.com/Tobion"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.4 || ^8.0",
|
||||
"ext-json": "*",
|
||||
"guzzlehttp/promises": "^3.1.1",
|
||||
"guzzlehttp/psr7": "^3.5.1",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"symfony/deprecation-contracts": "^2.5 || ^3.0",
|
||||
"symfony/polyfill-php80": "^1.25",
|
||||
"symfony/polyfill-php82": "^1.27"
|
||||
},
|
||||
"require-dev": {
|
||||
"ext-curl": "*",
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"guzzle/client-integration-tests": "4.0.1",
|
||||
"guzzlehttp/test-server": "^1.1",
|
||||
"php-http/message-factory": "^1.1",
|
||||
"phpunit/phpunit": "^9.6.34",
|
||||
"psr/log": "^1.1 || ^2.0 || ^3.0"
|
||||
},
|
||||
"provide": {
|
||||
"psr/http-client-implementation": "1.0"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-curl": "Required for CURL handler support",
|
||||
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
|
||||
"psr/log": "Required for using the Log middleware"
|
||||
},
|
||||
"repositories": [
|
||||
{
|
||||
"type": "package",
|
||||
"package": {
|
||||
"name": "guzzle/client-integration-tests",
|
||||
"version": "v4.0.1",
|
||||
"require": {
|
||||
"guzzlehttp/psr7": "^3.5.1",
|
||||
"php": "^7.4 || ^8.0",
|
||||
"php-http/message": "^1.0 || ^2.0",
|
||||
"phpunit/phpunit": "^9.6.34",
|
||||
"th3n3rd/cartesian-product": "^0.3"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Http\\Client\\Tests\\": "src/"
|
||||
}
|
||||
},
|
||||
"bin": [
|
||||
"bin/http_test_server"
|
||||
],
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/e54cb9d94e3aa5e125dcd7d01bec22db202444ac"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"bamarni/composer-bin-plugin": true
|
||||
},
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": false
|
||||
}
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Auth;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DigestAuth
|
||||
{
|
||||
/**
|
||||
* @var array<string, array{hash: string, sess: bool, rank: int, header: string}>
|
||||
*/
|
||||
private const ALGORITHMS = [
|
||||
'MD5' => ['hash' => 'md5', 'sess' => false, 'rank' => 10, 'header' => 'MD5'],
|
||||
'MD5-SESS' => ['hash' => 'md5', 'sess' => true, 'rank' => 11, 'header' => 'MD5-sess'],
|
||||
'SHA-256' => ['hash' => 'sha256', 'sess' => false, 'rank' => 20, 'header' => 'SHA-256'],
|
||||
'SHA-256-SESS' => ['hash' => 'sha256', 'sess' => true, 'rank' => 21, 'header' => 'SHA-256-sess'],
|
||||
'SHA-512-256' => ['hash' => 'sha512/256', 'sess' => false, 'rank' => 30, 'header' => 'SHA-512-256'],
|
||||
'SHA-512-256-SESS' => ['hash' => 'sha512/256', 'sess' => true, 'rank' => 31, 'header' => 'SHA-512-256-sess'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, true>
|
||||
*/
|
||||
private const DIGEST_CHALLENGE_PARAMETER_NAMES = [
|
||||
'realm' => true,
|
||||
'domain' => true,
|
||||
'nonce' => true,
|
||||
'opaque' => true,
|
||||
'stale' => true,
|
||||
'algorithm' => true,
|
||||
'qop' => true,
|
||||
'charset' => true,
|
||||
'userhash' => true,
|
||||
];
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function selectChallenge(
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): ?DigestChallenge {
|
||||
$selected = null;
|
||||
|
||||
foreach ($response->getHeader('WWW-Authenticate') as $header) {
|
||||
foreach (self::parseAuthenticateHeader($header) as $challenge) {
|
||||
if ($challenge['scheme'] !== 'digest' || $challenge['invalid']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$digest = self::createChallenge($challenge['params']);
|
||||
if ($digest === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($selected === null || $digest->algorithm['rank'] > $selected->algorithm['rank']) {
|
||||
$selected = $digest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $selected;
|
||||
}
|
||||
|
||||
public static function authorizationHeader(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
DigestChallenge $challenge,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
string $cnonce,
|
||||
string $nc = '00000001'
|
||||
): ?string {
|
||||
if ($challenge->algorithm['sess'] && $challenge->qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$uri = $request->getRequestTarget();
|
||||
if ($uri === '') {
|
||||
$uri = '/';
|
||||
}
|
||||
|
||||
foreach ([$username, $challenge->realm, $challenge->nonce, $uri, $cnonce] as $value) {
|
||||
if (!self::isHeaderSafe($value)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if ($challenge->opaque !== null && !self::isHeaderSafe($challenge->opaque)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($challenge->qop !== null && !self::isNonceCount($nc)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hash = $challenge->algorithm['hash'];
|
||||
$ha1 = \hash($hash, $username.':'.$challenge->realm.':'.$password);
|
||||
|
||||
if ($challenge->algorithm['sess']) {
|
||||
$ha1 = \hash($hash, $ha1.':'.$challenge->nonce.':'.$cnonce);
|
||||
}
|
||||
|
||||
$ha2 = \hash($hash, $request->getMethod().':'.$uri);
|
||||
$response = $challenge->qop === null
|
||||
? \hash($hash, $ha1.':'.$challenge->nonce.':'.$ha2)
|
||||
: \hash($hash, $ha1.':'.$challenge->nonce.':'.$nc.':'.$cnonce.':'.$challenge->qop.':'.$ha2);
|
||||
|
||||
if ($challenge->userhash) {
|
||||
$headerUsername = \hash($hash, $username.':'.$challenge->realm);
|
||||
if ($headerUsername === false) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
$headerUsername = $username;
|
||||
}
|
||||
|
||||
$parts = [
|
||||
'username='.self::quote($headerUsername),
|
||||
'realm='.self::quote($challenge->realm),
|
||||
'nonce='.self::quote($challenge->nonce),
|
||||
'uri='.self::quote($uri),
|
||||
'response='.self::quote($response),
|
||||
'algorithm='.$challenge->algorithm['header'],
|
||||
];
|
||||
|
||||
if ($challenge->opaque !== null) {
|
||||
$parts[] = 'opaque='.self::quote($challenge->opaque);
|
||||
}
|
||||
|
||||
if ($challenge->qop !== null) {
|
||||
$parts[] = 'qop='.$challenge->qop;
|
||||
$parts[] = 'nc='.$nc;
|
||||
$parts[] = 'cnonce='.self::quote($cnonce);
|
||||
}
|
||||
|
||||
if ($challenge->userhash) {
|
||||
$parts[] = 'userhash=true';
|
||||
}
|
||||
|
||||
return 'Digest '.\implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{scheme: string, params: array<string, string>, invalid: bool}>
|
||||
*/
|
||||
public static function parseAuthenticateHeader(string $header): array
|
||||
{
|
||||
$length = \strlen($header);
|
||||
$offset = 0;
|
||||
$challenges = [];
|
||||
|
||||
while (true) {
|
||||
self::skipSeparators($header, $offset, $length);
|
||||
if ($offset >= $length) {
|
||||
break;
|
||||
}
|
||||
|
||||
$scheme = self::readToken($header, $offset, $length);
|
||||
if ($scheme === null) {
|
||||
break;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
if (self::skipToken68Challenge($header, $offset, $length)) {
|
||||
$challenges[] = [
|
||||
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||
'params' => [],
|
||||
'invalid' => false,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = [];
|
||||
$invalid = false;
|
||||
|
||||
while ($offset < $length) {
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
if ($offset < $length && $header[$offset] === ',') {
|
||||
if (self::commaStartsNextChallenge($header, $offset + 1, $length)) {
|
||||
if (Psr7\Utils::caselessEquals($scheme, 'Digest')
|
||||
&& self::commaStartsKnownDigestParameterWithoutValue($header, $offset + 1, $length)
|
||||
) {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = self::readToken($header, $offset, $length);
|
||||
if ($name === null) {
|
||||
if ($offset < $length) {
|
||||
$invalid = true;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
if ($offset >= $length || $header[$offset] !== '=') {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
$value = self::readValue($header, $offset, $length);
|
||||
if ($value === null) {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
|
||||
$lowerName = Psr7\Utils::asciiToLower($name);
|
||||
if (\array_key_exists($lowerName, $params)) {
|
||||
$invalid = true;
|
||||
}
|
||||
|
||||
$params[$lowerName] = $value;
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
if ($offset >= $length) {
|
||||
break;
|
||||
}
|
||||
|
||||
if ($header[$offset] !== ',') {
|
||||
$invalid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$challenges[] = [
|
||||
'scheme' => Psr7\Utils::asciiToLower($scheme),
|
||||
'params' => $params,
|
||||
'invalid' => $invalid,
|
||||
];
|
||||
}
|
||||
|
||||
return $challenges;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $params
|
||||
*/
|
||||
private static function createChallenge(array $params): ?DigestChallenge
|
||||
{
|
||||
if (!isset($params['nonce']) || $params['nonce'] === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($params['charset']) && !Psr7\Utils::caselessEquals($params['charset'], 'UTF-8')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$algorithm = self::algorithm($params['algorithm'] ?? null);
|
||||
if ($algorithm === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$qop = self::selectQop($params['qop'] ?? null);
|
||||
if ($qop === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($algorithm['sess'] && $qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$challenge = new DigestChallenge();
|
||||
$challenge->algorithm = $algorithm;
|
||||
$challenge->realm = $params['realm'] ?? '';
|
||||
$challenge->nonce = $params['nonce'];
|
||||
$challenge->opaque = $params['opaque'] ?? null;
|
||||
if (isset($params['domain'])) {
|
||||
$domainAreas = \preg_split('/[ \t]+/', $params['domain']);
|
||||
|
||||
if ($domainAreas === false) {
|
||||
throw new \RuntimeException('Unable to split the Digest domain list: '.\preg_last_error_msg());
|
||||
}
|
||||
|
||||
$challenge->domain = \array_values(\array_filter($domainAreas));
|
||||
} else {
|
||||
$challenge->domain = [];
|
||||
}
|
||||
$challenge->qop = $qop;
|
||||
$challenge->stale = isset($params['stale']) && Psr7\Utils::caselessEquals($params['stale'], 'true');
|
||||
$challenge->userhash = isset($params['userhash']) && Psr7\Utils::caselessEquals($params['userhash'], 'true');
|
||||
|
||||
return $challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{name: string, hash: string, sess: bool, rank: int, header: string}|null
|
||||
*/
|
||||
private static function algorithm(?string $algorithm): ?array
|
||||
{
|
||||
$name = Psr7\Utils::asciiToUpper($algorithm ?? 'MD5');
|
||||
|
||||
if (!isset(self::ALGORITHMS[$name])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$mapped = self::ALGORITHMS[$name];
|
||||
if (!\in_array($mapped['hash'], \hash_algos(), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['name' => $name] + $mapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|false|null
|
||||
*/
|
||||
private static function selectQop(?string $qop)
|
||||
{
|
||||
if ($qop === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$tokens = \array_map(
|
||||
static function (string $token): string {
|
||||
return Psr7\Utils::asciiToLower(\trim($token, " \t"));
|
||||
},
|
||||
\explode(',', $qop)
|
||||
);
|
||||
|
||||
return \in_array('auth', $tokens, true) ? 'auth' : false;
|
||||
}
|
||||
|
||||
private static function quote(string $value): string
|
||||
{
|
||||
return '"'.\strtr($value, [
|
||||
'\\' => '\\\\',
|
||||
'"' => '\\"',
|
||||
]).'"';
|
||||
}
|
||||
|
||||
private static function isHeaderSafe(string $value): bool
|
||||
{
|
||||
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) === 1;
|
||||
}
|
||||
|
||||
private static function isNonceCount(string $nc): bool
|
||||
{
|
||||
// Nonce counts start at one.
|
||||
return $nc !== '00000000' && \preg_match('/^[0-9a-f]{8}$/D', $nc) === 1;
|
||||
}
|
||||
|
||||
private static function commaStartsNextChallenge(string $header, int $offset, int $length): bool
|
||||
{
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
$nextOffset = $offset;
|
||||
$token = self::readToken($header, $nextOffset, $length);
|
||||
if ($token === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $nextOffset, $length);
|
||||
|
||||
return $nextOffset >= $length || $header[$nextOffset] !== '=';
|
||||
}
|
||||
|
||||
private static function commaStartsKnownDigestParameterWithoutValue(string $header, int $offset, int $length): bool
|
||||
{
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
$name = self::readToken($header, $offset, $length);
|
||||
if ($name === null || !isset(self::DIGEST_CHALLENGE_PARAMETER_NAMES[Psr7\Utils::asciiToLower($name)])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
self::skipWhitespace($header, $offset, $length);
|
||||
|
||||
return $offset >= $length || $header[$offset] !== '=';
|
||||
}
|
||||
|
||||
private static function skipToken68Challenge(string $header, int &$offset, int $length): bool
|
||||
{
|
||||
$cursor = $offset;
|
||||
$hasValue = false;
|
||||
while ($cursor < $length && self::isToken68Char($header[$cursor])) {
|
||||
$hasValue = true;
|
||||
++$cursor;
|
||||
}
|
||||
|
||||
while ($cursor < $length && $header[$cursor] === '=') {
|
||||
++$cursor;
|
||||
}
|
||||
|
||||
if (!$hasValue) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$after = $cursor;
|
||||
self::skipWhitespace($header, $after, $length);
|
||||
|
||||
if ($after < $length && $header[$after] !== ',') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$offset = $after;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function skipSeparators(string $header, int &$offset, int $length): void
|
||||
{
|
||||
while ($offset < $length) {
|
||||
$char = $header[$offset];
|
||||
if ($char !== ',' && !self::isWhitespace($char)) {
|
||||
return;
|
||||
}
|
||||
|
||||
++$offset;
|
||||
}
|
||||
}
|
||||
|
||||
private static function skipWhitespace(string $header, int &$offset, int $length): void
|
||||
{
|
||||
while ($offset < $length && self::isWhitespace($header[$offset])) {
|
||||
++$offset;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isWhitespace(string $char): bool
|
||||
{
|
||||
return $char === ' ' || $char === "\t";
|
||||
}
|
||||
|
||||
private static function readToken(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
$start = $offset;
|
||||
while ($offset < $length && self::isTokenChar($header[$offset])) {
|
||||
++$offset;
|
||||
}
|
||||
|
||||
if ($offset === $start) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$token = \substr($header, $start, $offset - $start);
|
||||
|
||||
return $token === false ? null : $token;
|
||||
}
|
||||
|
||||
private static function isTokenChar(string $char): bool
|
||||
{
|
||||
return \strspn($char, "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") === 1;
|
||||
}
|
||||
|
||||
private static function isToken68Char(string $char): bool
|
||||
{
|
||||
return \strspn($char, '-._~+/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') === 1;
|
||||
}
|
||||
|
||||
private static function readValue(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
if ($offset >= $length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($header[$offset] === '"') {
|
||||
return self::readQuotedString($header, $offset, $length);
|
||||
}
|
||||
|
||||
return self::readToken($header, $offset, $length);
|
||||
}
|
||||
|
||||
private static function readQuotedString(string $header, int &$offset, int $length): ?string
|
||||
{
|
||||
++$offset;
|
||||
$value = '';
|
||||
$escaped = false;
|
||||
|
||||
while ($offset < $length) {
|
||||
$char = $header[$offset++];
|
||||
|
||||
if ($escaped) {
|
||||
$value .= $char;
|
||||
$escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '\\') {
|
||||
$escaped = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '"') {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$value .= $char;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Auth;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DigestChallenge
|
||||
{
|
||||
/** @var array{name: string, hash: string, sess: bool, rank: int, header: string} */
|
||||
public array $algorithm;
|
||||
|
||||
public string $realm = '';
|
||||
|
||||
public string $nonce;
|
||||
|
||||
public ?string $opaque = null;
|
||||
|
||||
/** @var list<string> */
|
||||
public array $domain = [];
|
||||
|
||||
public ?string $qop = null;
|
||||
|
||||
public bool $stale = false;
|
||||
|
||||
public bool $userhash = false;
|
||||
}
|
||||
+846
@@ -0,0 +1,846 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Auth\DigestAuth;
|
||||
use GuzzleHttp\Auth\DigestChallenge;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use GuzzleHttp\Psr7\LazyOpenStream;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Applies built-in Basic authentication and handles Digest authentication
|
||||
* challenges.
|
||||
*/
|
||||
final class AuthMiddleware
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const DIGEST_MAX_RETRIES = 2;
|
||||
|
||||
private const CHALLENGE_CACHE_LIMIT = 32;
|
||||
|
||||
/**
|
||||
* Request option carrying nonce counts already spent during a Digest
|
||||
* handshake, so stale retries advance instead of repeating a count.
|
||||
*/
|
||||
private const DIGEST_NONCE_COUNTS_OPTION = '__guzzle_digest_nonce_counts';
|
||||
|
||||
/**
|
||||
* Headers that describe the request payload. A probe with an empty body
|
||||
* must not carry them.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const DIGEST_PROBE_PAYLOAD_HEADERS = [
|
||||
'Transfer-Encoding',
|
||||
'Expect',
|
||||
'Trailer',
|
||||
'Content-Range',
|
||||
'Content-Encoding',
|
||||
'Content-MD5',
|
||||
'Digest',
|
||||
'Content-Digest',
|
||||
'Repr-Digest',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private $nextHandler;
|
||||
|
||||
/**
|
||||
* @var callable(): string
|
||||
*/
|
||||
private $cnonceGenerator;
|
||||
|
||||
private bool $reuseChallenges;
|
||||
|
||||
private ?string $credentialHashSecret = null;
|
||||
|
||||
/**
|
||||
* @var array<string, array{challenge: DigestChallenge, credentials: string, nextNc: int}>
|
||||
*/
|
||||
private array $digestChallenges = [];
|
||||
|
||||
/**
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler
|
||||
* @param (callable(): string)|null $cnonceGenerator
|
||||
*/
|
||||
public function __construct(callable $nextHandler, ?callable $cnonceGenerator = null, bool $reuseChallenges = true)
|
||||
{
|
||||
$this->nextHandler = $nextHandler;
|
||||
$this->cnonceGenerator = $cnonceGenerator ?? static function (): string {
|
||||
return \bin2hex(\random_bytes(16));
|
||||
};
|
||||
$this->reuseChallenges = $reuseChallenges;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$auth = $options['auth'] ?? null;
|
||||
if ($auth === null || $auth === false || $auth === [] || \is_string($auth)) {
|
||||
return ($this->nextHandler)($request, $options);
|
||||
}
|
||||
|
||||
$normalizedAuth = self::normalizeAuth($auth);
|
||||
if ($normalizedAuth === null) {
|
||||
return ($this->nextHandler)($request, $options);
|
||||
}
|
||||
|
||||
[$username, $password, $type] = $normalizedAuth;
|
||||
|
||||
if ($type === 'basic') {
|
||||
return $this->sendBasic($request, $options, $username, $password);
|
||||
}
|
||||
|
||||
return $this->sendDigest($request, $options, $username, $password);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $auth
|
||||
*
|
||||
* @return array{0: string, 1: string, 2: 'basic'|'digest'}|null
|
||||
*/
|
||||
private static function normalizeAuth(
|
||||
#[\SensitiveParameter]
|
||||
array $auth
|
||||
): ?array {
|
||||
$type = 'basic';
|
||||
if (\array_key_exists(2, $auth) && $auth[2] !== null) {
|
||||
if (!\is_string($auth[2])) {
|
||||
throw new InvalidArgumentException('auth type must be a string');
|
||||
}
|
||||
|
||||
$type = Psr7\Utils::asciiToLower($auth[2]);
|
||||
}
|
||||
|
||||
if (!\in_array($type, ['basic', 'digest'], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\array_key_exists(0, $auth) || !\array_key_exists(1, $auth)) {
|
||||
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||
}
|
||||
|
||||
if (!\is_string($auth[0]) || !\is_string($auth[1])) {
|
||||
throw new InvalidArgumentException('auth must contain username and password strings');
|
||||
}
|
||||
|
||||
return [$auth[0], $auth[1], $type];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function sendBasic(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): PromiseInterface {
|
||||
if (\strpos($username, ':') !== false) {
|
||||
throw new InvalidArgumentException('Basic authentication username must not contain a colon');
|
||||
}
|
||||
|
||||
if (\preg_match('/[\x00-\x1F\x7F]/', $username.$password) !== 0) {
|
||||
throw new InvalidArgumentException('Basic authentication credentials must not contain ASCII control characters');
|
||||
}
|
||||
|
||||
unset($options['auth']);
|
||||
|
||||
return ($this->nextHandler)(
|
||||
$request->withHeader('Authorization', 'Basic '.\base64_encode($username.':'.$password)),
|
||||
$options
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function sendDigest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): PromiseInterface {
|
||||
$preemptive = $this->reuseChallenges
|
||||
? $this->preemptiveDigestRequest($request, $username, $password)
|
||||
: null;
|
||||
|
||||
if ($preemptive !== null) {
|
||||
$preemptiveOptions = self::withTemporarySink($options);
|
||||
unset($preemptiveOptions['auth']);
|
||||
|
||||
return ($this->nextHandler)($preemptive, $preemptiveOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $options, $preemptiveOptions, $username, $password) {
|
||||
// Clear on 4xx/5xx other than 401 so non-conformant stale-nonce
|
||||
// errors cannot poison the cache indefinitely.
|
||||
$status = $response->getStatusCode();
|
||||
if ($status >= 400 && $status !== 401) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
return $this->handleDigestResponse($request, $options, $preemptiveOptions, $response, $username, $password, false);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $preemptiveOptions) {
|
||||
return $this->handleDigestRejection($request, $preemptiveOptions, $reason, true);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$probeOptions = self::withTemporarySink($options);
|
||||
unset($probeOptions['auth']);
|
||||
|
||||
[$probeRequest, $bodyWithheld] = self::probeRequest($request, $options);
|
||||
|
||||
if ($bodyWithheld) {
|
||||
// The probe has no payload, so prepare_body must not add Expect
|
||||
// if a custom empty stream has unknown size.
|
||||
$probeOptions[RequestOptions::EXPECT] = false;
|
||||
}
|
||||
|
||||
return ($this->nextHandler)($probeRequest, $probeOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $options, $probeOptions, $username, $password, $bodyWithheld) {
|
||||
return $this->handleDigestResponse($request, $options, $probeOptions, $response, $username, $password, $bodyWithheld);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $probeOptions) {
|
||||
return $this->handleDigestRejection($request, $probeOptions, $reason, false);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private function preemptiveDigestRequest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): ?RequestInterface {
|
||||
try {
|
||||
if ($request->getBody()->getSize() !== 0) {
|
||||
return null;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$entry = $this->digestChallenges[$key] ?? null;
|
||||
if ($entry === null
|
||||
|| $entry['credentials'] !== $this->digestCredentialKey($username, $password)
|
||||
|| !self::challengeCoversRequest($entry['challenge'], $request)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$authorization = DigestAuth::authorizationHeader(
|
||||
$request,
|
||||
$entry['challenge'],
|
||||
$username,
|
||||
$password,
|
||||
($this->cnonceGenerator)(),
|
||||
\sprintf('%08x', $entry['nextNc'])
|
||||
);
|
||||
|
||||
if ($authorization === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
++$this->digestChallenges[$key]['nextNc'];
|
||||
|
||||
return $request->withHeader('Authorization', $authorization);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the unauthenticated probe request for a Digest handshake.
|
||||
*
|
||||
* @return array{0: RequestInterface, 1: bool}
|
||||
*/
|
||||
private static function probeRequest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): array {
|
||||
$probe = $request->withoutHeader('Authorization');
|
||||
|
||||
try {
|
||||
$size = $probe->getBody()->getSize();
|
||||
} catch (\Exception $e) {
|
||||
$size = null;
|
||||
}
|
||||
|
||||
if ($size === 0) {
|
||||
return [$probe, false];
|
||||
}
|
||||
|
||||
$streamFactory = self::requireStreamFactory(
|
||||
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||
);
|
||||
|
||||
$probe = $probe->withBody($streamFactory->createStream(''))
|
||||
->withHeader('Content-Length', '0');
|
||||
|
||||
foreach (self::DIGEST_PROBE_PAYLOAD_HEADERS as $header) {
|
||||
$probe = $probe->withoutHeader($header);
|
||||
}
|
||||
|
||||
return [$probe, true];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ResponseInterface|PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function handleDigestResponse(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
array $probeOptions,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
bool $bodyWithheld
|
||||
) {
|
||||
$status = $response->getStatusCode();
|
||||
|
||||
$previousEntry = null;
|
||||
if ($this->reuseChallenges && $status === 401) {
|
||||
$key = self::digestCacheKey($request);
|
||||
$previousEntry = $key !== null ? ($this->digestChallenges[$key] ?? null) : null;
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
if ($status !== 401) {
|
||||
if ($this->reuseChallenges && $response->hasHeader('Authentication-Info')) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
|
||||
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
|
||||
if ($bodyWithheld && $status !== 407 && !self::isRedirectLikeResponse($response)) {
|
||||
throw new ResponseException(
|
||||
'Digest authentication failed because the server did not issue a challenge; the request was probed without its body',
|
||||
$request,
|
||||
$response
|
||||
);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
$challenge = DigestAuth::selectChallenge($response);
|
||||
if ($challenge === null) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
$retries = $options['__guzzle_digest_retries'] ?? 0;
|
||||
if (!\is_int($retries)) {
|
||||
$retries = 0;
|
||||
}
|
||||
|
||||
if (($retries > 0 && !$challenge->stale) || $retries >= self::DIGEST_MAX_RETRIES) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
try {
|
||||
self::rewindBodyForRetry($request, $bodyWithheld);
|
||||
} catch (\Exception $e) {
|
||||
$response = self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
|
||||
throw new ResponseException(
|
||||
'Digest authentication failed because the request body could not be rewound',
|
||||
$request,
|
||||
$response,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
$nonceCounts = self::digestNonceCountsFromOptions($options);
|
||||
|
||||
if ($previousEntry !== null
|
||||
&& $previousEntry['credentials'] === $this->digestCredentialKey($username, $password)
|
||||
) {
|
||||
self::rememberDigestNonceCount($nonceCounts, $previousEntry['challenge'], $previousEntry['nextNc']);
|
||||
}
|
||||
|
||||
$nc = $challenge->qop === null ? 1 : ($nonceCounts[self::digestNonceCountKey($challenge)] ?? 1);
|
||||
|
||||
$authorization = DigestAuth::authorizationHeader(
|
||||
$request,
|
||||
$challenge,
|
||||
$username,
|
||||
$password,
|
||||
($this->cnonceGenerator)(),
|
||||
\sprintf('%08x', $nc)
|
||||
);
|
||||
|
||||
if ($authorization === null) {
|
||||
return self::restoreOriginalSink($request, $response, $probeOptions);
|
||||
}
|
||||
|
||||
$response->getBody()->close();
|
||||
|
||||
self::rememberDigestNonceCount($nonceCounts, $challenge, $nc + 1);
|
||||
|
||||
$retryOptions = $options;
|
||||
$retryOptions['__guzzle_digest_retries'] = $retries + 1;
|
||||
$retryOptions[self::DIGEST_NONCE_COUNTS_OPTION] = $nonceCounts;
|
||||
$downstreamOptions = $retryOptions;
|
||||
// The nonce-count map only carries handshake state into the retry
|
||||
// recursion; downstream handlers must not observe it.
|
||||
unset($downstreamOptions[self::DIGEST_NONCE_COUNTS_OPTION]);
|
||||
// The caller's delay applies once, before the first Digest leg, not
|
||||
// before each handshake retry.
|
||||
unset($downstreamOptions[RequestOptions::DELAY]);
|
||||
$downstreamOptions = self::withTemporarySink($downstreamOptions);
|
||||
unset($downstreamOptions['auth']);
|
||||
|
||||
$retryRequest = $request->withHeader('Authorization', $authorization);
|
||||
|
||||
return ($this->nextHandler)($retryRequest, $downstreamOptions)->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $retryResponse
|
||||
) use ($retryRequest, $retryOptions, $downstreamOptions, $username, $password, $challenge, $nc) {
|
||||
if ($this->reuseChallenges && self::isCacheableDigestSuccess($retryResponse)) {
|
||||
$this->storeDigestChallenge($retryRequest, $challenge, $username, $password, $nc + 1);
|
||||
}
|
||||
|
||||
return $this->handleDigestResponse($retryRequest, $retryOptions, $downstreamOptions, $retryResponse, $username, $password, false);
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($retryRequest, $downstreamOptions) {
|
||||
return $this->handleDigestRejection($retryRequest, $downstreamOptions, $reason, false);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private static function isCacheableDigestSuccess(ResponseInterface $response): bool
|
||||
{
|
||||
$status = $response->getStatusCode();
|
||||
|
||||
return $status >= 200 && $status < 400 && !$response->hasHeader('Authentication-Info');
|
||||
}
|
||||
|
||||
private function storeDigestChallenge(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
DigestChallenge $challenge,
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password,
|
||||
int $nextNc
|
||||
): void {
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key === null || $challenge->qop === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
unset($this->digestChallenges[$key]);
|
||||
|
||||
if (\count($this->digestChallenges) >= self::CHALLENGE_CACHE_LIMIT) {
|
||||
\array_shift($this->digestChallenges);
|
||||
}
|
||||
|
||||
$this->digestChallenges[$key] = [
|
||||
'challenge' => $challenge,
|
||||
'credentials' => $this->digestCredentialKey($username, $password),
|
||||
'nextNc' => $nextNc,
|
||||
];
|
||||
}
|
||||
|
||||
private function clearDigestChallenge(RequestInterface $request): void
|
||||
{
|
||||
$key = self::digestCacheKey($request);
|
||||
if ($key !== null) {
|
||||
unset($this->digestChallenges[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $options
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private static function digestNonceCountsFromOptions(array $options): array
|
||||
{
|
||||
$counts = $options[self::DIGEST_NONCE_COUNTS_OPTION] ?? [];
|
||||
if (!\is_array($counts)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($counts as $key => $nextNc) {
|
||||
if (\is_string($key) && \is_int($nextNc) && $nextNc > 0 && $nextNc < \PHP_INT_MAX) {
|
||||
$normalized[$key] = $nextNc;
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private static function digestNonceCountKey(DigestChallenge $challenge): string
|
||||
{
|
||||
return \implode("\0", [
|
||||
$challenge->realm,
|
||||
$challenge->nonce,
|
||||
$challenge->qop ?? '',
|
||||
$challenge->algorithm['header'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, int> $counts
|
||||
*/
|
||||
private static function rememberDigestNonceCount(array &$counts, DigestChallenge $challenge, int $nextNc): void
|
||||
{
|
||||
if ($challenge->qop === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$key = self::digestNonceCountKey($challenge);
|
||||
$counts[$key] = \max($counts[$key] ?? 1, $nextNc);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function handleDigestRejection(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
$reason,
|
||||
bool $preemptive
|
||||
): PromiseInterface {
|
||||
if ($this->reuseChallenges && $reason instanceof ResponseException) {
|
||||
$response = $reason->getResponse();
|
||||
|
||||
if ($response->getStatusCode() === 401
|
||||
|| $response->hasHeader('Authentication-Info')
|
||||
|| ($preemptive && $response->getStatusCode() >= 400)
|
||||
) {
|
||||
$this->clearDigestChallenge($request);
|
||||
}
|
||||
}
|
||||
|
||||
return self::restoreOriginalSinkOnRejection($options, $reason);
|
||||
}
|
||||
|
||||
private static function digestCacheKey(RequestInterface $request): ?string
|
||||
{
|
||||
$uri = $request->getUri();
|
||||
$scheme = Psr7\Utils::asciiToLower($uri->getScheme());
|
||||
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||
|
||||
if (($scheme !== 'http' && $scheme !== 'https') || $host === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80);
|
||||
|
||||
return $scheme.'://'.$host.':'.$port.'|'.HostIdentity::canonicalHostHeader($request->getHeaderLine('Host'));
|
||||
}
|
||||
|
||||
private function digestCredentialKey(
|
||||
string $username,
|
||||
#[\SensitiveParameter]
|
||||
string $password
|
||||
): string {
|
||||
if ($this->credentialHashSecret === null) {
|
||||
$this->credentialHashSecret = \random_bytes(32);
|
||||
}
|
||||
|
||||
return \hash_hmac('sha256', $username."\0".$password, $this->credentialHashSecret);
|
||||
}
|
||||
|
||||
private static function challengeCoversRequest(DigestChallenge $challenge, RequestInterface $request): bool
|
||||
{
|
||||
if ($challenge->domain === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$target = $request->getRequestTarget();
|
||||
foreach ($challenge->domain as $space) {
|
||||
$prefix = self::protectionSpacePath($space, $request);
|
||||
if ($prefix !== null && \str_starts_with($target, $prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function protectionSpacePath(string $space, RequestInterface $request): ?string
|
||||
{
|
||||
if ($space === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($space[0] === '/') {
|
||||
return $space;
|
||||
}
|
||||
|
||||
try {
|
||||
// A server must not be able to raise the psr7 host deprecation.
|
||||
$uri = (new Psr7\ErrorScope(\E_USER_DEPRECATED))->run(static function () use ($space): Psr7\Uri {
|
||||
return new Psr7\Uri($space);
|
||||
});
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (Psr7\UriComparator::isCrossOrigin($uri, self::effectiveRequestUri($request))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$path = $uri->getPath();
|
||||
$prefix = $path === '' ? '/' : $path;
|
||||
|
||||
if ($uri->getQuery() !== '') {
|
||||
$prefix .= '?'.$uri->getQuery();
|
||||
}
|
||||
|
||||
return $prefix;
|
||||
}
|
||||
|
||||
private static function effectiveRequestUri(RequestInterface $request): UriInterface
|
||||
{
|
||||
$uri = $request->getUri();
|
||||
$host = $request->getHeaderLine('Host');
|
||||
if ($host === '' || Psr7\Utils::caselessEquals($host, $uri->getHost())) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
try {
|
||||
$authority = new Psr7\Uri('//'.$host);
|
||||
if ($authority->getHost() === '') {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
return $uri->withHost($authority->getHost())->withPort($authority->getPort());
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return $uri;
|
||||
}
|
||||
}
|
||||
|
||||
private static function isRedirectLikeResponse(ResponseInterface $response): bool
|
||||
{
|
||||
return $response->hasHeader('Location')
|
||||
&& \in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true);
|
||||
}
|
||||
|
||||
private static function rewindBodyForRetry(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
bool $bodyWithheld
|
||||
): void {
|
||||
$body = $request->getBody();
|
||||
|
||||
if (!$bodyWithheld) {
|
||||
try {
|
||||
if ($body->getSize() === 0) {
|
||||
return;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// Fall through to the standard rewind path.
|
||||
}
|
||||
|
||||
Psr7\Message::rewindBody($request);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($body->isSeekable()) {
|
||||
$body->rewind();
|
||||
}
|
||||
}
|
||||
|
||||
private static function withTemporarySink(
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): array {
|
||||
// The 'stream' option is deliberately not checked here: the cURL
|
||||
// handlers do not support streaming and write each leg to the sink,
|
||||
// so a configured sink always needs challenge-body protection.
|
||||
if (!isset($options[RequestOptions::SINK])) {
|
||||
return $options;
|
||||
}
|
||||
|
||||
$streamFactory = self::requireStreamFactory(
|
||||
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
|
||||
);
|
||||
|
||||
$options['__guzzle_auth_original_sink'] = $options[RequestOptions::SINK];
|
||||
$options[RequestOptions::SINK] = $streamFactory->createStreamFromResource(
|
||||
Psr7\Utils::tryFopen('php://temp', 'w+')
|
||||
);
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
private static function restoreOriginalSink(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): ResponseInterface {
|
||||
if (!\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
try {
|
||||
$source = $response->getBody();
|
||||
if ($source->isSeekable()) {
|
||||
$source->rewind();
|
||||
}
|
||||
|
||||
$target = self::streamForOriginalSink($options['__guzzle_auth_original_sink']);
|
||||
|
||||
Psr7\Utils::copyToStream($source, $target);
|
||||
|
||||
if ($target->isSeekable()) {
|
||||
$target->rewind();
|
||||
}
|
||||
|
||||
return $response->withBody($target);
|
||||
} catch (\Exception $e) {
|
||||
throw new ResponseException(
|
||||
$e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body',
|
||||
$request,
|
||||
$response,
|
||||
$e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private static function restoreOriginalSinkOnRejection(
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
): PromiseInterface {
|
||||
if (!$reason instanceof ResponseException || !\array_key_exists('__guzzle_auth_original_sink', $options)) {
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
|
||||
try {
|
||||
$response = self::restoreOriginalSink($reason->getRequest(), $reason->getResponse(), $options);
|
||||
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($reason->withResponse($response));
|
||||
} catch (\Throwable $e) {
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return P\Create::rejectionFor($e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sink
|
||||
*/
|
||||
private static function streamForOriginalSink($sink): StreamInterface
|
||||
{
|
||||
if (\is_string($sink)) {
|
||||
return new LazyOpenStream($sink, 'w+');
|
||||
}
|
||||
|
||||
if (\is_resource($sink)) {
|
||||
return self::streamForResourceSink(Psr7\Utils::streamFor($sink));
|
||||
}
|
||||
|
||||
if (!$sink instanceof StreamInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'sink must be a resource, string, or %s',
|
||||
StreamInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return Psr7\Utils::streamFor($sink);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorates a caller-owned sink stream so that closing the response body
|
||||
* detaches Guzzle's wrapper without closing the original PHP resource.
|
||||
*/
|
||||
private static function streamForResourceSink(StreamInterface $stream): StreamInterface
|
||||
{
|
||||
return Psr7\FnStream::decorate($stream, [
|
||||
'close' => static function () use ($stream): void {
|
||||
$stream->detach();
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $factory
|
||||
*/
|
||||
private static function requireStreamFactory($factory): StreamFactoryInterface
|
||||
{
|
||||
if (!$factory instanceof StreamFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::STREAM_FACTORY,
|
||||
StreamFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return $factory;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
|
||||
final class BodySummarizer implements BodySummarizerInterface
|
||||
{
|
||||
private ?int $truncateAt;
|
||||
|
||||
public function __construct(?int $truncateAt = null)
|
||||
{
|
||||
$this->truncateAt = $truncateAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a summarized message body.
|
||||
*/
|
||||
public function summarize(MessageInterface $message): ?string
|
||||
{
|
||||
try {
|
||||
return Psr7\Message::bodySummary($message, $this->truncateAt);
|
||||
} catch (\Exception $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
|
||||
interface BodySummarizerInterface
|
||||
{
|
||||
/**
|
||||
* Returns a summarized message body.
|
||||
*/
|
||||
public function summarize(MessageInterface $message): ?string;
|
||||
}
|
||||
+1716
File diff suppressed because it is too large
Load Diff
+370
@@ -0,0 +1,370 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJarInterface;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriFactoryInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Client interface for sending HTTP requests.
|
||||
*/
|
||||
interface ClientInterface
|
||||
{
|
||||
/**
|
||||
* The Guzzle major version.
|
||||
*/
|
||||
public const MAJOR_VERSION = 8;
|
||||
|
||||
/**
|
||||
* Send an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply to the given request and to the transfer.
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function send(RequestInterface $request, array $options = []): ResponseInterface;
|
||||
|
||||
/**
|
||||
* Asynchronously send an HTTP request.
|
||||
*
|
||||
* @param RequestInterface $request Request to send
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply to the given request and to the transfer.
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
|
||||
|
||||
/**
|
||||
* Create and send an HTTP request.
|
||||
*
|
||||
* Use an absolute path to override the base path of the client, or a
|
||||
* relative path to append to the base path of the client. The URL can
|
||||
* contain the query string as well.
|
||||
*
|
||||
* @param string $method HTTP method.
|
||||
* @param string|UriInterface $uri URI object or string.
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply.
|
||||
*
|
||||
* @throws GuzzleException
|
||||
*/
|
||||
public function request(string $method, $uri, array $options = []): ResponseInterface;
|
||||
|
||||
/**
|
||||
* Create and send an asynchronous HTTP request.
|
||||
*
|
||||
* Use an absolute path to override the base path of the client, or a
|
||||
* relative path to append to the base path of the client. The URL can
|
||||
* contain the query string as well.
|
||||
*
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI object or string.
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options Request options to apply.
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
|
||||
}
|
||||
+1315
File diff suppressed because it is too large
Load Diff
+452
@@ -0,0 +1,452 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\HostIdentity;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Cookie jar that stores cookies as an array
|
||||
*/
|
||||
class CookieJar implements CookieJarInterface
|
||||
{
|
||||
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
|
||||
private const MAX_SET_COOKIE_FIELDS = 50;
|
||||
private const MAX_REQUEST_COOKIES = 150;
|
||||
private const MAX_COOKIE_HEADER_LENGTH = 8190;
|
||||
|
||||
/**
|
||||
* @var SetCookie[] Loaded cookie data
|
||||
*/
|
||||
private array $cookies = [];
|
||||
|
||||
private bool $strictMode;
|
||||
|
||||
/**
|
||||
* @param bool $strictMode Set to true to throw exceptions when invalid
|
||||
* cookies are added to the cookie jar.
|
||||
* @param array $cookieArray Array of SetCookie objects or a hash of
|
||||
* arrays that can be used with the SetCookie
|
||||
* constructor
|
||||
*/
|
||||
public function __construct(
|
||||
bool $strictMode = false,
|
||||
#[\SensitiveParameter]
|
||||
array $cookieArray = []
|
||||
) {
|
||||
$this->strictMode = $strictMode;
|
||||
|
||||
foreach ($cookieArray as $cookie) {
|
||||
if (!$cookie instanceof SetCookie) {
|
||||
$cookie = new SetCookie($cookie);
|
||||
}
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new Cookie jar from an associative array and domain.
|
||||
*
|
||||
* @param array $cookies Cookies to create the jar from
|
||||
* @param string $domain Domain to set the cookies to
|
||||
*/
|
||||
public static function fromArray(
|
||||
#[\SensitiveParameter]
|
||||
array $cookies,
|
||||
string $domain
|
||||
): self {
|
||||
$cookieJar = new self();
|
||||
foreach ($cookies as $name => $value) {
|
||||
if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) {
|
||||
throw new \InvalidArgumentException('Cookie value must be scalar or stringable');
|
||||
}
|
||||
|
||||
$cookieJar->setCookie(new SetCookie([
|
||||
'Domain' => $domain,
|
||||
'Name' => (string) $name,
|
||||
'Value' => (string) $value,
|
||||
'Discard' => true,
|
||||
]));
|
||||
}
|
||||
|
||||
return $cookieJar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate if this cookie should be persisted to storage
|
||||
* that survives between requests.
|
||||
*
|
||||
* @param SetCookie $cookie Being evaluated.
|
||||
* @param bool $allowSessionCookies If we should persist session cookies
|
||||
*/
|
||||
public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
|
||||
{
|
||||
if ($cookie->getExpires() || $allowSessionCookies) {
|
||||
if (!$cookie->getDiscard()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds and returns the cookie based on the name
|
||||
*
|
||||
* @param string $name cookie name to search for
|
||||
*
|
||||
* @return SetCookie|null cookie that was found or null if not found
|
||||
*/
|
||||
public function getCookieByName(string $name): ?SetCookie
|
||||
{
|
||||
foreach ($this->cookies as $cookie) {
|
||||
if ($cookie->getName() === $name) {
|
||||
return $cookie;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return \array_map(static function (SetCookie $cookie): array {
|
||||
return $cookie->toArray();
|
||||
}, $this->getIterator()->getArrayCopy());
|
||||
}
|
||||
|
||||
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
|
||||
{
|
||||
if ($domain === null) {
|
||||
$this->cookies = [];
|
||||
|
||||
return;
|
||||
} elseif ($path === null) {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($domain): bool {
|
||||
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
|
||||
}
|
||||
);
|
||||
} elseif ($name === null) {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($path, $domain): bool {
|
||||
return !($cookie->getDomain() !== null
|
||||
&& $cookie->matchesPath($path)
|
||||
&& $cookie->matchesDomain($domain));
|
||||
}
|
||||
);
|
||||
} else {
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie) use ($path, $domain, $name): bool {
|
||||
return !($cookie->getDomain() !== null
|
||||
&& $cookie->getName() === $name
|
||||
&& $cookie->matchesPath($path)
|
||||
&& $cookie->matchesDomain($domain));
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function clearSessionCookies(): void
|
||||
{
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $cookie): bool {
|
||||
return !$cookie->getDiscard() && $cookie->getExpires();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public function setCookie(
|
||||
#[\SensitiveParameter]
|
||||
SetCookie $cookie
|
||||
): bool {
|
||||
// If the name string is empty (but not 0), ignore the set-cookie
|
||||
// string entirely.
|
||||
$name = $cookie->getName();
|
||||
if (!$name && $name !== '0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only allow cookies with set and valid domain, name, value
|
||||
$result = $cookie->validate();
|
||||
if ($result !== true) {
|
||||
if ($this->strictMode) {
|
||||
throw new \RuntimeException('Invalid cookie: '.$result);
|
||||
}
|
||||
$this->removeCookieIfEmpty($cookie);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$maxAge = $cookie->getMaxAge();
|
||||
if (($maxAge !== null && $maxAge <= 0) || $cookie->isExpired()) {
|
||||
if ($cookie->getDomain() !== null) {
|
||||
$this->removeCookie($cookie);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Resolve conflicts with previously set cookies
|
||||
$replaced = false;
|
||||
foreach ($this->cookies as $i => $c) {
|
||||
// Two cookies are identical, when their path, and domain are
|
||||
// identical.
|
||||
if ($c->getPath() !== $cookie->getPath()
|
||||
|| $c->getDomain() !== $cookie->getDomain()
|
||||
|| $c->getHostOnly() !== $cookie->getHostOnly()
|
||||
|| $c->getName() !== $cookie->getName()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// An expired cookie is gone, so it must not lend its position
|
||||
if ($c->isExpired()) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// A stored cookie can be mutated into a duplicate, so drop later matches
|
||||
if ($replaced) {
|
||||
unset($this->cookies[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Replace the old cookie in place when its value, expiry or flags
|
||||
// changed, so it keeps its position among the other cookies
|
||||
if ($cookie->getValue() !== $c->getValue()
|
||||
|| $cookie->getExpires() !== $c->getExpires()
|
||||
|| $cookie->getDiscard() !== $c->getDiscard()
|
||||
|| $cookie->getSecure() !== $c->getSecure()
|
||||
|| $cookie->getHttpOnly() !== $c->getHttpOnly()
|
||||
) {
|
||||
$this->cookies[$i] = $cookie;
|
||||
$replaced = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// The cookie exists, so no need to continue
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$replaced) {
|
||||
$this->cookies[] = $cookie;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return \count($this->cookies);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \ArrayIterator<int, SetCookie>
|
||||
*/
|
||||
public function getIterator(): \ArrayIterator
|
||||
{
|
||||
return new \ArrayIterator(\array_values($this->cookies));
|
||||
}
|
||||
|
||||
public function extractCookies(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): void {
|
||||
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
|
||||
$uri = $request->getUri();
|
||||
$requestHost = HostIdentity::canonicalHost($uri->getHost());
|
||||
$secure = $uri->getScheme() === 'https';
|
||||
$accepted = 0;
|
||||
|
||||
foreach ($cookieHeader as $cookie) {
|
||||
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sc = SetCookie::fromString($cookie);
|
||||
$domain = $sc->getDomain();
|
||||
if ($domain === null || $domain === '') {
|
||||
$sc->setDomain($requestHost);
|
||||
$sc->setHostOnly(true);
|
||||
} else {
|
||||
$sc->setHostOnly(false);
|
||||
}
|
||||
if (0 !== \strpos($sc->getPath(), '/')) {
|
||||
$sc->setPath($this->getCookiePathFromRequest($request));
|
||||
}
|
||||
if (!$sc->matchesDomain($requestHost)) {
|
||||
continue;
|
||||
}
|
||||
if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) {
|
||||
continue;
|
||||
}
|
||||
$prefixName = Psr7\Utils::asciiToLower((string) $sc->getName());
|
||||
if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) {
|
||||
continue;
|
||||
}
|
||||
if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) {
|
||||
continue;
|
||||
}
|
||||
// Note: At this point `$sc->getDomain()` being a public suffix should
|
||||
// be rejected, but we don't want to pull in the full PSL dependency.
|
||||
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function overlaysSecureCookie(SetCookie $cookie): bool
|
||||
{
|
||||
foreach ($this->cookies as $stored) {
|
||||
if (self::isSecureCookieOverlay($cookie, $stored)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool
|
||||
{
|
||||
if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$domain = $cookie->getDomain();
|
||||
$storedDomain = $stored->getDomain();
|
||||
if ($domain === null || $storedDomain === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $stored->matchesPath($cookie->getPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot
|
||||
* distinguish an absent Path attribute from a defaulted path.
|
||||
*/
|
||||
private static function hasPathAttribute(string $header): bool
|
||||
{
|
||||
$parts = \explode(';', $header);
|
||||
\array_shift($parts);
|
||||
|
||||
foreach ($parts as $part) {
|
||||
$separator = \strpos($part, '=');
|
||||
if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes cookie path following RFC 6265 section 5.1.4
|
||||
*
|
||||
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
|
||||
*/
|
||||
private function getCookiePathFromRequest(RequestInterface $request): string
|
||||
{
|
||||
$uriPath = $request->getUri()->getPath();
|
||||
if ('' === $uriPath) {
|
||||
return '/';
|
||||
}
|
||||
if (0 !== \strpos($uriPath, '/')) {
|
||||
return '/';
|
||||
}
|
||||
if ('/' === $uriPath) {
|
||||
return '/';
|
||||
}
|
||||
$lastSlashPos = \strrpos($uriPath, '/');
|
||||
if (0 === $lastSlashPos || false === $lastSlashPos) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
return \substr($uriPath, 0, $lastSlashPos);
|
||||
}
|
||||
|
||||
public function withCookieHeader(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): RequestInterface {
|
||||
$values = [];
|
||||
$count = 0;
|
||||
$headerLength = 8;
|
||||
$uri = $request->getUri();
|
||||
$scheme = $uri->getScheme();
|
||||
$host = HostIdentity::canonicalHost($uri->getHost());
|
||||
$path = $uri->getPath() ?: '/';
|
||||
|
||||
foreach ($this->cookies as $cookie) {
|
||||
if ($cookie->getDomain() !== null
|
||||
&& $cookie->matchesPath($path)
|
||||
&& $cookie->matchesDomain($host)
|
||||
&& !$cookie->isExpired()
|
||||
&& (!$cookie->getSecure() || $scheme === 'https')
|
||||
) {
|
||||
$name = (string) $cookie->getName();
|
||||
$value = (string) $cookie->getValue();
|
||||
$separatorLength = $values === [] ? 0 : 2;
|
||||
$valueLength = \strlen($name) + 1 + \strlen($value);
|
||||
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
|
||||
break;
|
||||
}
|
||||
|
||||
$values[\strlen($cookie->getPath())][] = $name.'='.$value;
|
||||
$headerLength += $separatorLength + $valueLength;
|
||||
if (++$count === self::MAX_REQUEST_COOKIES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Longer paths first, then creation order, as in RFC 6265 section 5.4,
|
||||
// sorted after the limits so later cookies cannot crowd out older ones
|
||||
\krsort($values);
|
||||
|
||||
return $values
|
||||
? $request->withHeader('Cookie', \implode('; ', \array_merge(...$values)))
|
||||
: $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* If a cookie already exists and the server asks to set it again with a
|
||||
* null value, the cookie must be deleted.
|
||||
*/
|
||||
private function removeCookieIfEmpty(SetCookie $cookie): void
|
||||
{
|
||||
$cookieValue = $cookie->getValue();
|
||||
if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
|
||||
$this->removeCookie($cookie);
|
||||
}
|
||||
}
|
||||
|
||||
private function removeCookie(SetCookie $cookie): void
|
||||
{
|
||||
$this->cookies = \array_filter(
|
||||
$this->cookies,
|
||||
static function (SetCookie $stored) use ($cookie): bool {
|
||||
return !($stored->getName() === $cookie->getName()
|
||||
&& $stored->getPath() === $cookie->getPath()
|
||||
&& $stored->getDomain() === $cookie->getDomain()
|
||||
&& $stored->getHostOnly() === $cookie->getHostOnly());
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Stores HTTP cookies.
|
||||
*
|
||||
* It extracts cookies from HTTP requests, and returns them in HTTP responses.
|
||||
* CookieJarInterface instances automatically expire contained cookies when
|
||||
* necessary. Subclasses are also responsible for storing and retrieving
|
||||
* cookies from a file, database, etc.
|
||||
*
|
||||
* @see https://docs.python.org/2/library/cookielib.html Inspiration
|
||||
*
|
||||
* @extends \IteratorAggregate<SetCookie>
|
||||
*/
|
||||
interface CookieJarInterface extends \Countable, \IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Create a request with added cookie headers.
|
||||
*
|
||||
* If no matching cookies are found in the cookie jar, then no Cookie
|
||||
* header is added to the request and the same request is returned.
|
||||
*
|
||||
* @param RequestInterface $request Request object to modify.
|
||||
*
|
||||
* @return RequestInterface returns the modified request.
|
||||
*/
|
||||
public function withCookieHeader(RequestInterface $request): RequestInterface;
|
||||
|
||||
/**
|
||||
* Extract cookies from an HTTP response and store them in the CookieJar.
|
||||
*
|
||||
* @param RequestInterface $request Request that was sent
|
||||
* @param ResponseInterface $response Response that was received
|
||||
*/
|
||||
public function extractCookies(RequestInterface $request, ResponseInterface $response): void;
|
||||
|
||||
/**
|
||||
* Sets a cookie in the cookie jar.
|
||||
*
|
||||
* @param SetCookie $cookie Cookie to set.
|
||||
*
|
||||
* @return bool Returns true on success or false on failure
|
||||
*/
|
||||
public function setCookie(SetCookie $cookie): bool;
|
||||
|
||||
/**
|
||||
* Remove cookies currently held in the cookie jar.
|
||||
*
|
||||
* Invoking this method without arguments will empty the whole cookie jar.
|
||||
* If given a $domain argument only cookies belonging to that domain will
|
||||
* be removed. If given a $domain and $path argument, cookies belonging to
|
||||
* the specified path within that domain are removed. If given all three
|
||||
* arguments, then the cookie with the specified name, path and domain is
|
||||
* removed.
|
||||
*
|
||||
* @param string|null $domain Clears cookies matching a domain
|
||||
* @param string|null $path Clears cookies matching a domain and path
|
||||
* @param string|null $name Clears cookies matching a domain, path, and name
|
||||
*/
|
||||
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void;
|
||||
|
||||
/**
|
||||
* Discard all sessions cookies.
|
||||
*
|
||||
* Removes cookies that don't have an expire field or a have a discard
|
||||
* field set to true. To be called when the user agent shuts down according
|
||||
* to RFC 2965.
|
||||
*/
|
||||
public function clearSessionCookies(): void;
|
||||
|
||||
/**
|
||||
* Converts the cookie jar to an array.
|
||||
*/
|
||||
public function toArray(): array;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
|
||||
/**
|
||||
* Persists non-session cookies using a JSON formatted file
|
||||
*/
|
||||
class FileCookieJar extends CookieJar
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var string filename
|
||||
*/
|
||||
private string $filename;
|
||||
|
||||
/**
|
||||
* @var bool Control whether to persist session cookies or not.
|
||||
*/
|
||||
private bool $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* @var bool Whether to save the cookie jar on destruction.
|
||||
*
|
||||
* Disabled by __wakeup() to prevent FileCookieJar from being used as a
|
||||
* PHP object injection file-write gadget when an application unserializes
|
||||
* attacker-controlled data.
|
||||
*/
|
||||
private bool $autoSave = false;
|
||||
|
||||
/**
|
||||
* Create a new FileCookieJar object
|
||||
*
|
||||
* @param string $cookieFile File to store the cookie data
|
||||
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||
* in the cookie jar.
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be loaded or is invalid
|
||||
*/
|
||||
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->filename = $cookieFile;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
|
||||
if (\file_exists($cookieFile)) {
|
||||
$this->load($cookieFile);
|
||||
}
|
||||
|
||||
$this->autoSave = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the file when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->autoSave) {
|
||||
$this->save($this->filename);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable automatic persistence after unserialization.
|
||||
*/
|
||||
public function __wakeup(): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the cookies to a file.
|
||||
*
|
||||
* @param string $filename File to save
|
||||
*
|
||||
* @throws \RuntimeException if the cookie data cannot be encoded or the
|
||||
* file cannot be written
|
||||
*/
|
||||
public function save(string $filename): void
|
||||
{
|
||||
$json = [];
|
||||
/** @var SetCookie $cookie */
|
||||
foreach ($this as $cookie) {
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$data = $cookie->toArray();
|
||||
$data['HostOnly'] = $cookie->getHostOnly();
|
||||
$json[] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||
}
|
||||
|
||||
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
|
||||
throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename)));
|
||||
}
|
||||
|
||||
// Best-effort: restrict the cookie file to the owner so persisted
|
||||
// cookies are not world-readable.
|
||||
@\chmod($filename, 0600);
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cookies from a JSON formatted file.
|
||||
*
|
||||
* Old cookies are kept unless overwritten by newly loaded ones.
|
||||
* Cookie records are constructed before any are passed to setCookie().
|
||||
*
|
||||
* @param string $filename Cookie file to load.
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be loaded or is invalid
|
||||
*/
|
||||
public function load(string $filename): void
|
||||
{
|
||||
$json = \file_get_contents($filename);
|
||||
if (false === $json) {
|
||||
throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename)));
|
||||
}
|
||||
if ($json === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename));
|
||||
|
||||
try {
|
||||
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
|
||||
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
$cookies = [];
|
||||
foreach ($data as $cookie) {
|
||||
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$cookies[] = new SetCookie($cookie);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($cookies as $cookie) {
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* Persists cookies in the client session
|
||||
*/
|
||||
class SessionCookieJar extends CookieJar
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var string session key
|
||||
*/
|
||||
private string $sessionKey;
|
||||
|
||||
/**
|
||||
* @var bool Control whether to persist session cookies or not.
|
||||
*/
|
||||
private bool $storeSessionCookies;
|
||||
|
||||
/**
|
||||
* @var bool Whether to save the cookie jar on destruction.
|
||||
*
|
||||
* Disabled by __wakeup() to prevent SessionCookieJar from being used as a
|
||||
* PHP object injection $_SESSION-write gadget when an application
|
||||
* unserializes attacker-controlled data.
|
||||
*/
|
||||
private bool $autoSave = false;
|
||||
|
||||
/**
|
||||
* Create a new SessionCookieJar object
|
||||
*
|
||||
* @param string $sessionKey Session key name to store the cookie
|
||||
* data in session
|
||||
* @param bool $storeSessionCookies Set to true to store session cookies
|
||||
* in the cookie jar.
|
||||
*
|
||||
* @throws \RuntimeException if the session contains invalid cookie data
|
||||
*/
|
||||
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->sessionKey = $sessionKey;
|
||||
$this->storeSessionCookies = $storeSessionCookies;
|
||||
$this->load();
|
||||
$this->autoSave = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves cookies to session when shutting down
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
if ($this->autoSave) {
|
||||
$this->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable automatic persistence after unserialization.
|
||||
*/
|
||||
public function __wakeup(): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->autoSave = false;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Save cookies to the client session.
|
||||
*
|
||||
* @throws \RuntimeException if the cookie data cannot be encoded
|
||||
*/
|
||||
public function save(): void
|
||||
{
|
||||
$json = [];
|
||||
/** @var SetCookie $cookie */
|
||||
foreach ($this as $cookie) {
|
||||
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
|
||||
$data = $cookie->toArray();
|
||||
$data['HostOnly'] = $cookie->getHostOnly();
|
||||
$json[] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$json = \json_encode($json, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
|
||||
}
|
||||
|
||||
$_SESSION[$this->sessionKey] = $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load cookies from the client session.
|
||||
*
|
||||
* @throws \RuntimeException if the session contains invalid cookie data
|
||||
*/
|
||||
protected function load(): void
|
||||
{
|
||||
if (!isset($_SESSION[$this->sessionKey])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$message = 'Invalid cookie data';
|
||||
$json = $_SESSION[$this->sessionKey];
|
||||
if (!\is_string($json)) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
|
||||
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
|
||||
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
$cookies = [];
|
||||
foreach ($data as $cookie) {
|
||||
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
|
||||
throw new \RuntimeException($message);
|
||||
}
|
||||
|
||||
try {
|
||||
$cookies[] = new SetCookie($cookie);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new \RuntimeException($message, 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($cookies as $cookie) {
|
||||
$this->setCookie($cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
+601
@@ -0,0 +1,601 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Cookie;
|
||||
|
||||
use GuzzleHttp\HostIdentity;
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* Set-Cookie object
|
||||
*/
|
||||
class SetCookie
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private const DEFAULTS = [
|
||||
'Name' => null,
|
||||
'Value' => null,
|
||||
'Domain' => null,
|
||||
'Path' => '/',
|
||||
'Max-Age' => null,
|
||||
'Expires' => null,
|
||||
'Secure' => false,
|
||||
'Discard' => false,
|
||||
'HttpOnly' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array Cookie data
|
||||
*/
|
||||
private array $data;
|
||||
|
||||
/**
|
||||
* @var bool Whether this cookie was set without a Domain attribute.
|
||||
*/
|
||||
private bool $hostOnly = false;
|
||||
|
||||
/**
|
||||
* Create a new SetCookie object from a string.
|
||||
*
|
||||
* @param string $cookie Set-Cookie header string
|
||||
*/
|
||||
public static function fromString(
|
||||
#[\SensitiveParameter]
|
||||
string $cookie
|
||||
): self {
|
||||
// Create the default return array
|
||||
$data = self::DEFAULTS;
|
||||
// Explode the cookie string using a series of semicolons
|
||||
$pieces = \array_filter(\array_map(static function (string $piece): string {
|
||||
return \trim($piece, " \t");
|
||||
}, \explode(';', $cookie)));
|
||||
// The name of the cookie (first kvp) must exist and include an equal sign.
|
||||
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
// Add the cookie pieces into the parsed data array
|
||||
foreach ($pieces as $part) {
|
||||
$cookieParts = \explode('=', $part, 2);
|
||||
$key = \trim($cookieParts[0], " \t");
|
||||
$value = isset($cookieParts[1])
|
||||
? \trim($cookieParts[1], " \t")
|
||||
: true;
|
||||
|
||||
// Only check for non-cookies when cookies have been found
|
||||
if (!isset($data['Name'])) {
|
||||
$data['Name'] = $key;
|
||||
$data['Value'] = $value;
|
||||
} else {
|
||||
foreach (\array_keys(self::DEFAULTS) as $search) {
|
||||
if (Psr7\Utils::caselessEquals($search, $key)) {
|
||||
if ($search === 'Max-Age') {
|
||||
if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||
$maxAge = self::parseNumericInteger($value);
|
||||
if ($maxAge !== null) {
|
||||
$data[$search] = $maxAge;
|
||||
}
|
||||
}
|
||||
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
|
||||
if ($value) {
|
||||
$data[$search] = true;
|
||||
}
|
||||
} elseif (\is_string($value)) {
|
||||
$data[$search] = $value;
|
||||
}
|
||||
continue 2;
|
||||
}
|
||||
}
|
||||
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
|
||||
continue;
|
||||
}
|
||||
$data[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// Max-Age takes precedence over Expires, RFC 6265 section 5.3
|
||||
if ($data['Max-Age'] !== null) {
|
||||
$data['Expires'] = null;
|
||||
}
|
||||
|
||||
return new self($data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data Array of cookie data provided by a Cookie parser
|
||||
*/
|
||||
public function __construct(
|
||||
#[\SensitiveParameter]
|
||||
array $data = []
|
||||
) {
|
||||
$this->data = self::DEFAULTS;
|
||||
self::validateFieldTypes($data);
|
||||
|
||||
if (\array_key_exists('HostOnly', $data)) {
|
||||
$this->setHostOnly($data['HostOnly']);
|
||||
unset($data['HostOnly']);
|
||||
}
|
||||
|
||||
if (isset($data['Name'])) {
|
||||
$this->setName($data['Name']);
|
||||
}
|
||||
|
||||
if (isset($data['Value'])) {
|
||||
$this->setValue($data['Value']);
|
||||
}
|
||||
|
||||
if (isset($data['Domain'])) {
|
||||
$this->setDomain($data['Domain']);
|
||||
}
|
||||
|
||||
if (isset($data['Path'])) {
|
||||
$this->setPath($data['Path']);
|
||||
}
|
||||
|
||||
if (isset($data['Max-Age'])) {
|
||||
$this->setMaxAge($data['Max-Age']);
|
||||
}
|
||||
|
||||
if (isset($data['Expires'])) {
|
||||
$this->setExpires($data['Expires']);
|
||||
}
|
||||
|
||||
if (isset($data['Secure'])) {
|
||||
$this->setSecure($data['Secure']);
|
||||
}
|
||||
|
||||
if (isset($data['Discard'])) {
|
||||
$this->setDiscard($data['Discard']);
|
||||
}
|
||||
|
||||
if (isset($data['HttpOnly'])) {
|
||||
$this->setHttpOnly($data['HttpOnly']);
|
||||
}
|
||||
|
||||
// Set the remaining values that don't have extra validation logic
|
||||
foreach (array_diff(array_keys($data), array_keys(self::DEFAULTS)) as $key) {
|
||||
$this->data[$key] = $data[$key];
|
||||
}
|
||||
|
||||
// Derive Expires from Max-Age unless the data already carries one
|
||||
$maxAge = $this->getMaxAge();
|
||||
if ($maxAge !== null && $this->getExpires() === null) {
|
||||
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
|
||||
foreach ($this->data as $k => $v) {
|
||||
if ($k === 'Domain' && $this->getHostOnly()) {
|
||||
continue;
|
||||
}
|
||||
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
|
||||
if ($k === 'Expires') {
|
||||
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
|
||||
} else {
|
||||
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return \rtrim($str, '; ');
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
$data = $this->data;
|
||||
if ($this->getHostOnly()) {
|
||||
$data['HostOnly'] = true;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie name.
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->data['Name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie name.
|
||||
*
|
||||
* @param string $name Cookie name
|
||||
*/
|
||||
public function setName(string $name): void
|
||||
{
|
||||
$this->data['Name'] = $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the cookie value.
|
||||
*/
|
||||
public function getValue(): ?string
|
||||
{
|
||||
return $this->data['Value'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the cookie value.
|
||||
*
|
||||
* @param string $value Cookie value
|
||||
*/
|
||||
public function setValue(string $value): void
|
||||
{
|
||||
$this->data['Value'] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the domain.
|
||||
*/
|
||||
public function getDomain(): ?string
|
||||
{
|
||||
return $this->data['Domain'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the domain of the cookie.
|
||||
*
|
||||
* @param string|null $domain Domain of the cookie
|
||||
*/
|
||||
public function setDomain(?string $domain): void
|
||||
{
|
||||
$this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether this cookie is scoped to the origin host only.
|
||||
*/
|
||||
public function getHostOnly(): bool
|
||||
{
|
||||
return $this->hostOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether this cookie is scoped to the origin host only.
|
||||
*
|
||||
* @param bool $hostOnly Set to true for host-only cookies
|
||||
*/
|
||||
public function setHostOnly(bool $hostOnly): void
|
||||
{
|
||||
$this->hostOnly = $hostOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path.
|
||||
*/
|
||||
public function getPath(): string
|
||||
{
|
||||
return $this->data['Path'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the path of the cookie.
|
||||
*
|
||||
* @param string $path Path of the cookie
|
||||
*/
|
||||
public function setPath(string $path): void
|
||||
{
|
||||
$this->data['Path'] = $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maximum lifetime of the cookie in seconds.
|
||||
*/
|
||||
public function getMaxAge(): ?int
|
||||
{
|
||||
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the max-age of the cookie.
|
||||
*
|
||||
* @param int|null $maxAge Max age of the cookie in seconds
|
||||
*/
|
||||
public function setMaxAge(?int $maxAge): void
|
||||
{
|
||||
$this->data['Max-Age'] = $maxAge;
|
||||
}
|
||||
|
||||
/**
|
||||
* The UNIX timestamp when the cookie Expires.
|
||||
*/
|
||||
public function getExpires(): ?int
|
||||
{
|
||||
return $this->data['Expires'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the unix timestamp for which the cookie will expire.
|
||||
*
|
||||
* @param int|string|null $timestamp Unix timestamp or any English textual datetime description.
|
||||
*/
|
||||
public function setExpires($timestamp): void
|
||||
{
|
||||
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
|
||||
// TODO: Move this to the parameter definition in 9.0.
|
||||
throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null');
|
||||
}
|
||||
|
||||
if ($timestamp === null) {
|
||||
$this->data['Expires'] = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (\is_string($timestamp)) {
|
||||
if (\is_numeric($timestamp)) {
|
||||
$this->data['Expires'] = self::parseNumericInteger($timestamp);
|
||||
|
||||
return;
|
||||
}
|
||||
} elseif (\is_int($timestamp)) {
|
||||
$this->data['Expires'] = $timestamp;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$expires = \strtotime($timestamp);
|
||||
$this->data['Expires'] = $expires === false ? null : $expires;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a secure cookie.
|
||||
*/
|
||||
public function getSecure(): bool
|
||||
{
|
||||
return $this->data['Secure'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not the cookie is secure.
|
||||
*
|
||||
* @param bool $secure Set to true or false if secure
|
||||
*/
|
||||
public function setSecure(bool $secure): void
|
||||
{
|
||||
$this->data['Secure'] = $secure;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is a session cookie.
|
||||
*/
|
||||
public function getDiscard(): bool
|
||||
{
|
||||
return $this->data['Discard'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not this is a session cookie.
|
||||
*
|
||||
* @param bool $discard Set to true or false if this is a session cookie
|
||||
*/
|
||||
public function setDiscard(bool $discard): void
|
||||
{
|
||||
$this->data['Discard'] = $discard;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether or not this is an HTTP only cookie.
|
||||
*/
|
||||
public function getHttpOnly(): bool
|
||||
{
|
||||
return $this->data['HttpOnly'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether or not this is an HTTP only cookie.
|
||||
*
|
||||
* @param bool $httpOnly Set to true or false if this is HTTP only
|
||||
*/
|
||||
public function setHttpOnly(bool $httpOnly): void
|
||||
{
|
||||
$this->data['HttpOnly'] = $httpOnly;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie matches a path value.
|
||||
*
|
||||
* A request-path path-matches a given cookie-path if at least one of
|
||||
* the following conditions holds:
|
||||
*
|
||||
* - The cookie-path and the request-path are identical.
|
||||
* - The cookie-path is a prefix of the request-path, and the last
|
||||
* character of the cookie-path is %x2F ("/").
|
||||
* - The cookie-path is a prefix of the request-path, and the first
|
||||
* character of the request-path that is not included in the cookie-
|
||||
* path is a %x2F ("/") character.
|
||||
*
|
||||
* @param string $requestPath Path to check against
|
||||
*/
|
||||
public function matchesPath(string $requestPath): bool
|
||||
{
|
||||
$cookiePath = $this->getPath();
|
||||
|
||||
// Match on exact matches or when path is the default empty "/"
|
||||
if ($cookiePath === '/' || $cookiePath === $requestPath) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Ensure that the cookie-path is a prefix of the request path.
|
||||
if (0 !== \strpos($requestPath, $cookiePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Match if the last character of the cookie-path is "/"
|
||||
if (\substr($cookiePath, -1, 1) === '/') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Match if the first character not included in cookie path is "/"
|
||||
return \substr($requestPath, \strlen($cookiePath), 1) === '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie matches a domain value.
|
||||
*
|
||||
* @param string $domain Domain to check against
|
||||
*/
|
||||
public function matchesDomain(string $domain): bool
|
||||
{
|
||||
$cookieDomain = $this->getDomain();
|
||||
if (null === $cookieDomain || $cookieDomain === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->getHostOnly()) {
|
||||
return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain);
|
||||
}
|
||||
|
||||
return HostIdentity::cookieDomainMatches($domain, $cookieDomain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie is expired.
|
||||
*/
|
||||
public function isExpired(): bool
|
||||
{
|
||||
return $this->getExpires() !== null && \time() > $this->getExpires();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cookie is valid according to RFC 6265.
|
||||
*
|
||||
* @return string|true Returns true if valid or an error message if invalid
|
||||
*/
|
||||
public function validate()
|
||||
{
|
||||
$name = $this->getName();
|
||||
if ($name === null || $name === '') {
|
||||
return 'The cookie name must not be empty';
|
||||
}
|
||||
|
||||
// Check if any of the invalid characters are present in the cookie name
|
||||
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
|
||||
return 'Cookie name must not contain invalid characters: ASCII '
|
||||
.'Control characters (0-31;127), space, tab and the '
|
||||
.'following characters: ()<>@,;:\"/?={}';
|
||||
}
|
||||
|
||||
// Value must not be null. 0 and empty string are valid. Empty strings
|
||||
// are technically against RFC 6265, but known to happen in the wild.
|
||||
$value = $this->getValue();
|
||||
if ($value === null) {
|
||||
return 'The cookie value must not be empty';
|
||||
}
|
||||
|
||||
// Domains must not be empty, but may be omitted. "0" is not a valid
|
||||
// internet domain, but may be used as server name in a private network.
|
||||
$domain = $this->getDomain();
|
||||
if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) {
|
||||
return 'The cookie domain must not be empty';
|
||||
}
|
||||
|
||||
if ($this->getHostOnly() && $domain === null) {
|
||||
return 'Host-only cookies must have a domain';
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function normalizeDomain(string $domain): string
|
||||
{
|
||||
$domain = Psr7\Utils::asciiToLower($domain);
|
||||
|
||||
// Treat trailing-dot domains as host-only, but keep pure-dot domains invalid.
|
||||
if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($domain !== '' && $domain !== '.' && $domain[0] === '.') {
|
||||
$domain = \substr_replace($domain, '', 0, 1);
|
||||
}
|
||||
|
||||
return HostIdentity::canonicalCookieDomain($domain);
|
||||
}
|
||||
|
||||
private static function maxAgeToExpires(int $maxAge, int $now): int
|
||||
{
|
||||
if ($maxAge <= 0) {
|
||||
return $now - 1;
|
||||
}
|
||||
|
||||
// Clamp absurd Max-Age values so addition cannot promote to float
|
||||
if ($maxAge > \PHP_INT_MAX - $now) {
|
||||
return \PHP_INT_MAX;
|
||||
}
|
||||
|
||||
return $now + $maxAge;
|
||||
}
|
||||
|
||||
private static function parseNumericInteger(string $value): ?int
|
||||
{
|
||||
if (!\is_numeric($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
|
||||
$negative = $value[0] === '-';
|
||||
$digits = \ltrim($value, '+-');
|
||||
$digits = \ltrim($digits, '0');
|
||||
$digits = $digits === '' ? '0' : $digits;
|
||||
$limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX;
|
||||
|
||||
if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) ($negative ? '-'.$digits : $digits);
|
||||
}
|
||||
|
||||
$number = (float) $value;
|
||||
if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $number;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed[] $data
|
||||
*/
|
||||
private static function validateFieldTypes(
|
||||
#[\SensitiveParameter]
|
||||
array $data
|
||||
): void {
|
||||
foreach (['Name', 'Value', 'Domain', 'Path'] as $field) {
|
||||
if (isset($data[$field]) && !\is_string($data[$field])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field));
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer');
|
||||
}
|
||||
|
||||
if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string');
|
||||
}
|
||||
|
||||
foreach (['Secure', 'Discard', 'HttpOnly'] as $field) {
|
||||
if (isset($data[$field]) && !\is_bool($data[$field])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field));
|
||||
}
|
||||
}
|
||||
|
||||
if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) {
|
||||
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
/**
|
||||
* Reads configuration from the process environment.
|
||||
*
|
||||
* Intentionally separate from Handler\ProxyEnv, which has different
|
||||
* lookup semantics.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class Env
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function get(string $name): ?string
|
||||
{
|
||||
if (isset($_SERVER[$name])) {
|
||||
return (string) $_SERVER[$name];
|
||||
}
|
||||
|
||||
if (\PHP_SAPI === 'cli' && ($value = \getenv($name)) !== false && $value !== null) {
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 4xx or 5xx status codes.
|
||||
*/
|
||||
class BadResponseException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 4xx status codes.
|
||||
*/
|
||||
class ClientException extends BadResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when connection establishment fails.
|
||||
*/
|
||||
class ConnectException extends NetworkException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when connection establishment exceeds the time limit.
|
||||
*/
|
||||
class ConnectTimeoutException extends ConnectException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Client\ClientExceptionInterface;
|
||||
|
||||
interface GuzzleException extends ClientExceptionInterface
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a handler is closed before a transfer completes.
|
||||
*/
|
||||
class HandlerClosedException extends TransferException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when an invalid argument is supplied to Guzzle.
|
||||
*/
|
||||
final class InvalidArgumentException extends \InvalidArgumentException implements GuzzleException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Client\NetworkExceptionInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Base exception for transfer failures without a response.
|
||||
*/
|
||||
class NetworkException extends TransferException implements NetworkExceptionInterface
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, 0, $previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a transfer times out before response headers are
|
||||
* received.
|
||||
*/
|
||||
class NetworkTimeoutException extends NetworkException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use GuzzleHttp\BodySummarizer;
|
||||
use GuzzleHttp\BodySummarizerInterface;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use Psr\Http\Client\RequestExceptionInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Base exception for request failures associated with a request.
|
||||
*/
|
||||
class RequestException extends TransferException implements RequestExceptionInterface
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
int $code = 0,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, $code, $previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create a new exception with a normalized error message
|
||||
*
|
||||
* @param RequestInterface $request Request sent
|
||||
* @param ResponseInterface|null $response Response received, if any
|
||||
* @param \Throwable|null $previous Previous exception
|
||||
* @param BodySummarizerInterface|null $bodySummarizer Optional body summarizer
|
||||
*/
|
||||
public static function create(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
?ResponseInterface $response = null,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null,
|
||||
?BodySummarizerInterface $bodySummarizer = null
|
||||
): self {
|
||||
if (!$response) {
|
||||
return new self(
|
||||
'Error completing request',
|
||||
$request,
|
||||
0,
|
||||
$previous
|
||||
);
|
||||
}
|
||||
|
||||
$level = (int) \floor($response->getStatusCode() / 100);
|
||||
if ($level === 4) {
|
||||
$label = 'Client error';
|
||||
} elseif ($level === 5) {
|
||||
$label = 'Server error';
|
||||
} else {
|
||||
$label = 'Unsuccessful request';
|
||||
}
|
||||
|
||||
$uri = \GuzzleHttp\Psr7\UriRedactor::redactUriForMessage($request->getUri());
|
||||
|
||||
// Client error: `GET /` resulted in a `404 Not Found` response: <html> ... (truncated)
|
||||
$message = \sprintf(
|
||||
'%s: `%s %s` resulted in a `%s %s` response',
|
||||
$label,
|
||||
DiagnosticValue::escape($request->getMethod()),
|
||||
$uri,
|
||||
$response->getStatusCode(),
|
||||
DiagnosticValue::escape($response->getReasonPhrase())
|
||||
);
|
||||
|
||||
$summary = ($bodySummarizer ?? new BodySummarizer())->summarize($response);
|
||||
|
||||
if ($summary !== null) {
|
||||
$message .= \sprintf(': %s', DiagnosticValue::escape($summary));
|
||||
}
|
||||
|
||||
if ($level === 4) {
|
||||
return new ClientException($message, $request, $response, $previous);
|
||||
}
|
||||
|
||||
if ($level === 5) {
|
||||
return new ServerException($message, $request, $response, $previous);
|
||||
}
|
||||
|
||||
return new ResponseException($message, $request, $response, $previous);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Exception thrown when a request fails after response headers are received.
|
||||
*/
|
||||
class ResponseException extends RequestException
|
||||
{
|
||||
private ResponseInterface $response;
|
||||
|
||||
final public function __construct(
|
||||
string $message,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $request, $response->getStatusCode(), $previous);
|
||||
$this->response = $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a new exception instance with an updated response.
|
||||
*
|
||||
* @param \Throwable|null $previous Previous exception, or the current
|
||||
* previous exception when omitted.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public function withResponse(
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
?\Throwable $previous = null
|
||||
): self {
|
||||
if ($response->getStatusCode() !== $this->response->getStatusCode()) {
|
||||
throw new InvalidArgumentException('Cannot replace response with a different status code.');
|
||||
}
|
||||
|
||||
return new static(
|
||||
$this->getMessage(),
|
||||
$this->getRequest(),
|
||||
$response,
|
||||
$previous ?? $this->getPrevious()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the associated response.
|
||||
*/
|
||||
public function getResponse(): ResponseInterface
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a transfer times out after response headers are
|
||||
* received.
|
||||
*/
|
||||
class ResponseTimeoutException extends ResponseTransferException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when a response transfer fails after response headers are
|
||||
* received.
|
||||
*/
|
||||
class ResponseTransferException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown for HTTP responses with 5xx status codes.
|
||||
*/
|
||||
class ServerException extends BadResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
/**
|
||||
* Exception thrown when redirect middleware reaches the redirect limit.
|
||||
*/
|
||||
class TooManyRedirectsException extends ResponseException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Exception;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Base exception for transfer failures.
|
||||
*/
|
||||
class TransferException extends \RuntimeException implements GuzzleException
|
||||
{
|
||||
private RequestInterface $request;
|
||||
|
||||
public function __construct(
|
||||
string $message,
|
||||
RequestInterface $request,
|
||||
int $code = 0,
|
||||
?\Throwable $previous = null
|
||||
) {
|
||||
parent::__construct($message, $code, $previous);
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the request that caused the exception.
|
||||
*/
|
||||
public function getRequest(): RequestInterface
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use GuzzleHttp\Psr7\StreamWrapper;
|
||||
use GuzzleHttp\Psr7\Utils;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Decodes the chunked transfer coding of a response body read from the
|
||||
* unfiltered transport stream, with the framing rules libcurl applies.
|
||||
*
|
||||
* Each read returns the decoded bytes that are already available, waiting on
|
||||
* the transport only when there are none, so the transport's idle timeout
|
||||
* governs every wait. The body ends as soon as the last chunk and trailer
|
||||
* section have been decoded, without another transport read. A body that ends
|
||||
* early or has malformed framing fails the read once the bytes decoded before
|
||||
* the fault have been returned, and every later read fails the same way.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class ChunkedBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private const READ_SIZE = 8192;
|
||||
|
||||
private const MAX_SIZE_DIGITS = 17;
|
||||
|
||||
// libcurl's trailer line and header section limits.
|
||||
private const MAX_TRAILER_LINE_LENGTH = 4093;
|
||||
|
||||
private const MAX_TRAILER_SECTION_LENGTH = 307200;
|
||||
|
||||
private const SIZE = 0;
|
||||
|
||||
private const SIZE_LINE = 1;
|
||||
|
||||
private const DATA = 2;
|
||||
|
||||
private const DATA_END = 3;
|
||||
|
||||
private const TRAILER = 4;
|
||||
|
||||
private const TRAILER_CR = 5;
|
||||
|
||||
private const FINAL_CR = 6;
|
||||
|
||||
private const DONE = 7;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private string $buffer = '';
|
||||
|
||||
private int $offset = 0;
|
||||
|
||||
private int $state = self::SIZE;
|
||||
|
||||
private string $digits = '';
|
||||
|
||||
private int $remaining = 0;
|
||||
|
||||
private string $line = '';
|
||||
|
||||
private int $trailerLength = 0;
|
||||
|
||||
private int $position = 0;
|
||||
|
||||
private ?\RuntimeException $failure = null;
|
||||
|
||||
private bool $detachable = true;
|
||||
|
||||
public function __construct(StreamInterface $stream)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
}
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// A clone shares the transport, so detaching it would break this body.
|
||||
$this->detachable = false;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
do {
|
||||
$data = $this->decode($length);
|
||||
} while ($data === '' && $length > 0 && !$this->eof() && $this->fill());
|
||||
|
||||
$this->position = TransferByteCounter::add(
|
||||
$this->position,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return $this->state === self::DONE;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
// A failed body has not timed out, whatever a stale flag on the
|
||||
// transport says, so callers report the failure itself.
|
||||
if ($this->failure !== null && $key === 'timed_out') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($this->failure !== null && $key === null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
public function tell(): int
|
||||
{
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function getSize(): ?int
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a chunked response body');
|
||||
}
|
||||
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $string): int
|
||||
{
|
||||
throw new \RuntimeException('Cannot write to a chunked response body');
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
$this->detachable = false;
|
||||
$this->stream->close();
|
||||
}
|
||||
|
||||
public function detach()
|
||||
{
|
||||
if (!$this->detachable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->state === self::DONE) {
|
||||
return $this->stream->detach();
|
||||
}
|
||||
|
||||
if ($this->buffer === '' && $this->failure === null) {
|
||||
$resource = $this->stream->detach();
|
||||
if (\is_resource($resource)) {
|
||||
// Nothing has been decoded yet, so PHP's filter can take over.
|
||||
\stream_filter_append($resource, 'dechunk', \STREAM_FILTER_READ);
|
||||
}
|
||||
|
||||
return $resource;
|
||||
}
|
||||
|
||||
// PHP's filter cannot resume part way through a chunk, so hand the
|
||||
// decoder over to a resource that keeps decoding the rest of the body.
|
||||
$decoder = clone $this;
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
$this->detachable = false;
|
||||
$this->stream = Utils::streamFor('');
|
||||
$this->stream->detach();
|
||||
|
||||
return StreamWrapper::getResource($decoder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends what the transport has available to the buffer, waiting for at
|
||||
* least one byte.
|
||||
*/
|
||||
private function fill(): bool
|
||||
{
|
||||
$data = $this->stream->read(self::READ_SIZE);
|
||||
if ($data === '') {
|
||||
if (!$this->stream->eof()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->failure = new \RuntimeException('Response body ended before the chunked body was complete');
|
||||
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
$this->buffer = \substr($this->buffer, $this->offset).$data;
|
||||
$this->offset = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes up to $length bytes from the buffer, and any framing after them,
|
||||
* so the end of the body is noticed without another transport read.
|
||||
*/
|
||||
private function decode(int $length): string
|
||||
{
|
||||
$data = '';
|
||||
|
||||
try {
|
||||
while ($this->offset < \strlen($this->buffer) && $this->state !== self::DONE) {
|
||||
if ($this->state === self::DATA) {
|
||||
$take = \min($this->remaining, $length - \strlen($data), \strlen($this->buffer) - $this->offset);
|
||||
if ($take === 0) {
|
||||
break;
|
||||
}
|
||||
$data .= \substr($this->buffer, $this->offset, $take);
|
||||
$this->offset += $take;
|
||||
$this->remaining -= $take;
|
||||
if ($this->remaining === 0) {
|
||||
$this->state = self::DATA_END;
|
||||
}
|
||||
} elseif ($this->state === self::SIZE) {
|
||||
$chunks = $this->digits === '' ? $this->decodeChunks($length - \strlen($data)) : null;
|
||||
if ($chunks === null) {
|
||||
$this->decodeSize();
|
||||
} else {
|
||||
$data .= $chunks;
|
||||
}
|
||||
} elseif ($this->state === self::SIZE_LINE) {
|
||||
$this->skipSizeLine();
|
||||
} elseif ($this->state === self::DATA_END) {
|
||||
$this->decodeDataEnd();
|
||||
} else {
|
||||
$this->decodeTrailer();
|
||||
}
|
||||
}
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->failure = $e;
|
||||
if ($data === '') {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes buffered chunks in bulk, up to $length bytes, and leaves the
|
||||
* state machine at the first chunk that needs more care. Returns null when
|
||||
* it consumes nothing.
|
||||
*/
|
||||
private function decodeChunks(int $length): ?string
|
||||
{
|
||||
$buffer = $this->buffer;
|
||||
$end = \strlen($buffer);
|
||||
$offset = $this->offset;
|
||||
$data = '';
|
||||
|
||||
while (true) {
|
||||
// Up to seven digits keep the size an int on every platform.
|
||||
$digits = \strspn($buffer, '0123456789abcdefABCDEF', $offset, 8);
|
||||
if ($digits === 0 || $digits === 8) {
|
||||
break;
|
||||
}
|
||||
$lineEnd = \strpos($buffer, "\n", $offset + $digits);
|
||||
if ($lineEnd === false) {
|
||||
break;
|
||||
}
|
||||
|
||||
$size = (int) \hexdec(\substr($buffer, $offset, $digits));
|
||||
$offset = $lineEnd + 1;
|
||||
if ($size === 0) {
|
||||
$this->state = self::TRAILER;
|
||||
break;
|
||||
}
|
||||
if ($size > $length || $offset + $size > $end) {
|
||||
$this->remaining = $size;
|
||||
$this->state = self::DATA;
|
||||
break;
|
||||
}
|
||||
|
||||
$data .= \substr($buffer, $offset, $size);
|
||||
$length -= $size;
|
||||
$offset += $size;
|
||||
if ($offset + 1 < $end && $buffer[$offset] === "\r" && $buffer[$offset + 1] === "\n") {
|
||||
$offset += 2;
|
||||
} elseif ($offset < $end && $buffer[$offset] === "\n") {
|
||||
++$offset;
|
||||
} else {
|
||||
$this->state = self::DATA_END;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($offset === $this->offset) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->offset = $offset;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function decodeSize(): void
|
||||
{
|
||||
$count = \strspn($this->buffer, '0123456789abcdefABCDEF', $this->offset);
|
||||
$this->digits .= \substr($this->buffer, $this->offset, $count);
|
||||
$this->offset += $count;
|
||||
if (\strlen($this->digits) > self::MAX_SIZE_DIGITS) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
if ($this->digits === '') {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
|
||||
$significant = \ltrim($this->digits, '0');
|
||||
if (\strlen($significant) > 16 || (\strlen($significant) === 16 && $significant[0] > '7')) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid chunk size');
|
||||
}
|
||||
|
||||
$size = \hexdec($this->digits);
|
||||
if (!\is_int($size)) {
|
||||
throw new \OverflowException('Chunk size exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
$this->digits = '';
|
||||
$this->remaining = $size;
|
||||
$this->state = self::SIZE_LINE;
|
||||
}
|
||||
|
||||
private function skipSizeLine(): void
|
||||
{
|
||||
// Chunk extensions, and anything else up to the line feed, are ignored
|
||||
// the way libcurl ignores them.
|
||||
$end = \strpos($this->buffer, "\n", $this->offset);
|
||||
if ($end === false) {
|
||||
$this->offset = \strlen($this->buffer);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->offset = $end + 1;
|
||||
$this->state = $this->remaining === 0 ? self::TRAILER : self::DATA;
|
||||
}
|
||||
|
||||
private function decodeDataEnd(): void
|
||||
{
|
||||
$this->offset += \strspn($this->buffer, "\r", $this->offset);
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
if ($this->buffer[$this->offset] !== "\n") {
|
||||
throw new \RuntimeException('Invalid chunked response body: missing CRLF after chunk data');
|
||||
}
|
||||
|
||||
++$this->offset;
|
||||
$this->state = self::SIZE;
|
||||
}
|
||||
|
||||
private function decodeTrailer(): void
|
||||
{
|
||||
if ($this->state !== self::TRAILER) {
|
||||
if ($this->buffer[$this->offset] !== "\n") {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
|
||||
++$this->offset;
|
||||
$this->state = $this->state === self::FINAL_CR ? self::DONE : self::TRAILER;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$count = \strcspn($this->buffer, "\r\n", $this->offset);
|
||||
$this->line .= \substr($this->buffer, $this->offset, $count);
|
||||
$this->offset += $count;
|
||||
$this->trailerLength += $count;
|
||||
if (\strlen($this->line) > self::MAX_TRAILER_LINE_LENGTH || $this->trailerLength > self::MAX_TRAILER_SECTION_LENGTH) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
if ($this->offset === \strlen($this->buffer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$carriageReturn = $this->buffer[$this->offset] === "\r";
|
||||
++$this->offset;
|
||||
if ($this->line === '') {
|
||||
$this->state = $carriageReturn ? self::FINAL_CR : self::DONE;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (\strpos($this->line, "\0") !== false || \strpos($this->line, ':') === false) {
|
||||
throw new \RuntimeException('Invalid chunked response body: invalid trailer section');
|
||||
}
|
||||
|
||||
$this->line = '';
|
||||
if ($carriageReturn) {
|
||||
$this->state = self::TRAILER_CR;
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Clock
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current monotonic clock reading in seconds.
|
||||
*/
|
||||
public static function now(): float
|
||||
{
|
||||
return \hrtime(true) / 1e9;
|
||||
}
|
||||
|
||||
public static function sleep(int $microseconds): void
|
||||
{
|
||||
while ($microseconds > 0) {
|
||||
$slice = \min($microseconds, 0xFFFFFFFF);
|
||||
\usleep($slice);
|
||||
$microseconds -= $slice;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3179
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
interface CurlFactoryInterface
|
||||
{
|
||||
/**
|
||||
* Creates a cURL handle resource.
|
||||
*
|
||||
* Implementations must return an EasyHandle whose public state properties,
|
||||
* including the request and sink, contain values compatible with Guzzle's
|
||||
* cURL handlers.
|
||||
*
|
||||
* @param RequestInterface $request Request
|
||||
* @param array $options Transfer options
|
||||
*
|
||||
* @throws \RuntimeException when an option cannot be applied
|
||||
*/
|
||||
public function create(RequestInterface $request, array $options): EasyHandle;
|
||||
|
||||
/**
|
||||
* Release an easy handle, allowing it to be reused or closed.
|
||||
*
|
||||
* This function must call unset on the easy handle's "handle" property.
|
||||
*/
|
||||
public function release(EasyHandle $easy): void;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* HTTP handler that uses cURL easy handles as a transport layer.
|
||||
*
|
||||
* When using the CurlHandler, custom curl options can be specified as an
|
||||
* associative array of curl option constants mapping to values in the
|
||||
* **curl** key of the "client" key of the request.
|
||||
*/
|
||||
final class CurlHandler
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const KNOWN_CONSTRUCTOR_OPTIONS = [
|
||||
'handle_factory' => true,
|
||||
'max_idle_handles' => true,
|
||||
'transport_sharing' => true,
|
||||
];
|
||||
|
||||
private CurlFactoryInterface $factory;
|
||||
|
||||
private bool $ownsFactory;
|
||||
|
||||
private bool $closed = false;
|
||||
|
||||
private ?CurlShareHandleState $shareHandleState;
|
||||
|
||||
/**
|
||||
* Accepts an associative array of options:
|
||||
*
|
||||
* - handle_factory: Optional curl factory used to create cURL handles.
|
||||
* - max_idle_handles: Optional maximum number of idle cURL easy handles.
|
||||
* Zero disables retention; null or omission keeps the default of 3.
|
||||
* - transport_sharing: Optional transport sharing mode.
|
||||
*
|
||||
* @param array{handle_factory?: ?CurlFactoryInterface, max_idle_handles?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
foreach ($options as $name => $_) {
|
||||
if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
|
||||
throw new InvalidArgumentException(\sprintf('Invalid CurlHandler constructor option "%s".', DiagnosticValue::escape((string) $name)));
|
||||
}
|
||||
}
|
||||
|
||||
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler');
|
||||
$transportSharing = $options['transport_sharing'] ?? null;
|
||||
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
|
||||
|
||||
$maxIdleHandles = $options['max_idle_handles'] ?? 3;
|
||||
if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) {
|
||||
throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.');
|
||||
}
|
||||
|
||||
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
|
||||
if (isset($options['max_idle_handles'])) {
|
||||
throw new InvalidArgumentException('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.');
|
||||
}
|
||||
|
||||
$this->shareHandleState = null;
|
||||
$this->factory = $options['handle_factory'];
|
||||
$this->ownsFactory = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->shareHandleState = $sharingMode !== TransportSharing::NONE
|
||||
? CurlShareHandleState::fromOption($transportSharing)
|
||||
: null;
|
||||
|
||||
$this->factory = $this->shareHandleState !== null
|
||||
? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState)
|
||||
: new CurlFactory($maxIdleHandles);
|
||||
|
||||
$this->ownsFactory = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$this->assertOpen();
|
||||
HostValidator::assertRequestHost($request);
|
||||
|
||||
if (isset($options['delay'])) {
|
||||
Clock::sleep((int) ($options['delay'] * 1000));
|
||||
}
|
||||
|
||||
// A Multiplexing::NONE request option holds unconditionally here:
|
||||
// the transfer runs alone during the blocking curl_exec(), and even
|
||||
// under persistent transport sharing an in-use connection cannot be
|
||||
// joined from another multi handle, so it never shares its
|
||||
// connection with a concurrent transfer.
|
||||
$easy = $this->factory->create($request, $options);
|
||||
|
||||
\curl_exec($easy->handle);
|
||||
$easy->errno = \curl_errno($easy->handle);
|
||||
|
||||
return CurlFactory::finish($this, $easy, $this->factory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes native cURL resources owned by this handler.
|
||||
*
|
||||
* After closing, the handler is terminal and must not be reused.
|
||||
*/
|
||||
public function close(): void
|
||||
{
|
||||
$this->doClose(true);
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
try {
|
||||
$this->doClose(false);
|
||||
} catch (\Throwable $e) {
|
||||
// Destructors must not throw.
|
||||
}
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->closed = true;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
private function assertOpen(): void
|
||||
{
|
||||
if ($this->closed) {
|
||||
// Programmer misuse (reusing a closed handler), not a transfer failure;
|
||||
// intentionally a LogicException outside the GuzzleException hierarchy.
|
||||
throw new \BadMethodCallException('Cannot use the cURL handler after it has been closed.');
|
||||
}
|
||||
}
|
||||
|
||||
private function doClose(bool $explicit): void
|
||||
{
|
||||
if ($this->closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->closed = true;
|
||||
|
||||
try {
|
||||
if ($this->ownsFactory && $this->factory instanceof CurlFactory) {
|
||||
$this->factory->close();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
if ($explicit) {
|
||||
throw $e;
|
||||
}
|
||||
} finally {
|
||||
$this->shareHandleState = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,276 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CurlShareHandleState
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var resource|\CurlShareHandle|\CurlSharePersistentHandle|null
|
||||
*/
|
||||
public $handle;
|
||||
|
||||
public string $mode;
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle|\CurlSharePersistentHandle|null $handle
|
||||
*/
|
||||
private function __construct(string $mode, $handle)
|
||||
{
|
||||
$this->mode = $mode;
|
||||
$this->handle = $handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function fromOption($sharing): ?self
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($sharing, 'transport_sharing');
|
||||
if ($mode === TransportSharing::NONE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_PREFER) {
|
||||
return self::createHandlerShareOrNull($mode);
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_REQUIRE) {
|
||||
return self::createHandlerShare($mode);
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::PERSISTENT_PREFER) {
|
||||
return self::createPersistentShareOrFallback();
|
||||
}
|
||||
|
||||
return self::createPersistentShare($mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function normalizeMode($sharing, string $option): string
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing->mode;
|
||||
}
|
||||
|
||||
if ($sharing === null || $sharing === TransportSharing::NONE) {
|
||||
return TransportSharing::NONE;
|
||||
}
|
||||
|
||||
if (
|
||||
$sharing === TransportSharing::HANDLER_PREFER
|
||||
|| $sharing === TransportSharing::HANDLER_REQUIRE
|
||||
|| $sharing === TransportSharing::PERSISTENT_PREFER
|
||||
|| $sharing === TransportSharing::PERSISTENT_REQUIRE
|
||||
) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.',
|
||||
$option,
|
||||
\get_debug_type($sharing)
|
||||
));
|
||||
}
|
||||
|
||||
public static function assertNoRequiredSharingCustomFactoryConflict(array $options, string $handlerName): void
|
||||
{
|
||||
if (!\array_key_exists('handle_factory', $options) || $options['handle_factory'] === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($options['transport_sharing'] ?? null, 'transport_sharing');
|
||||
if (!\in_array($mode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" %s option cannot require sharing with a custom "handle_factory" because Guzzle cannot ensure that the custom factory applies CURLOPT_SHARE.',
|
||||
$handlerName
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether cURL can share both the DNS and SSL session cache state that
|
||||
* required handler-lifetime sharing needs, checked without configuring a
|
||||
* share handle so default handler selection can fall back to the stream
|
||||
* handler instead.
|
||||
*/
|
||||
public static function supportsHandlerRequireShare(): bool
|
||||
{
|
||||
return CurlVersion::supportsHandlerSharing()
|
||||
&& CurlVersion::supportsSslSessionSharing()
|
||||
&& \function_exists('curl_share_init')
|
||||
&& \function_exists('curl_share_setopt')
|
||||
&& \defined('CURLOPT_SHARE')
|
||||
&& \defined('CURLSHOPT_SHARE')
|
||||
&& \defined('CURL_LOCK_DATA_DNS')
|
||||
&& \defined('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
private static function createHandlerShareOrNull(string $mode): ?self
|
||||
{
|
||||
try {
|
||||
return self::createHandlerShare($mode);
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static function createHandlerShare(string $mode): self
|
||||
{
|
||||
if (!\function_exists('curl_share_init') || !\function_exists('curl_share_setopt')) {
|
||||
throw new InvalidArgumentException('The "transport_sharing" option requires cURL share support.');
|
||||
}
|
||||
|
||||
self::requireCurlConstant('CURLOPT_SHARE');
|
||||
$shareOption = self::requireCurlConstant('CURLSHOPT_SHARE');
|
||||
$locks = self::handlerLocks($mode);
|
||||
$handle = curl_share_init();
|
||||
|
||||
try {
|
||||
foreach ($locks as $lock) {
|
||||
try {
|
||||
$success = curl_share_setopt($handle, $shareOption, $lock);
|
||||
} catch (\Throwable $e) {
|
||||
throw new InvalidArgumentException('Unable to configure cURL share handle: '.$e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
if (!$success) {
|
||||
throw new InvalidArgumentException(\sprintf('Unable to configure cURL share handle with lock data %d.', $lock));
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
self::closeHandlerShareHandleOnPhp7($handle);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return new self($mode, $handle);
|
||||
}
|
||||
|
||||
private static function createPersistentShareOrFallback(): ?self
|
||||
{
|
||||
if (self::supportsPersistentShare()) {
|
||||
try {
|
||||
return self::createPersistentShare(TransportSharing::PERSISTENT_PREFER);
|
||||
} catch (\Throwable $e) {
|
||||
// Fall back to handler-lifetime best effort below.
|
||||
}
|
||||
}
|
||||
|
||||
return self::createHandlerShareOrNull(TransportSharing::HANDLER_PREFER);
|
||||
}
|
||||
|
||||
private static function createPersistentShare(string $mode): self
|
||||
{
|
||||
CurlVersion::ensureConnectionSharingSupported();
|
||||
CurlVersion::ensureSslSessionSharingSupported();
|
||||
|
||||
if (!self::supportsPersistentShare()) {
|
||||
throw new InvalidArgumentException('The "transport_sharing" option requires persistent cURL share handle support.');
|
||||
}
|
||||
|
||||
self::requireCurlConstant('CURLOPT_SHARE');
|
||||
|
||||
try {
|
||||
$handle = curl_share_init_persistent(self::persistentLocks());
|
||||
} catch (\Throwable $e) {
|
||||
throw new InvalidArgumentException(
|
||||
'Unable to create persistent cURL share handle: '.$e->getMessage(),
|
||||
0,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
return new self($mode, $handle);
|
||||
}
|
||||
|
||||
private static function supportsPersistentShare(): bool
|
||||
{
|
||||
return CurlVersion::supportsConnectionSharing()
|
||||
&& CurlVersion::supportsSslSessionSharing()
|
||||
&& \function_exists('curl_share_init_persistent')
|
||||
&& \class_exists('CurlSharePersistentHandle')
|
||||
&& \defined('CURL_LOCK_DATA_DNS')
|
||||
&& \defined('CURL_LOCK_DATA_CONNECT')
|
||||
&& \defined('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private static function handlerLocks(string $mode): array
|
||||
{
|
||||
CurlVersion::ensureHandlerSharingSupported();
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_REQUIRE) {
|
||||
CurlVersion::ensureSslSessionSharingSupported();
|
||||
}
|
||||
|
||||
$locks = [
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
|
||||
];
|
||||
|
||||
if (CurlVersion::supportsSslSessionSharing()) {
|
||||
$locks[] = self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION');
|
||||
}
|
||||
|
||||
return $locks;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private static function persistentLocks(): array
|
||||
{
|
||||
return [
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_CONNECT'),
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'),
|
||||
];
|
||||
}
|
||||
|
||||
private static function requireCurlConstant(string $constant): int
|
||||
{
|
||||
if (!\defined($constant)) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires %s, but it is not available in the installed PHP cURL extension.',
|
||||
$constant
|
||||
));
|
||||
}
|
||||
|
||||
$value = \constant($constant);
|
||||
if (!\is_int($value)) {
|
||||
throw new InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant));
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle $handle
|
||||
*/
|
||||
private static function closeHandlerShareHandleOnPhp7($handle): void
|
||||
{
|
||||
if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) {
|
||||
curl_share_close($handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,407 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\ConnectException;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CurlVersion
|
||||
{
|
||||
private const MIN_VERSION = '7.34.0';
|
||||
|
||||
private const TLS_13_VERSION = '7.52.0';
|
||||
|
||||
// CURLOPT_PIPEWAIT exists since libcurl 7.43.0, and multi handles have
|
||||
// multiplexed by default since 7.62.0 - but a 7.65.0-7.65.1 regression
|
||||
// dropped that default, which 7.65.2 restored, so 7.65.2 is the floor at
|
||||
// which PIPEWAIT is reliably effective.
|
||||
private const MULTIPLEX_VERSION = '7.65.2';
|
||||
|
||||
// libcurl's connection matcher refuses to hand a transfer wanting
|
||||
// HTTP/1.x a pooled connection that already negotiated HTTP/2 or newer
|
||||
// from 7.77.0: ConnectionExists() in lib/url.c gained the check between
|
||||
// the 7.76.0 and 7.77.0 releases. The HTTP/2 branch of the check
|
||||
// regressed to a debug log in 8.11.0 (curl commit 433d730) and was
|
||||
// restored in 8.13.0 via the negotiation mask (curl commit db72b8d), so
|
||||
// 8.11.0 through 8.12.1 are vulnerable again.
|
||||
private const HTTP_VERSION_REUSE_MATCH_VERSION = '7.77.0';
|
||||
|
||||
private const HTTP_VERSION_REUSE_MATCH_REGRESSION = '8.11.0';
|
||||
|
||||
private const HTTP_VERSION_REUSE_MATCH_RESTORED = '8.13.0';
|
||||
|
||||
// CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE restricts the ALPN offer to h2 only
|
||||
// since libcurl 8.10.0, and connection reuse matching stopped handing
|
||||
// lower-version connections to prior-knowledge transfers in 8.14.0; below
|
||||
// that, a required HTTP/2 request could silently be sent over a reused
|
||||
// HTTP/1.1 connection.
|
||||
private const REQUIRED_HTTP2_MULTIPLEX_VERSION = '8.14.0';
|
||||
|
||||
// Version-aware connection reuse matching arrived in libcurl 8.13.0 with
|
||||
// an HTTP/3-only mask for CURL_HTTP_VERSION_3ONLY transfers; below that,
|
||||
// a required HTTP/3 request could silently ride a reused HTTP/2
|
||||
// connection.
|
||||
private const REQUIRED_HTTP3_MULTIPLEX_VERSION = '8.13.0';
|
||||
|
||||
// curl 7.52.0 introduced HTTPS proxy support, advertised by a feature bit
|
||||
// (a build can meet the version yet lack the feature). Earlier libcurl
|
||||
// mishandles an https:// proxy: before 7.50.2 it silently downgrades to a
|
||||
// plaintext HTTP proxy, and 7.50.2 through 7.51 reject it at connect time.
|
||||
// The 7.52.0 TLS rework also shipped verification flaws in exactly this
|
||||
// path (CVE-2017-2629, CVE-2017-7468); the latter affects 7.52.0-7.53.1
|
||||
// and was fixed in 7.54.0, so TLS to a proxy is only trusted from there.
|
||||
private const HTTPS_PROXY_VERSION = '7.54.0';
|
||||
|
||||
// HTTP/3 arrived in libcurl 7.66.0, but CURL_HTTP_VERSION_3ONLY only
|
||||
// exists from 7.88.0; requiring it keeps every HTTP/3-capable runtime
|
||||
// able to pin HTTP/3 with no downgrade.
|
||||
private const HTTP_3_VERSION = '7.88.0';
|
||||
|
||||
private const PROTOCOLS_STR_VERSION = '7.85.0';
|
||||
|
||||
private const HANDLER_SHARING_VERSION = '7.35.0';
|
||||
|
||||
private const SSL_SESSION_SHARING_VERSION = '8.6.0';
|
||||
|
||||
private const CONNECTION_SHARING_VERSION = '8.12.0';
|
||||
|
||||
// curl 7.57.0 added share-handle connection caches through
|
||||
// CURL_LOCK_DATA_CONNECT; older share objects can only hold DNS, TLS
|
||||
// session, and cookie data, never connections. This is libcurl's raw
|
||||
// capability floor for the opaque share safeguards; Guzzle-managed
|
||||
// connection sharing is separately gated by CONNECTION_SHARING_VERSION.
|
||||
private const SHARE_CONNECTION_CACHE_VERSION = '7.57.0';
|
||||
|
||||
// curl 8.22.0 applies the cURL multi connection caps from the transfer's
|
||||
// own multi handle to transfers using a share-owned connection pool, with
|
||||
// safe eviction from such pools, and documents that contract (curl #22266);
|
||||
// from 8.13.0 (df67269) until then, the limit check on share-owned pools
|
||||
// always passed (curl #22265).
|
||||
public const SHARED_POOL_CONNECTION_CAP_VERSION = '8.22.0';
|
||||
|
||||
// curl 7.83.1 added proxy TLS-SRP to the connection-reuse match
|
||||
// (CVE-2022-27782); the proxy client certificate was matched from 7.52.0,
|
||||
// so proxy TLS credentials are trusted from 7.83.1 onwards.
|
||||
private const PROXY_TLS_CREDENTIAL_REUSE_VERSION = '7.83.1';
|
||||
|
||||
// curl 8.19.0 fixed proxy tunnel reuse after credential changes
|
||||
// (CVE-2026-3784), but related proxy credential leak flaws were only
|
||||
// fixed in 8.20.0, so connection reuse is trusted from 8.20.0 onwards.
|
||||
private const PROXY_CREDENTIAL_REUSE_VERSION = '8.20.0';
|
||||
|
||||
// curl 7.69.0 started comparing SOCKS proxy credentials when matching
|
||||
// connections for reuse (curl #4835); older libcurl matches a SOCKS proxy
|
||||
// by type, host, and port only.
|
||||
private const SOCKS_PROXY_CREDENTIAL_REUSE_VERSION = '7.69.0';
|
||||
|
||||
private const PROXY_HEADER_SEPARATION_VERSION = '7.37.0';
|
||||
|
||||
// CURLOPT_SUPPRESS_CONNECT_HEADERS arrived in curl 7.54.0; proxy CONNECT
|
||||
// tunneling is gated on it so the proxy's interim reply can never surface
|
||||
// as a phantom response on any build that can tunnel.
|
||||
private const PROXY_TUNNEL_VERSION = '7.54.0';
|
||||
|
||||
/**
|
||||
* @var array{version: string, features: int}|false|null
|
||||
*/
|
||||
private static $versionInfo;
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function supportsCurlHandler(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_SSL')
|
||||
&& \defined('CURL_SSLVERSION_TLSv1_2')
|
||||
&& \defined('CURLMOPT_MAX_HOST_CONNECTIONS')
|
||||
&& \defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::MIN_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsTls13(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURL_SSLVERSION_TLSv1_3')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::TLS_13_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsMultiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_PIPEWAIT')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttpVersionReuseMatching(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
if (null === $version || version_compare($version, self::HTTP_VERSION_REUSE_MATCH_VERSION, '<')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return version_compare($version, self::HTTP_VERSION_REUSE_MATCH_REGRESSION, '<')
|
||||
|| version_compare($version, self::HTTP_VERSION_REUSE_MATCH_RESTORED, '>=');
|
||||
}
|
||||
|
||||
public static function supportsRequiredHttp2Multiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
|
||||
&& null !== $version
|
||||
&& self::supportsHttp2()
|
||||
&& version_compare($version, self::REQUIRED_HTTP2_MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttp2(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
// Requiring dependable CURLOPT_PIPEWAIT support keeps waiting from
|
||||
// ever being silently unavailable where HTTP/2 works.
|
||||
return \defined('CURL_VERSION_HTTP2')
|
||||
&& null !== $versionInfo
|
||||
&& self::supportsMultiplex()
|
||||
&& 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsHttp3(): bool
|
||||
{
|
||||
if (!\defined('CURL_VERSION_HTTP3') || !\defined('CURL_HTTP_VERSION_3') || !\defined('CURL_HTTP_VERSION_3ONLY')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$versionInfo = self::getVersionInfo();
|
||||
if (null === $versionInfo || version_compare($versionInfo['version'], self::HTTP_3_VERSION, '<')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 0 !== ((int) \constant('CURL_VERSION_HTTP3') & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsRequiredHttp3Multiplex(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return self::supportsHttp3()
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::REQUIRED_HTTP3_MULTIPLEX_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsHttpsProxy(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_HTTPS_PROXY')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_HTTPS_PROXY & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function supportsHandlerSharing(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::HANDLER_SHARING_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureHandlerSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsHandlerSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher for cURL share handles.',
|
||||
self::HANDLER_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsSslSessionSharing(): bool
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return \defined('CURL_VERSION_SSL')
|
||||
&& null !== $versionInfo
|
||||
&& version_compare($versionInfo['version'], self::SSL_SESSION_SHARING_VERSION, '>=')
|
||||
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
|
||||
}
|
||||
|
||||
public static function ensureSslSessionSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsSslSessionSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher with SSL support for SSL session sharing.',
|
||||
self::SSL_SESSION_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsConnectionSharing(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::CONNECTION_SHARING_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureConnectionSharingSupported(): void
|
||||
{
|
||||
if (!self::supportsConnectionSharing()) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires libcurl %s or higher for persistent connection sharing.',
|
||||
self::CONNECTION_SHARING_VERSION
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public static function supportsSharedPoolConnectionCaps(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::SHARED_POOL_CONNECTION_CAP_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsShareConnectionCaches(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
// An undetectable libcurl version is treated as capable so the
|
||||
// opaque share safeguards fail closed.
|
||||
return null === $version
|
||||
|| version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyHeaderSeparation(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return null !== $version
|
||||
&& version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
|
||||
&& \defined('CURLOPT_PROXYHEADER')
|
||||
&& \defined('CURLOPT_HEADEROPT')
|
||||
&& \defined('CURLHEADER_SEPARATE');
|
||||
}
|
||||
|
||||
public static function supportsProtocolsStr(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_PROTOCOLS_STR')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::PROTOCOLS_STR_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function supportsProxyTunneling(): bool
|
||||
{
|
||||
$version = self::get();
|
||||
|
||||
return \defined('CURLOPT_SUPPRESS_CONNECT_HEADERS')
|
||||
&& null !== $version
|
||||
&& version_compare($version, self::PROXY_TUNNEL_VERSION, '>=');
|
||||
}
|
||||
|
||||
public static function ensureSupported(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
if (self::supportsCurlHandler()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$version = self::get();
|
||||
|
||||
if (null === $version || version_compare($version, self::MIN_VERSION, '<')) {
|
||||
throw new ConnectException(\sprintf(
|
||||
'cURL %s or higher is required by the cURL handler; %s is installed.',
|
||||
self::MIN_VERSION,
|
||||
$version ?? 'an unknown version'
|
||||
), $request);
|
||||
}
|
||||
|
||||
if (!\defined('CURL_SSLVERSION_TLSv1_2')) {
|
||||
throw new ConnectException(\sprintf(
|
||||
'The PHP cURL extension must be built against cURL %s or higher to use the cURL handler.',
|
||||
self::MIN_VERSION
|
||||
), $request);
|
||||
}
|
||||
|
||||
if (!\defined('CURLMOPT_MAX_HOST_CONNECTIONS') || !\defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) {
|
||||
throw new ConnectException('The PHP cURL extension must expose CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS to use the cURL handler.', $request);
|
||||
}
|
||||
|
||||
throw new ConnectException('The cURL handler requires libcurl SSL support.', $request);
|
||||
}
|
||||
|
||||
private static function get(): ?string
|
||||
{
|
||||
$versionInfo = self::getVersionInfo();
|
||||
|
||||
return null === $versionInfo ? null : $versionInfo['version'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{version: string, features: int}|null
|
||||
*/
|
||||
private static function getVersionInfo(): ?array
|
||||
{
|
||||
if (null === self::$versionInfo) {
|
||||
if (!\function_exists('curl_version')) {
|
||||
self::$versionInfo = false;
|
||||
} else {
|
||||
$versionInfo = \curl_version();
|
||||
self::$versionInfo = \is_array($versionInfo)
|
||||
&& isset($versionInfo['version'], $versionInfo['features'])
|
||||
&& \is_string($versionInfo['version'])
|
||||
&& \is_int($versionInfo['features'])
|
||||
? [
|
||||
'version' => $versionInfo['version'],
|
||||
'features' => $versionInfo['features'],
|
||||
]
|
||||
: false;
|
||||
}
|
||||
}
|
||||
|
||||
return false === self::$versionInfo ? null : self::$versionInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Decorates the transport stream of a buffered response so every read
|
||||
* observes the wall-clock deadline of the "timeout" request option.
|
||||
*
|
||||
* The transport resource must be in non-blocking mode: a blocking read waits
|
||||
* for data up to the transport's own timeout, so a deadline check between reads
|
||||
* never runs while the server stalls. Reads return whatever bytes are available
|
||||
* and poll briefly for more, so the deadline is checked between packets rather
|
||||
* than between buffers.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class DeadlineSourceStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private const POLL_INTERVAL = 0.05;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private float $deadline;
|
||||
|
||||
private ?float $readTimeout;
|
||||
|
||||
/**
|
||||
* @param StreamInterface $stream Transport stream in non-blocking mode.
|
||||
* @param float $deadline Deadline based on Clock::now().
|
||||
* @param float|null $readTimeout Optional idle timeout per read, in seconds.
|
||||
*/
|
||||
public function __construct(StreamInterface $stream, float $deadline, ?float $readTimeout)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->deadline = $deadline;
|
||||
$this->readTimeout = $readTimeout;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
$idleStart = null;
|
||||
|
||||
while (true) {
|
||||
$remaining = $this->deadline - Clock::now();
|
||||
if ($remaining <= 0) {
|
||||
throw new TimeoutException('Unable to read from stream: timed out');
|
||||
}
|
||||
|
||||
$data = $this->stream->read($length);
|
||||
if ($data !== '') {
|
||||
return $data;
|
||||
}
|
||||
if ($this->stream->eof()) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$now = Clock::now();
|
||||
if ($idleStart === null) {
|
||||
$idleStart = $now;
|
||||
}
|
||||
if ($this->readTimeout !== null && $now - $idleStart >= $this->readTimeout) {
|
||||
throw new TimeoutException('Unable to read from stream: timed out');
|
||||
}
|
||||
|
||||
$wait = \min($remaining, self::POLL_INTERVAL);
|
||||
if ($this->readTimeout !== null) {
|
||||
$wait = \min($wait, $this->readTimeout - ($now - $idleStart));
|
||||
}
|
||||
\usleep((int) \ceil($wait * 1e6));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class DebugResource
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a debug stream based on the provided variable.
|
||||
*
|
||||
* @param mixed $value Optional value
|
||||
*
|
||||
* @return resource
|
||||
*/
|
||||
public static function from($value = null)
|
||||
{
|
||||
if (\is_resource($value)) {
|
||||
return $value;
|
||||
}
|
||||
if (\defined('STDOUT')) {
|
||||
return \STDOUT;
|
||||
}
|
||||
|
||||
return Psr7\Utils::tryFopen('php://output', 'w');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Ends a streamed response body at its declared Content-Length.
|
||||
*
|
||||
* Reads never consume bytes beyond the response message, and the body reaches
|
||||
* EOF without waiting for the server to close the connection. A transport that
|
||||
* ends before the declared length fails the read instead of looking like a
|
||||
* complete body.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class DeclaredLengthStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private int $remaining;
|
||||
|
||||
private ?\RuntimeException $failure = null;
|
||||
|
||||
public function __construct(StreamInterface $stream, int $declaredLength)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->remaining = $declaredLength;
|
||||
}
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// Detaching a clone must not detach this body's transport.
|
||||
$this->stream = clone $this->stream;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return $this->remaining === 0;
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a response body bounded by its declared Content-Length');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
// A failed body has not timed out, whatever a stale flag on the
|
||||
// transport says, so callers report the failure itself.
|
||||
if ($this->failure !== null && $key === 'timed_out') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($this->failure !== null && $key === null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
if ($length === 0 || $this->remaining === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$data = $this->stream->read(\min($length, $this->remaining));
|
||||
if ($data === '' && $this->stream->eof()) {
|
||||
$this->failure = new \RuntimeException('Response body ended before the declared Content-Length was reached');
|
||||
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
$this->remaining -= \strlen($data);
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Exception\ResponseTransferException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Represents a cURL easy handle and the data it populates.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class EasyHandle
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var resource|\CurlHandle cURL resource
|
||||
*/
|
||||
public $handle;
|
||||
|
||||
public StreamInterface $sink;
|
||||
|
||||
public RequestInterface $request;
|
||||
|
||||
/**
|
||||
* @var list<string> Received HTTP headers so far
|
||||
*/
|
||||
public array $headers = [];
|
||||
|
||||
/**
|
||||
* @var list<string> Valid trailer lines, retained only when an
|
||||
* on_trailers callback is configured
|
||||
*/
|
||||
public array $trailers = [];
|
||||
|
||||
/**
|
||||
* @var bool Whether this handle was configured with CURLOPT_PIPEWAIT
|
||||
*/
|
||||
public bool $usesPipewait = false;
|
||||
|
||||
/**
|
||||
* @var bool Whether processMessages() settled the deferred promise, which
|
||||
* a rewind retry settles with a still-pending promise
|
||||
*/
|
||||
public bool $deferredSettled = false;
|
||||
|
||||
/**
|
||||
* @var ResponseInterface|null Received response (if any)
|
||||
*/
|
||||
public ?ResponseInterface $response = null;
|
||||
|
||||
/**
|
||||
* @var array Request options
|
||||
*/
|
||||
public array $options = [];
|
||||
|
||||
/**
|
||||
* @var int cURL error number (if any)
|
||||
*/
|
||||
public int $errno = 0;
|
||||
|
||||
/**
|
||||
* @var string|null Effective CURLOPT_PROXY value the handle was created with (if any)
|
||||
*/
|
||||
public ?string $effectiveProxy = null;
|
||||
|
||||
/**
|
||||
* Proxy tunnel or SOCKS proxy section signature for connection-reuse
|
||||
* isolation, or null when the request does not require sectioning.
|
||||
*/
|
||||
public ?string $proxyTunnelSignature = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during on_headers (if any)
|
||||
*/
|
||||
public ?\Throwable $onHeadersException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during progress callback (if any)
|
||||
*/
|
||||
public ?\Throwable $progressException = null;
|
||||
|
||||
/**
|
||||
* @var bool Whether the progress callback requested abort
|
||||
*/
|
||||
public bool $progressAborted = false;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during createResponse (if any)
|
||||
*/
|
||||
public ?\Throwable $createResponseException = null;
|
||||
|
||||
/**
|
||||
* @var ResponseException|null Response header failure, if any.
|
||||
*/
|
||||
public ?ResponseException $responseHeaderException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during request body read timeout.
|
||||
*/
|
||||
public ?TimeoutException $bodyReadTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during request body rewind timeout.
|
||||
*/
|
||||
public ?TimeoutException $bodyRewindTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during request body rewind.
|
||||
*/
|
||||
public ?\Throwable $bodyRewindException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during request body read.
|
||||
*/
|
||||
public ?\Throwable $bodyReadException = null;
|
||||
|
||||
/**
|
||||
* @var TimeoutException|null Exception during response sink write timeout.
|
||||
*/
|
||||
public ?TimeoutException $sinkWriteTimeoutException = null;
|
||||
|
||||
/**
|
||||
* @var \Throwable|null Exception during response sink write.
|
||||
*/
|
||||
public ?\Throwable $sinkWriteException = null;
|
||||
|
||||
/**
|
||||
* @var bool Whether the response sink accepted a different byte count.
|
||||
*/
|
||||
public bool $sinkWriteIncomplete = false;
|
||||
|
||||
/**
|
||||
* @var int Number of response body bytes accepted by the sink.
|
||||
*/
|
||||
public int $responseBodyBytes = 0;
|
||||
|
||||
/**
|
||||
* @var \OverflowException|null Unrepresentable response body size or byte count.
|
||||
*/
|
||||
public ?\OverflowException $responseBodySizeException = null;
|
||||
|
||||
/**
|
||||
* Attach a response to the easy handle based on the received headers.
|
||||
*
|
||||
* @throws \RuntimeException if no headers have been received or the first
|
||||
* header line is invalid.
|
||||
*/
|
||||
public function createResponse(): void
|
||||
{
|
||||
$this->response = null;
|
||||
$this->responseBodyBytes = 0;
|
||||
$this->responseBodySizeException = null;
|
||||
$this->responseHeaderException = null;
|
||||
|
||||
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
|
||||
|
||||
// Non-101 informational responses precede the final response. Do not
|
||||
// expose them as the response for a transfer that ends before the final
|
||||
// response arrives. 101 switches protocol and is kept as terminal.
|
||||
if ($status < 200 && $status !== 101) {
|
||||
return;
|
||||
}
|
||||
|
||||
$framingFailure = null;
|
||||
try {
|
||||
$declaredLength = HeaderProcessor::validateResponseFraming($this->request->getMethod(), $status, $headers);
|
||||
HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength);
|
||||
} catch (\RuntimeException $e) {
|
||||
$framingFailure = $e;
|
||||
}
|
||||
|
||||
$normalizedKeys = HeaderProcessor::normalizeHeaderKeys($headers);
|
||||
$decodeContent = $this->options['decode_content'] ?? false;
|
||||
if ($framingFailure === null && $decodeContent !== false && isset($normalizedKeys['content-encoding'])) {
|
||||
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
|
||||
unset($headers[$normalizedKeys['content-encoding']]);
|
||||
$encodedContentLength = HeaderProcessor::removeHeader('Content-Length', $headers);
|
||||
if ($encodedContentLength !== []) {
|
||||
$headers['x-encoded-content-length'] = $encodedContentLength;
|
||||
|
||||
try {
|
||||
$bodyLength = $this->sink->getSize();
|
||||
} catch (\Exception $e) {
|
||||
$bodyLength = null;
|
||||
}
|
||||
if ($bodyLength) {
|
||||
$headers['Content-Length'] = [(string) $bodyLength];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attach a response to the easy handle with the parsed headers. Any
|
||||
// exception propagates to the caller (CurlFactory), which records it as
|
||||
// the createResponseException — do not catch it here.
|
||||
$responseFactory = self::requireResponseFactory($this->options[RequestOptions::RESPONSE_FACTORY] ?? new HttpFactory());
|
||||
$response = $responseFactory->createResponse($status, $reason ?? '')->withProtocolVersion($ver);
|
||||
foreach ($headers as $name => $value) {
|
||||
$response = $response->withAddedHeader((string) $name, $value);
|
||||
}
|
||||
$this->response = $response->withBody($this->sink);
|
||||
|
||||
if ($framingFailure instanceof \OverflowException) {
|
||||
$this->responseHeaderException = new ResponseException(
|
||||
$framingFailure->getMessage(),
|
||||
$this->request,
|
||||
$this->response,
|
||||
$framingFailure
|
||||
);
|
||||
} elseif ($framingFailure !== null) {
|
||||
$this->responseHeaderException = new ResponseTransferException(
|
||||
$framingFailure->getMessage(),
|
||||
$this->request,
|
||||
$this->response,
|
||||
$framingFailure
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $factory
|
||||
*/
|
||||
private static function requireResponseFactory($factory): ResponseFactoryInterface
|
||||
{
|
||||
if (!$factory instanceof ResponseFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::RESPONSE_FACTORY,
|
||||
ResponseFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return $factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
public function __get(string $name): void
|
||||
{
|
||||
$msg = $name === 'handle'
|
||||
? 'The EasyHandle has been released'
|
||||
: \sprintf('Invalid property: %s', DiagnosticValue::escape($name));
|
||||
|
||||
throw new \BadMethodCallException($msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Tracks encoded response bytes beneath a content-decoding stream.
|
||||
*
|
||||
* Reads are bounded by a positive, representable Content-Length so a decoder
|
||||
* cannot consume bytes beyond the response message boundary.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class EncodedBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
private ?int $limit;
|
||||
|
||||
private int $bytesRead = 0;
|
||||
|
||||
public function __construct(StreamInterface $stream, string $declaredLength)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
|
||||
$limit = HeaderProcessor::contentLengthToInt($declaredLength);
|
||||
$this->limit = $limit !== null && $limit > 0 ? $limit : null;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
return ($this->limit !== null && $this->bytesRead >= $this->limit)
|
||||
|| $this->stream->eof();
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Cannot seek a stream while tracking encoded response bytes');
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($this->limit !== null) {
|
||||
$remaining = $this->limit - $this->bytesRead;
|
||||
if ($remaining === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$length = \min($length, $remaining);
|
||||
}
|
||||
|
||||
$data = $this->stream->read($length);
|
||||
$this->bytesRead = TransferByteCounter::add(
|
||||
$this->bytesRead,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getBytesRead(): int
|
||||
{
|
||||
return $this->bytesRead;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class HeaderProcessor
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the HTTP version, status code, reason phrase, and headers.
|
||||
*
|
||||
* @param string[] $headers
|
||||
*
|
||||
* @return array{0:string, 1:int, 2:?string, 3:array}
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function parseHeaders(array $headers): array
|
||||
{
|
||||
if ($headers === []) {
|
||||
throw new \RuntimeException('Expected a non-empty array of header data');
|
||||
}
|
||||
|
||||
$headers = self::getLastHeaderBlock(\array_values($headers));
|
||||
|
||||
$statusLine = \array_shift($headers);
|
||||
if ($statusLine === null) {
|
||||
throw new \RuntimeException('Expected a non-empty array of header data');
|
||||
}
|
||||
|
||||
$parts = \explode(' ', $statusLine, 3);
|
||||
$protocol = $parts[0];
|
||||
|
||||
if (!Psr7\Utils::caselessEquals(\substr($protocol, 0, 5), 'HTTP/')) {
|
||||
throw new \RuntimeException('HTTP version missing from header data');
|
||||
}
|
||||
|
||||
$version = \substr($protocol, 5);
|
||||
|
||||
if (!\preg_match('/^\d+(?:\.\d+)?$/D', $version)) {
|
||||
throw new \RuntimeException('HTTP version is invalid');
|
||||
}
|
||||
|
||||
$status = $parts[1] ?? null;
|
||||
|
||||
if ($status === null) {
|
||||
throw new \RuntimeException('HTTP status code missing from header data');
|
||||
}
|
||||
|
||||
if (!\preg_match('/^[1-5]\d{2}$/D', $status)) {
|
||||
throw new \RuntimeException('HTTP status code is invalid');
|
||||
}
|
||||
|
||||
$reason = $parts[2] ?? null;
|
||||
|
||||
if ($reason !== null && !\preg_match('/^[\x09\x20-\x7E\x80-\xFF]*$/D', $reason)) {
|
||||
throw new \RuntimeException('HTTP reason phrase is invalid');
|
||||
}
|
||||
|
||||
foreach ($headers as $header) {
|
||||
if (\strpos($header, ':') === false) {
|
||||
throw new \RuntimeException('HTTP header line is invalid');
|
||||
}
|
||||
}
|
||||
|
||||
return [$version, (int) $status, $reason, self::headersFromLines($headers)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an array of header lines into an associative array of headers.
|
||||
*
|
||||
* @param iterable $lines Header lines array of strings in the following
|
||||
* format: "Name: Value"
|
||||
*/
|
||||
public static function headersFromLines(iterable $lines): array
|
||||
{
|
||||
$headers = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$parts = \explode(':', $line, 2);
|
||||
$headers[\trim($parts[0], " \n\r\t\0\x0B")][] = isset($parts[1]) ? \trim($parts[1], " \n\r\t\0\x0B") : null;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
public static function isStatusLineCandidate(string $line): bool
|
||||
{
|
||||
return \preg_match('/^HTTP\/[0-9]+(?:\.[0-9]+)? [0-9]{3}(?: [^\r\n]*)?(?:\r\n|\r|\n)?$/iD', $line) === 1;
|
||||
}
|
||||
|
||||
public static function isValidHeaderFieldLine(string $line): bool
|
||||
{
|
||||
$parts = \explode(':', $line, 2);
|
||||
|
||||
if (!isset($parts[1])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $parts[0])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*(?:\r\n|\r|\n)?$/D', \trim($parts[1], " \t")) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a normalized decimal Content-Length, or null when absent.
|
||||
*
|
||||
* @param string[] $values
|
||||
*
|
||||
* @throws \RuntimeException when Content-Length is malformed or conflicting.
|
||||
*/
|
||||
public static function parseContentLength(array $values): ?string
|
||||
{
|
||||
$length = null;
|
||||
|
||||
foreach ($values as $value) {
|
||||
foreach (\explode(',', $value) as $part) {
|
||||
$part = \trim($part, " \t");
|
||||
if (\preg_match('/^[0-9]+$/D', $part) !== 1) {
|
||||
throw new \RuntimeException('value is not a non-negative decimal integer');
|
||||
}
|
||||
|
||||
$part = \ltrim($part, '0');
|
||||
$part = $part === '' ? '0' : $part;
|
||||
if ($length !== null && $part !== $length) {
|
||||
throw new \RuntimeException('values conflict');
|
||||
}
|
||||
|
||||
$length = $part;
|
||||
}
|
||||
}
|
||||
|
||||
if ($length === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $length;
|
||||
}
|
||||
|
||||
public static function contentLengthToInt(?string $length): ?int
|
||||
{
|
||||
if ($length === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$max = (string) \PHP_INT_MAX;
|
||||
if (
|
||||
\strlen($length) > \strlen($max)
|
||||
|| (\strlen($length) === \strlen($max) && \strcmp($length, $max) > 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $length;
|
||||
}
|
||||
|
||||
public static function assertContentLengthWithinPlatformLimit(?string $length): void
|
||||
{
|
||||
if ($length === null || self::contentLengthToInt($length) !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new \OverflowException('Content-Length exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates response framing and returns its normalized Content-Length.
|
||||
* Returns null when absent or when ordinary body framing does not apply.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @throws \RuntimeException when Content-Length is malformed, conflicting,
|
||||
* or combined with Transfer-Encoding, or when a
|
||||
* transfer coding is unsupported or follows
|
||||
* chunked on the same field line
|
||||
*/
|
||||
public static function validateResponseFraming(
|
||||
string $method,
|
||||
int $status,
|
||||
array $headers
|
||||
): ?string {
|
||||
if (!self::responseCanHaveBody($method, $status)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalizedKeys = self::normalizeHeaderKeys($headers);
|
||||
$contentLength = self::removeHeader('Content-Length', $headers);
|
||||
|
||||
try {
|
||||
$length = self::parseContentLength($contentLength);
|
||||
} catch (\RuntimeException $e) {
|
||||
throw new \RuntimeException('Invalid Content-Length response header: '.$e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
if ($length !== null && isset($normalizedKeys['transfer-encoding'])) {
|
||||
throw new \RuntimeException('A response must not contain both Content-Length and Transfer-Encoding');
|
||||
}
|
||||
|
||||
self::parseTransferEncoding($headers);
|
||||
|
||||
return $length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the response uses the chunked transfer coding.
|
||||
*
|
||||
* Guzzle never asks for a transfer coding, so like libcurl 8.14 and newer
|
||||
* it accepts only identity and chunked, with nothing but chunked after
|
||||
* chunked on the same field line. Empty list elements are ignored.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @throws \RuntimeException when a coding is unsupported or follows chunked
|
||||
* on the same field line
|
||||
*/
|
||||
public static function parseTransferEncoding(array $headers): bool
|
||||
{
|
||||
$chunked = false;
|
||||
|
||||
foreach ($headers as $name => $values) {
|
||||
if (!Psr7\Utils::caselessEquals((string) $name, 'Transfer-Encoding')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($values as $value) {
|
||||
$afterChunked = false;
|
||||
foreach (\explode(',', $value) as $coding) {
|
||||
$coding = \trim($coding, " \t");
|
||||
if ($coding === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Psr7\Utils::caselessEquals($coding, 'chunked')) {
|
||||
$chunked = true;
|
||||
$afterChunked = true;
|
||||
} elseif ($afterChunked) {
|
||||
throw new \RuntimeException('Invalid Transfer-Encoding response header: chunked is not the final transfer coding');
|
||||
} elseif (!Psr7\Utils::caselessEquals($coding, 'identity')) {
|
||||
throw new \RuntimeException(\sprintf(
|
||||
'Invalid Transfer-Encoding response header: unsupported transfer coding "%s"',
|
||||
Psr7\DiagnosticValue::escape($coding)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $chunked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes every case-insensitive occurrence of a header and returns all
|
||||
* removed values in their original field order.
|
||||
*
|
||||
* @param array<string, string[]> $headers
|
||||
*
|
||||
* @return string[] Removed values across all header-name casings
|
||||
*/
|
||||
public static function removeHeader(string $name, array &$headers): array
|
||||
{
|
||||
$values = [];
|
||||
|
||||
foreach ($headers as $key => $headerValues) {
|
||||
if (Psr7\Utils::caselessEquals((string) $key, $name)) {
|
||||
\array_push($values, ...$headerValues);
|
||||
unset($headers[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an associative array of lowercase header names to the actual
|
||||
* header casing.
|
||||
*/
|
||||
public static function normalizeHeaderKeys(array $headers): array
|
||||
{
|
||||
$result = [];
|
||||
foreach (\array_keys($headers) as $key) {
|
||||
$result[Psr7\Utils::asciiToLower((string) $key)] = $key;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a response uses ordinary body framing. A response to HEAD, a
|
||||
* response with a 1xx, 204, or 304 status code, or a 2xx response to
|
||||
* CONNECT never has a body, whatever its framing headers claim. A 205
|
||||
* remains subject to framing even though its semantics require no content.
|
||||
*/
|
||||
public static function responseCanHaveBody(string $method, int $status): bool
|
||||
{
|
||||
return $method !== 'HEAD'
|
||||
&& !($method === 'CONNECT' && $status >= 200 && $status < 300)
|
||||
&& $status >= 200
|
||||
&& $status !== 204
|
||||
&& $status !== 304;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param non-empty-list<string> $headers
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function getLastHeaderBlock(array $headers): array
|
||||
{
|
||||
$lastStatusLine = 0;
|
||||
|
||||
foreach ($headers as $index => $line) {
|
||||
if (self::isStatusLineCandidate($line)) {
|
||||
$lastStatusLine = $index;
|
||||
}
|
||||
}
|
||||
|
||||
return \array_slice($headers, $lastStatusLine);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Rejects request hosts that a handler could resolve differently from the host
|
||||
* the request names.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class HostValidator
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a request names one unambiguous network host.
|
||||
*
|
||||
* A handler reparses the URI but sends the Host header as given. The URI
|
||||
* host must therefore be printable ASCII, free of percent escapes, a valid
|
||||
* RFC 3986 host, and not numeric-looking parts followed by trailing dots.
|
||||
* Every Host header value must be printable ASCII.
|
||||
*
|
||||
* @throws RequestException
|
||||
*/
|
||||
public static function assertRequestHost(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
self::assertUriHost($request->getUri()->getHost(), $request);
|
||||
|
||||
foreach ($request->getHeader('Host') as $value) {
|
||||
self::assertPrintableAscii((string) $value, 'The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only the URI host is reparsed for the connection. A Host header is sent
|
||||
* verbatim and may carry a port, brackets, and an RFC 6874 zone identifier.
|
||||
*
|
||||
* @throws RequestException
|
||||
*/
|
||||
private static function assertUriHost(
|
||||
string $host,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
self::assertPrintableAscii($host, 'The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
|
||||
|
||||
if (\strpos($host, '%') !== false) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler decodes it and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
|
||||
}
|
||||
|
||||
// GuzzleHttp\Psr7\Uri already enforces this predicate, so it only
|
||||
// rejects invalid third-party UriInterface values.
|
||||
if (!Psr7\Rfc3986::isValidHost($host)) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must be a valid RFC 3986 host, because a handler reparses the URI and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
|
||||
}
|
||||
|
||||
// libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric
|
||||
// hosts before connecting, while other readers treat the input as a
|
||||
// name. Test the shape rather than the range so malformed numeric
|
||||
// values fail closed. rtrim() also covers multiple trailing dots if
|
||||
// libcurl later relaxes its current guard. Plain shorthand stays
|
||||
// accepted. HostIdentity uses a broader grammar for cookie matching.
|
||||
//
|
||||
// @see \GuzzleHttp\HostIdentity::canonicalHost()
|
||||
if (\str_ends_with($host, '.') && self::isNumericIpv4Host(\rtrim($host, '.'))) {
|
||||
throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether a host has libcurl's inet_aton-style shape: one to four
|
||||
* decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
|
||||
*
|
||||
* Range and 32-bit overflow checks are deliberately omitted. This may
|
||||
* reject a trailing-dot spelling the transport reads as a name, but avoids
|
||||
* missing one it resolves as an address.
|
||||
*/
|
||||
public static function isNumericIpv4Host(string $host): bool
|
||||
{
|
||||
if ($host === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$parts = \explode('.', $host);
|
||||
|
||||
if (\count($parts) > 4) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($parts as $part) {
|
||||
if (!self::isNumericIpv4Part($part)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function isNumericIpv4Part(string $part): bool
|
||||
{
|
||||
if ($part === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
|
||||
return \strlen($part) > 2 && \strspn($part, '0123456789abcdefABCDEF', 2) === \strlen($part) - 2;
|
||||
}
|
||||
|
||||
$digits = $part[0] === '0' ? '01234567' : '0123456789';
|
||||
|
||||
return \strspn($part, $digits) === \strlen($part);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws RequestException
|
||||
*/
|
||||
private static function assertPrintableAscii(
|
||||
string $value,
|
||||
string $message,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): void {
|
||||
// Match positively so a PCRE failure rejects.
|
||||
if (\preg_match('/\A[\x21-\x7E]*\z/D', $value) !== 1) {
|
||||
throw new RequestException(\sprintf($message, self::escape($value)), $request);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
|
||||
*
|
||||
* Psr7\DiagnosticValue is not used because it preserves valid non-ASCII
|
||||
* UTF-8, including invisible characters rejected here.
|
||||
*/
|
||||
private static function escape(string $value): string
|
||||
{
|
||||
$escaped = '';
|
||||
|
||||
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
|
||||
$byte = \ord($value[$offset]);
|
||||
if ($byte >= 0x20 && $byte <= 0x7E) {
|
||||
$escaped .= $value[$offset];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$escaped .= \sprintf('\\x%02X', $byte);
|
||||
}
|
||||
|
||||
return $escaped;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamWrapper;
|
||||
use GuzzleHttp\Psr7\Utils;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Inflates a gzip or deflate encoded response body as the encoded bytes arrive.
|
||||
*
|
||||
* Unlike the zlib.inflate stream filter, a read returns the bytes decoded so
|
||||
* far instead of waiting to fill the requested length, and invalid compressed
|
||||
* data always fails the read. As with libcurl, data after the compressed
|
||||
* stream, beyond up to 4 bytes after raw deflate data, fails the read that
|
||||
* follows the last decoded byte.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class InflateBodyStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
private const CHUNK_SIZE = 8192;
|
||||
|
||||
private const INVALID_DATA = 'Unable to decode the response body: invalid gzip or deflate data';
|
||||
|
||||
private const TRAILING_DATA = 'Unable to decode the response body: unexpected data after the compressed stream';
|
||||
|
||||
private ?StreamInterface $stream;
|
||||
|
||||
private bool $deflate;
|
||||
|
||||
/** @var \InflateContext|resource|null */
|
||||
private $context;
|
||||
|
||||
private string $header = '';
|
||||
|
||||
private string $buffer = '';
|
||||
|
||||
private int $offset = 0;
|
||||
|
||||
private int $position = 0;
|
||||
|
||||
private bool $finished = false;
|
||||
|
||||
private int $trailingAllowance = 0;
|
||||
|
||||
private bool $detachable = true;
|
||||
|
||||
private ?\RuntimeException $error = null;
|
||||
|
||||
/**
|
||||
* @param bool $deflate Whether the body is labelled "deflate", which also
|
||||
* accepts raw deflate data like libcurl does.
|
||||
*/
|
||||
public function __construct(StreamInterface $stream, bool $deflate = false)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
$this->deflate = $deflate;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->getContents();
|
||||
}
|
||||
|
||||
public function getContents(): string
|
||||
{
|
||||
return Utils::copyToString($this);
|
||||
}
|
||||
|
||||
public function close(): void
|
||||
{
|
||||
$stream = $this->stream;
|
||||
$this->release();
|
||||
|
||||
if ($stream !== null) {
|
||||
$stream->close();
|
||||
}
|
||||
}
|
||||
|
||||
public function detach()
|
||||
{
|
||||
if ($this->stream === null || !$this->detachable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Hand the decoder over to a resource that keeps yielding decoded
|
||||
// bytes. That decoder cannot be detached again, so casting the resource
|
||||
// to a descriptor fails instead of recursing.
|
||||
$stream = clone $this;
|
||||
$stream->detachable = false;
|
||||
$this->release();
|
||||
|
||||
return StreamWrapper::getResource($stream);
|
||||
}
|
||||
|
||||
public function getSize(): ?int
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function tell(): int
|
||||
{
|
||||
$this->attached();
|
||||
|
||||
return $this->position;
|
||||
}
|
||||
|
||||
public function eof(): bool
|
||||
{
|
||||
$stream = $this->attached();
|
||||
|
||||
// A failed body never ends, so resource readers see the failure
|
||||
// instead of a clean end of the stream.
|
||||
return $this->error === null && $this->offset === \strlen($this->buffer) && $stream->eof();
|
||||
}
|
||||
|
||||
public function isSeekable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function seek(int $offset, int $whence = \SEEK_SET): void
|
||||
{
|
||||
throw new \RuntimeException('Stream is not seekable');
|
||||
}
|
||||
|
||||
public function rewind(): void
|
||||
{
|
||||
$this->seek(0);
|
||||
}
|
||||
|
||||
public function isWritable(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function write(string $string): int
|
||||
{
|
||||
throw new \RuntimeException('Cannot write to a non-writable stream');
|
||||
}
|
||||
|
||||
public function isReadable(): bool
|
||||
{
|
||||
return $this->stream !== null && $this->stream->isReadable();
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
$stream = $this->attached();
|
||||
|
||||
if ($length < 0) {
|
||||
throw new \RuntimeException('Length parameter cannot be negative');
|
||||
}
|
||||
|
||||
if ($length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
while ($this->offset === \strlen($this->buffer)) {
|
||||
if ($this->error !== null) {
|
||||
throw $this->error;
|
||||
}
|
||||
|
||||
$encoded = $stream->read(self::CHUNK_SIZE);
|
||||
if ($encoded === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($this->finished) {
|
||||
if ($this->allowTrailing(\strlen($encoded))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
throw $this->fail(self::TRAILING_DATA);
|
||||
}
|
||||
|
||||
$this->buffer = $this->inflate($encoded);
|
||||
$this->offset = 0;
|
||||
}
|
||||
|
||||
// Slice by offset, since a single inflate_add() call can return
|
||||
// megabytes of highly compressible data.
|
||||
$data = (string) \substr($this->buffer, $this->offset, $length);
|
||||
$this->offset += \strlen($data);
|
||||
$this->position = TransferByteCounter::add(
|
||||
$this->position,
|
||||
\strlen($data),
|
||||
'Response body exceeds the maximum integer size supported on this platform'
|
||||
);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getMetadata(?string $key = null)
|
||||
{
|
||||
if ($this->stream === null) {
|
||||
return $key === null ? [] : null;
|
||||
}
|
||||
|
||||
// A decoding failure is not a timeout, even when Windows leaves the
|
||||
// transport's timed_out flag set after a read drains PHP's buffer.
|
||||
if ($key === 'timed_out' && $this->error !== null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$metadata = $this->stream->getMetadata($key);
|
||||
if ($key === null && $this->error !== null && \is_array($metadata)) {
|
||||
$metadata['timed_out'] = false;
|
||||
}
|
||||
|
||||
return $metadata;
|
||||
}
|
||||
|
||||
private function inflate(string $encoded, ?int $encoding = null): string
|
||||
{
|
||||
$retry = false;
|
||||
if ($this->context === null) {
|
||||
$this->header .= $encoded;
|
||||
if (\strlen($this->header) < 2) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$encoded = $this->header;
|
||||
$this->header = '';
|
||||
|
||||
if (!\function_exists('inflate_init')) {
|
||||
throw $this->fail('Unable to decode the response body: the zlib extension is not loaded');
|
||||
}
|
||||
|
||||
// inflate_init() has no automatic header detection, so pick the
|
||||
// format the way zlib does for the window bits 15 + 32 that the
|
||||
// zlib.inflate filter is given.
|
||||
$encoding = $encoding ?? (\strncmp($encoded, "\x1f\x8b", 2) === 0 ? \ZLIB_ENCODING_GZIP : \ZLIB_ENCODING_DEFLATE);
|
||||
$retry = $this->deflate && $encoding === \ZLIB_ENCODING_DEFLATE;
|
||||
$context = \inflate_init($encoding);
|
||||
if ($context === false) {
|
||||
throw $this->fail(self::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->context = $context;
|
||||
}
|
||||
|
||||
$readBefore = \inflate_get_read_len($this->context);
|
||||
|
||||
// Application error handlers also see @-suppressed warnings, so keep
|
||||
// the warning inflate_add() emits before returning false from them.
|
||||
\set_error_handler(static function (): bool {
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
$decoded = \inflate_add($this->context, $encoded);
|
||||
} finally {
|
||||
\restore_error_handler();
|
||||
}
|
||||
|
||||
if ($decoded === false) {
|
||||
// Like libcurl, decode deflate data that zlib rejects in the first
|
||||
// call as raw deflate, which may be followed by up to 4 unknown
|
||||
// bytes such as the checksum of a zlib stream missing its header.
|
||||
if ($retry) {
|
||||
$this->context = null;
|
||||
$this->trailingAllowance = 4;
|
||||
|
||||
return $this->inflate($encoded, \ZLIB_ENCODING_RAW);
|
||||
}
|
||||
|
||||
throw $this->fail(self::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->finished = \inflate_get_status($this->context) === \ZLIB_STREAM_END;
|
||||
if ($this->finished) {
|
||||
$consumed = \inflate_get_read_len($this->context) - $readBefore;
|
||||
if ($consumed < 0) {
|
||||
// zlib counts input in an unsigned long, which wraps at 4 GiB
|
||||
// on Windows and 32-bit builds.
|
||||
$consumed += 0x100000000;
|
||||
}
|
||||
|
||||
if (!$this->allowTrailing(\strlen($encoded) - (int) $consumed)) {
|
||||
// Throw only after the bytes decoded so far have been read.
|
||||
$this->fail(self::TRAILING_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
private function allowTrailing(int $length): bool
|
||||
{
|
||||
if ($length > $this->trailingAllowance) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->trailingAllowance -= $length;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function attached(): StreamInterface
|
||||
{
|
||||
if ($this->stream === null) {
|
||||
throw new \RuntimeException('Stream is detached');
|
||||
}
|
||||
|
||||
return $this->stream;
|
||||
}
|
||||
|
||||
private function release(): void
|
||||
{
|
||||
$this->stream = null;
|
||||
$this->context = null;
|
||||
$this->buffer = '';
|
||||
$this->offset = 0;
|
||||
}
|
||||
|
||||
private function fail(string $message): \RuntimeException
|
||||
{
|
||||
return $this->error = new \RuntimeException($message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Handler that returns responses or rejection reasons from a queue.
|
||||
*/
|
||||
final class MockHandler implements \Countable
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var list<ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>
|
||||
*/
|
||||
private array $queue = [];
|
||||
|
||||
private ?RequestInterface $lastRequest = null;
|
||||
|
||||
/**
|
||||
* @var array<array-key, mixed>
|
||||
*/
|
||||
private array $lastOptions = [];
|
||||
|
||||
/**
|
||||
* @var (callable(ResponseInterface|null): mixed)|null
|
||||
*/
|
||||
private $onFulfilled;
|
||||
|
||||
/**
|
||||
* @var (callable(mixed): mixed)|null
|
||||
*/
|
||||
private $onRejected;
|
||||
|
||||
/**
|
||||
* Creates a new MockHandler that uses the default handler stack list of
|
||||
* middlewares.
|
||||
*
|
||||
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue Array of responses, promises, callables, or throwables.
|
||||
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
|
||||
*
|
||||
* @return HandlerStack<callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>>
|
||||
*/
|
||||
public static function createWithMiddleware(
|
||||
#[\SensitiveParameter]
|
||||
?array $queue = null,
|
||||
?callable $onFulfilled = null,
|
||||
?callable $onRejected = null
|
||||
): HandlerStack {
|
||||
return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
|
||||
}
|
||||
|
||||
/**
|
||||
* The passed in value must be an array of
|
||||
* {@see ResponseInterface} objects, throwables, callables, or promises.
|
||||
*
|
||||
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue The parameters to be passed to the append function, as an indexed array.
|
||||
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
|
||||
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
|
||||
*/
|
||||
public function __construct(
|
||||
#[\SensitiveParameter]
|
||||
?array $queue = null,
|
||||
?callable $onFulfilled = null,
|
||||
?callable $onRejected = null
|
||||
) {
|
||||
$this->onFulfilled = $onFulfilled;
|
||||
$this->onRejected = $onRejected;
|
||||
|
||||
if ($queue) {
|
||||
// array_values included for BC
|
||||
$this->append(...array_values($queue));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
if (!$this->queue) {
|
||||
// Test-setup error (more requests made than responses queued);
|
||||
// intentionally a bare SPL exception, not a GuzzleException.
|
||||
throw new \OutOfBoundsException('Mock queue is empty');
|
||||
}
|
||||
|
||||
if (isset($options['delay']) && \is_numeric($options['delay'])) {
|
||||
Clock::sleep((int) ($options['delay'] * 1000));
|
||||
}
|
||||
|
||||
if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) {
|
||||
throw new InvalidArgumentException('on_stats must be callable');
|
||||
}
|
||||
|
||||
$this->lastRequest = $request;
|
||||
$this->lastOptions = $options;
|
||||
$response = \array_shift($this->queue);
|
||||
$onHeaders = null;
|
||||
$onHeadersResponse = null;
|
||||
|
||||
if (isset($options['on_headers'])) {
|
||||
if (!\is_callable($options['on_headers'])) {
|
||||
throw new InvalidArgumentException('on_headers must be callable');
|
||||
}
|
||||
|
||||
$onHeaders = $options['on_headers'];
|
||||
}
|
||||
|
||||
if (\is_callable($response)) {
|
||||
$response = $response($request, $options);
|
||||
}
|
||||
|
||||
$response = $response instanceof \Throwable
|
||||
? P\Create::rejectionFor($response)
|
||||
: P\Create::promiseFor($response);
|
||||
|
||||
if (\is_callable($onHeaders)) {
|
||||
$response = $response->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
$value
|
||||
) use ($onHeaders, $request, &$onHeadersResponse) {
|
||||
if (!$value instanceof ResponseInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
try {
|
||||
$onHeaders($value, $request);
|
||||
} catch (\Throwable $e) {
|
||||
$msg = 'An error was encountered during the on_headers event';
|
||||
$onHeadersResponse = $value;
|
||||
|
||||
throw new ResponseException($msg, $request, $value, $e);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
$promise = $response->then(
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$value
|
||||
) use ($request, $options): ?ResponseInterface {
|
||||
/** @var ResponseInterface|null $value */
|
||||
$this->invokeStats($request, $options, $value);
|
||||
if ($this->onFulfilled) {
|
||||
($this->onFulfilled)($value);
|
||||
}
|
||||
|
||||
if ($value !== null && isset($options['sink'])) {
|
||||
$contents = (string) $value->getBody();
|
||||
$sink = $options['sink'];
|
||||
|
||||
if (\is_resource($sink)) {
|
||||
\fwrite($sink, $contents);
|
||||
} elseif (\is_string($sink)) {
|
||||
\file_put_contents($sink, $contents);
|
||||
} elseif ($sink instanceof StreamInterface) {
|
||||
$sink->write($contents);
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
},
|
||||
function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, $options, &$onHeadersResponse): PromiseInterface {
|
||||
$this->invokeStats($request, $options, $onHeadersResponse, $reason);
|
||||
if ($this->onRejected) {
|
||||
($this->onRejected)($reason);
|
||||
}
|
||||
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
);
|
||||
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> $promise */
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more variadic requests, exceptions, callables, or promises
|
||||
* to the queue.
|
||||
*
|
||||
* @param mixed ...$values Responses, promises, throwables, or request-aware callables.
|
||||
*/
|
||||
public function append(
|
||||
#[\SensitiveParameter]
|
||||
...$values
|
||||
): void {
|
||||
foreach ($values as $value) {
|
||||
if ($value instanceof ResponseInterface
|
||||
|| $value instanceof \Throwable
|
||||
|| $value instanceof PromiseInterface
|
||||
|| \is_callable($value)
|
||||
) {
|
||||
$this->queue[] = $value;
|
||||
} else {
|
||||
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.\get_debug_type($value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last received request.
|
||||
*/
|
||||
public function getLastRequest(): ?RequestInterface
|
||||
{
|
||||
return $this->lastRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last received request options.
|
||||
*/
|
||||
public function getLastOptions(): array
|
||||
{
|
||||
return $this->lastOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of remaining items in the queue.
|
||||
*/
|
||||
public function count(): int
|
||||
{
|
||||
return \count($this->queue);
|
||||
}
|
||||
|
||||
public function reset(): void
|
||||
{
|
||||
$this->queue = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $reason Promise or reason.
|
||||
*/
|
||||
private function invokeStats(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
?ResponseInterface $response = null,
|
||||
#[\SensitiveParameter]
|
||||
$reason = null
|
||||
): void {
|
||||
if (isset($options['on_stats'])) {
|
||||
$transferTime = $options['transfer_time'] ?? 0.0;
|
||||
if (!\is_int($transferTime) && !\is_float($transferTime) && (!\is_string($transferTime) || !\is_numeric($transferTime))) {
|
||||
throw new InvalidArgumentException('transfer_time must be a number of seconds');
|
||||
}
|
||||
|
||||
$stats = new TransferStats($request, $response, (float) $transferTime, $reason);
|
||||
($options['on_stats'])($stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Protocols
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $protocols
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function normalize($protocols): array
|
||||
{
|
||||
if (!\is_array($protocols) || $protocols === []) {
|
||||
throw new InvalidArgumentException('protocols must be a non-empty array of "http" and/or "https"');
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
|
||||
foreach ($protocols as $protocol) {
|
||||
if (!\is_string($protocol)) {
|
||||
throw new InvalidArgumentException('protocols must contain only strings');
|
||||
}
|
||||
|
||||
if ($protocol !== 'http' && $protocol !== 'https') {
|
||||
throw new InvalidArgumentException('protocols may only contain "http" and "https"');
|
||||
}
|
||||
|
||||
$normalized[$protocol] = true;
|
||||
}
|
||||
|
||||
return \array_keys($normalized);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\RequestOptions;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Provides basic proxies for handlers.
|
||||
*/
|
||||
final class Proxy
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends synchronous requests to a specific handler while sending all other
|
||||
* requests to another handler.
|
||||
*
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for normal responses
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $sync Handler used for synchronous responses.
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
|
||||
*/
|
||||
public static function wrapSync(callable $default, callable $sync): callable
|
||||
{
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($default, $sync): PromiseInterface {
|
||||
return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends streaming requests to a streaming compatible handler while sending
|
||||
* all other requests to a default handler.
|
||||
*
|
||||
* This, for example, could be useful for taking advantage of the
|
||||
* performance benefits of curl while still supporting true streaming
|
||||
* through the StreamHandler.
|
||||
*
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for non-streaming responses
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $streaming Handler used for streaming responses
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
|
||||
*/
|
||||
public static function wrapStreaming(callable $default, callable $streaming): callable
|
||||
{
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($default, $streaming): PromiseInterface {
|
||||
return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options);
|
||||
};
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\ProxyOptions;
|
||||
use GuzzleHttp\ProxySelection;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Resolves proxy configuration from the process environment with the same
|
||||
* semantics libcurl applies, shared by the built-in handlers: the cURL
|
||||
* handlers pin CURLOPT_PROXY and CURLOPT_NOPROXY explicitly so libcurl never
|
||||
* reads the environment itself, and the stream handler resolves the same way.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class ProxyEnv
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the proxy selection for a request, falling back to the proxy
|
||||
* environment variables when the proxy request option makes no decision.
|
||||
*
|
||||
* The environment no_proxy list is tokenized the way libcurl tokenizes
|
||||
* it and matched here with the same rules as the proxy option's "no"
|
||||
* list, so behavior does not depend on the installed libcurl's matcher.
|
||||
*
|
||||
* @param mixed $proxyOption
|
||||
*/
|
||||
public static function resolveProxySelection(
|
||||
UriInterface $uri,
|
||||
#[\SensitiveParameter]
|
||||
$proxyOption
|
||||
): ProxySelection {
|
||||
$selection = ProxyOptions::resolve($uri, $proxyOption);
|
||||
|
||||
// Any option decision (proxy, bypassed, or disabled) is final; only
|
||||
// a none() selection leaves room for the environment.
|
||||
if ($selection->hasProxy() || $selection->shouldDisableProxy()) {
|
||||
return $selection;
|
||||
}
|
||||
|
||||
$envProxy = self::getProxyForScheme($uri->getScheme());
|
||||
if ($envProxy === null) {
|
||||
return $selection;
|
||||
}
|
||||
|
||||
$noProxy = self::getNoProxy();
|
||||
if ($noProxy !== null && ProxyOptions::isUriInNoProxy($uri, self::splitNoProxy($noProxy))) {
|
||||
return ProxySelection::bypassed();
|
||||
}
|
||||
|
||||
// $envProxy is never '' (empty env values are treated as unset).
|
||||
return ProxySelection::proxy($envProxy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the proxy to use for the given request scheme.
|
||||
*
|
||||
* The lookup mirrors libcurl for the http and https schemes the handlers
|
||||
* accept: the lowercase scheme-specific variable first, its uppercase
|
||||
* variant next (except for "http", where uppercase HTTP_PROXY is never
|
||||
* read), then all_proxy/ALL_PROXY.
|
||||
*
|
||||
* @return string|null The proxy to use; null when the environment
|
||||
* configures none.
|
||||
*/
|
||||
public static function getProxyForScheme(string $scheme): ?string
|
||||
{
|
||||
$scheme = Psr7\Utils::asciiToLower($scheme);
|
||||
$candidates = [$scheme.'_proxy'];
|
||||
if ($scheme !== 'http') {
|
||||
// Uppercase HTTP_PROXY is deliberately never consulted: a CGI
|
||||
// request header "Proxy:" becomes HTTP_PROXY in the environment.
|
||||
// See https://httpoxy.org for more information.
|
||||
$candidates[] = Psr7\Utils::asciiToUpper($scheme).'_PROXY';
|
||||
}
|
||||
$candidates[] = 'all_proxy';
|
||||
$candidates[] = 'ALL_PROXY';
|
||||
|
||||
foreach ($candidates as $name) {
|
||||
$value = self::getenv($name);
|
||||
if ($value !== null) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null The no-proxy list; null when nothing is set.
|
||||
*/
|
||||
public static function getNoProxy(): ?string
|
||||
{
|
||||
foreach (['no_proxy', 'NO_PROXY'] as $name) {
|
||||
$value = self::getenv($name);
|
||||
if ($value !== null) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits a no_proxy environment value into matchable entries.
|
||||
*
|
||||
* Entries may be separated by commas or blanks, the way libcurl tokenizes
|
||||
* the value.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function splitNoProxy(string $noProxy): array
|
||||
{
|
||||
$entries = [];
|
||||
|
||||
$split = \preg_split('/[\s,]+/', $noProxy);
|
||||
|
||||
if ($split === false) {
|
||||
throw new \RuntimeException('Unable to split the no_proxy value: '.\preg_last_error_msg());
|
||||
}
|
||||
|
||||
foreach ($split as $entry) {
|
||||
if ($entry !== '') {
|
||||
$entries[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
private static function getenv(string $name): ?string
|
||||
{
|
||||
// Windows environment variables are case-insensitive, so the
|
||||
// lowercase-only httpoxy defence does not hold there. Outside the
|
||||
// CLI SAPI on Windows, environment proxies are not resolved at all
|
||||
// (a safe-side divergence from libcurl).
|
||||
if (\PHP_OS_FAMILY === 'Windows' && \PHP_SAPI !== 'cli') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// local_only: the OS environment and putenv() only - the same
|
||||
// environ(7) libcurl reads. SAPI request environments such as
|
||||
// fastcgi_param or SetEnv are deliberately excluded.
|
||||
$value = \getenv($name, true);
|
||||
|
||||
// libcurl's GetEnv (lib/getenv.c) treats variables set to an empty
|
||||
// string as unset on every version, so the lookup falls through to
|
||||
// the next candidate.
|
||||
return $value === false || $value === '' ? null : $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\Psr7\Exception\TimeoutException;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
* Validates and normalizes request framing before a handler performs I/O.
|
||||
*
|
||||
* Body size describes the bytes available under handler rewind semantics.
|
||||
* Content-Length is the selected transport boundary and may remain unknown.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class RequestFraming
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
public RequestInterface $request;
|
||||
|
||||
/**
|
||||
* Number of bytes available after applying handler rewind semantics, if
|
||||
* known.
|
||||
*/
|
||||
public ?int $bodySize;
|
||||
|
||||
/** Canonical Content-Length boundary selected for transport, if any. */
|
||||
public ?int $contentLength;
|
||||
|
||||
private function __construct(RequestInterface $request, ?int $bodySize, ?int $contentLength)
|
||||
{
|
||||
$this->request = $request;
|
||||
$this->bodySize = $bodySize;
|
||||
$this->contentLength = $contentLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalizes request framing for a handler dispatch.
|
||||
*
|
||||
* When $sendBody is false, body-dependent validation and size probing are
|
||||
* skipped. Content-Length is still canonicalized and Transfer-Encoding is
|
||||
* removed.
|
||||
*
|
||||
* @throws RequestException when framing or body metadata is unsafe
|
||||
*/
|
||||
public static function analyze(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
bool $sendBody = true
|
||||
): self {
|
||||
try {
|
||||
$length = HeaderProcessor::parseContentLength($request->getHeader('Content-Length'));
|
||||
} catch (\RuntimeException $e) {
|
||||
throw new RequestException('Invalid Content-Length request header: '.$e->getMessage(), $request, 0, $e);
|
||||
}
|
||||
|
||||
try {
|
||||
HeaderProcessor::assertContentLengthWithinPlatformLimit($length);
|
||||
} catch (\OverflowException $e) {
|
||||
throw new RequestException($e->getMessage(), $request, 0, $e);
|
||||
}
|
||||
|
||||
$contentLength = HeaderProcessor::contentLengthToInt($length);
|
||||
if ($length !== null) {
|
||||
$request = $request->withHeader('Content-Length', $length);
|
||||
}
|
||||
|
||||
if (!$sendBody) {
|
||||
return new self($request->withoutHeader('Transfer-Encoding'), null, $contentLength);
|
||||
}
|
||||
|
||||
$transferEncoding = $request->getHeader('Transfer-Encoding');
|
||||
if ($length !== null && $transferEncoding !== []) {
|
||||
throw new RequestException(
|
||||
'A request must not contain both Content-Length and Transfer-Encoding',
|
||||
$request
|
||||
);
|
||||
}
|
||||
|
||||
if ($transferEncoding !== []) {
|
||||
$tokens = [];
|
||||
foreach ($transferEncoding as $value) {
|
||||
foreach (\explode(',', $value) as $part) {
|
||||
$tokens[] = \trim($part, " \t");
|
||||
}
|
||||
}
|
||||
|
||||
if (\count($tokens) !== 1 || !Psr7\Utils::caselessEquals($tokens[0], 'chunked') || $request->getProtocolVersion() !== '1.1') {
|
||||
throw new RequestException('Unsupported Transfer-Encoding request header', $request);
|
||||
}
|
||||
}
|
||||
|
||||
$bodySize = self::bodySize($request);
|
||||
if ($bodySize !== null && $contentLength !== null && $bodySize !== $contentLength) {
|
||||
throw new RequestException('Content-Length does not match the request body size', $request);
|
||||
}
|
||||
|
||||
if ($bodySize === null && $contentLength === null && $request->getProtocolVersion() === '1.0') {
|
||||
throw new RequestException('An unknown-size HTTP/1.0 request body requires Content-Length', $request);
|
||||
}
|
||||
|
||||
if ($length === null && $bodySize !== null && ($bodySize > 0 || \in_array($request->getMethod(), ['PUT', 'POST'], true))) {
|
||||
$contentLength = $bodySize;
|
||||
$request = $request->withHeader('Content-Length', (string) $bodySize);
|
||||
}
|
||||
|
||||
return new self($request->withoutHeader('Transfer-Encoding'), $bodySize, $contentLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of bytes available for dispatch, or null when unknown.
|
||||
*
|
||||
* Seekable bodies use their total size because handlers rewind them.
|
||||
* Positioned non-seekable bodies use the total size minus their current
|
||||
* position.
|
||||
*
|
||||
* @throws RequestException when body metadata cannot be read safely
|
||||
*/
|
||||
public static function bodySize(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
): ?int {
|
||||
$body = $request->getBody();
|
||||
|
||||
try {
|
||||
$size = $body->getSize();
|
||||
if ($size === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($size < 0) {
|
||||
throw new \RuntimeException('Request body size must not be negative');
|
||||
}
|
||||
|
||||
$seekable = $body->isSeekable();
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$request,
|
||||
$e,
|
||||
'Timed out while determining the request body size',
|
||||
'Failed to determine the request body size'
|
||||
);
|
||||
}
|
||||
|
||||
if ($seekable) {
|
||||
return $size;
|
||||
}
|
||||
|
||||
try {
|
||||
$position = $body->tell();
|
||||
} catch (\RuntimeException $e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($position < 0 || $position > $size) {
|
||||
throw new RequestException('The request body position is outside the stream size', $request);
|
||||
}
|
||||
|
||||
return $size - $position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes the body, stopping at the selected Content-Length when
|
||||
* present.
|
||||
*
|
||||
* @throws RequestException when the body cannot be fully rewound or read
|
||||
*/
|
||||
public function materialize(): string
|
||||
{
|
||||
$body = $this->request->getBody();
|
||||
|
||||
if ($this->contentLength === null) {
|
||||
try {
|
||||
return (string) $body;
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while reading the request body',
|
||||
'Failed to read the request body'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->contentLength === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
if ($body->isSeekable()) {
|
||||
$body->rewind();
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while rewinding the request body',
|
||||
'Failed to rewind the request body'
|
||||
);
|
||||
}
|
||||
|
||||
$contents = '';
|
||||
$remaining = $this->contentLength;
|
||||
while ($remaining > 0) {
|
||||
$limit = \min(8192, $remaining);
|
||||
|
||||
try {
|
||||
$chunk = $body->read($limit);
|
||||
} catch (\Exception $e) {
|
||||
throw self::bodyException(
|
||||
$this->request,
|
||||
$e,
|
||||
'Timed out while reading the request body',
|
||||
'Failed to read the request body'
|
||||
);
|
||||
}
|
||||
|
||||
if ($chunk === '') {
|
||||
throw new RequestException(
|
||||
'Request body ended before the declared Content-Length was reached',
|
||||
$this->request
|
||||
);
|
||||
}
|
||||
|
||||
if (\strlen($chunk) > $limit) {
|
||||
throw new RequestException('Request body stream returned more bytes than requested', $this->request);
|
||||
}
|
||||
|
||||
$contents .= $chunk;
|
||||
$remaining -= \strlen($chunk);
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
private static function bodyException(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
\Exception $exception,
|
||||
string $timeoutMessage,
|
||||
string $fallbackMessage
|
||||
): RequestException {
|
||||
$message = $exception instanceof TimeoutException
|
||||
? $timeoutMessage
|
||||
: ($exception->getMessage() !== '' ? $exception->getMessage() : $fallbackMessage);
|
||||
|
||||
return new RequestException($message, $request, 0, $exception);
|
||||
}
|
||||
}
|
||||
+2073
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,583 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\HostIdentity;
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Openssl\Session;
|
||||
|
||||
/**
|
||||
* Per-handler in-memory TLS session resumption cache for the stream handler.
|
||||
*
|
||||
* Backed by the OpenSSL TLS session API added in PHP 8.6. A session is only
|
||||
* ever replayed for an identical TLS identity: the non-secret identity is
|
||||
* encoded in the lookup key and secret material is matched in constant time.
|
||||
* TLS resumption reuses the original certificate-chain verification result
|
||||
* instead of building and verifying the chain again. Guzzle includes ambient
|
||||
* trust configuration paths in the cache identity, but cannot detect
|
||||
* trust-store contents rewritten at an unchanged path. Recreate the handler
|
||||
* or disable transport sharing when trust changes must take effect
|
||||
* immediately.
|
||||
*
|
||||
* New sessions are held temporarily and committed only after the HTTPS stream
|
||||
* opens successfully. If PHP rejects peer verification or another stream-open
|
||||
* step fails, any session reported during that attempt is discarded.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class StreamTlsSessionCache
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* Sessions retained per peer. libcurl uses 2 to buffer single-use TLS 1.3
|
||||
* tickets; the synchronous stream handler does not need more.
|
||||
*/
|
||||
public const MAX_SESSIONS_PER_KEY = 2;
|
||||
|
||||
/**
|
||||
* TLS 1.3 tickets should not live longer than RFC 8446 allows. All
|
||||
* pre-TLS-1.3 sessions use libcurl's tighter one-day cap.
|
||||
*/
|
||||
private const MAX_TLS13_LIFETIME = 604800;
|
||||
private const MAX_PRE_TLS13_LIFETIME = 86400;
|
||||
|
||||
private const USER_MANAGED_SESSION_OPTIONS = [
|
||||
'session_cache' => true,
|
||||
'session_cache_size' => true,
|
||||
'session_data' => true,
|
||||
'session_get_cb' => true,
|
||||
'session_id_context' => true,
|
||||
'session_new_cb' => true,
|
||||
'session_remove_cb' => true,
|
||||
'session_stream' => true,
|
||||
'session_timeout' => true,
|
||||
];
|
||||
|
||||
private const USER_MANAGED_PSK_OPTIONS = [
|
||||
'psk_client_cb' => true,
|
||||
'psk_server_cb' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* TLS 1.3 early data (0-RTT) options are deliberately never shared: an
|
||||
* injected cached session would let PHP send the replayable early data
|
||||
* payload ahead of the HTTP request.
|
||||
*/
|
||||
private const USER_MANAGED_EARLY_DATA_OPTIONS = [
|
||||
'early_data' => true,
|
||||
'early_data_cb' => true,
|
||||
'max_early_data' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* File/path-bearing SSL context options are deliberately not shared: their
|
||||
* contents can change outside this handler.
|
||||
*/
|
||||
private const PATH_OPTIONS = [
|
||||
'SNI_server_certs' => true,
|
||||
'cafile' => true,
|
||||
'capath' => true,
|
||||
'dh_param' => true,
|
||||
'local_cert' => true,
|
||||
'local_pk' => true,
|
||||
];
|
||||
|
||||
private const CERT_CAPTURE_OPTIONS = [
|
||||
'capture_peer_cert' => true,
|
||||
'capture_peer_cert_chain' => true,
|
||||
];
|
||||
|
||||
/**
|
||||
* Scalar custom SSL context options that are known to be self-contained
|
||||
* and safe to include in the TLS session cache identity.
|
||||
*/
|
||||
private const CUSTOM_SCALAR_KEYABLE_OPTIONS = [
|
||||
'SNI_enabled' => true,
|
||||
'allow_self_signed' => true,
|
||||
'alpn_protocols' => true,
|
||||
'ciphers' => true,
|
||||
'crypto_method' => true,
|
||||
'disable_compression' => true,
|
||||
'max_proto_version' => true,
|
||||
'min_proto_version' => true,
|
||||
'peer_name' => true,
|
||||
'security_level' => true,
|
||||
'verify_depth' => true,
|
||||
'verify_peer' => true,
|
||||
'verify_peer_name' => true,
|
||||
];
|
||||
|
||||
private const INVALID_PEER_FINGERPRINT_REASON = 'the SSL context option "peer_fingerprint" must be a string or a non-empty, flat array with string algorithm names and string fingerprints.';
|
||||
|
||||
private int $maxKeys;
|
||||
|
||||
/**
|
||||
* @var array<string, list<array{session: Session, credentials: string, expiresAt: int, singleUse: bool}>>
|
||||
*/
|
||||
private array $sessions = [];
|
||||
|
||||
public function __construct(int $maxKeys)
|
||||
{
|
||||
if ($maxKeys < 1) {
|
||||
throw new InvalidArgumentException('maxKeys must be a positive integer.');
|
||||
}
|
||||
|
||||
$this->maxKeys = $maxKeys;
|
||||
}
|
||||
|
||||
public static function isSupported(): bool
|
||||
{
|
||||
// Any PHP 8.6 build qualifies, including pre-release and nightly
|
||||
// builds; the class check keeps unstable builds that do not carry
|
||||
// the final API fail-closed.
|
||||
return \PHP_VERSION_ID >= 80600 && \class_exists(Session::class, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $ssl The assembled 'ssl' stream context array.
|
||||
* @param array $customSsl The user-supplied stream_context['ssl'] array.
|
||||
*/
|
||||
public static function unsupportedContextReason(array $ssl, array $customSsl = []): ?string
|
||||
{
|
||||
foreach ($customSsl as $key => $value) {
|
||||
if (
|
||||
!isset(self::CUSTOM_SCALAR_KEYABLE_OPTIONS[$key])
|
||||
&& !isset(self::PATH_OPTIONS[$key])
|
||||
&& !isset(self::USER_MANAGED_SESSION_OPTIONS[$key])
|
||||
&& !isset(self::USER_MANAGED_PSK_OPTIONS[$key])
|
||||
&& !isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key])
|
||||
&& !isset(self::CERT_CAPTURE_OPTIONS[$key])
|
||||
&& $key !== 'no_ticket'
|
||||
&& $key !== 'peer_fingerprint'
|
||||
) {
|
||||
return \sprintf('the custom SSL context option "%s" is not known to be safe for TLS session sharing.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($ssl as $key => $value) {
|
||||
if (isset(self::PATH_OPTIONS[$key])) {
|
||||
return \sprintf('the SSL context option "%s" uses file or path state that cannot be safely shared.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
|
||||
if (isset(self::USER_MANAGED_SESSION_OPTIONS[$key])) {
|
||||
return \sprintf('the SSL context option "%s" is user-managed TLS session state.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
|
||||
if (isset(self::USER_MANAGED_PSK_OPTIONS[$key])) {
|
||||
return \sprintf('the SSL context option "%s" is user-managed TLS PSK state.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
|
||||
if (isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key])) {
|
||||
return \sprintf('the SSL context option "%s" is user-managed TLS early data state.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
|
||||
if (isset(self::CERT_CAPTURE_OPTIONS[$key]) && $value) {
|
||||
return \sprintf('the SSL context option "%s" requires a fresh peer certificate handshake.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
|
||||
if ($key === 'no_ticket' && $value) {
|
||||
return 'the SSL context option "no_ticket" disables TLS ticket sharing.';
|
||||
}
|
||||
|
||||
if ($key === 'peer_fingerprint') {
|
||||
if (!self::isPeerFingerprint($value)) {
|
||||
return self::INVALID_PEER_FINGERPRINT_REASON;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!self::isCanonicalScalar($value)) {
|
||||
return \sprintf('the SSL context option "%s" cannot be safely included in the TLS session cache identity.', Psr7\DiagnosticValue::escape((string) $key));
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the non-secret lookup key: host/port plus every TLS parameter that
|
||||
* defines the verification/identity context. Keyed on the connection host
|
||||
* a transport reads, with numeric IPv4 spellings folded to one dotted
|
||||
* quad; names are never resolved. Secret material is excluded.
|
||||
*
|
||||
* @param array $ssl The assembled 'ssl' stream context array.
|
||||
*/
|
||||
public static function peerKey(
|
||||
string $host,
|
||||
?int $port,
|
||||
#[\SensitiveParameter]
|
||||
array $ssl
|
||||
): string {
|
||||
$identity = [
|
||||
'schema' => 'guzzle-stream-tls-session-v1',
|
||||
'runtime' => self::runtimeIdentity(),
|
||||
'peer' => [
|
||||
'host' => self::canonicalHost($host),
|
||||
'port' => $port,
|
||||
],
|
||||
'ssl' => self::canonicalPeerSslContext($ssl),
|
||||
];
|
||||
|
||||
return \hash('sha256', \serialize($identity));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the secret-aware credential fingerprint matched in constant time,
|
||||
* keeping the passphrase out of the loggable peer key.
|
||||
*
|
||||
* Every credential-bearing context is currently rejected by
|
||||
* unsupportedContextReason() before sharing, so fingerprints can only
|
||||
* diverge if the allow-lists are ever widened; the constant-time match is
|
||||
* retained as defense in depth for that case.
|
||||
*
|
||||
* @param array $ssl The assembled 'ssl' stream context array.
|
||||
*/
|
||||
public static function credentialFingerprint(array $ssl): string
|
||||
{
|
||||
$material = [
|
||||
'local_cert' => isset($ssl['local_cert']) && \is_string($ssl['local_cert']) ? self::pathIdentity($ssl['local_cert']) : null,
|
||||
'local_pk' => isset($ssl['local_pk']) && \is_string($ssl['local_pk']) ? self::pathIdentity($ssl['local_pk']) : null,
|
||||
'passphrase' => isset($ssl['passphrase']) && \is_string($ssl['passphrase']) ? $ssl['passphrase'] : null,
|
||||
];
|
||||
|
||||
return \hash('sha256', \serialize($material));
|
||||
}
|
||||
|
||||
public function find(string $key, string $credentials): ?Session
|
||||
{
|
||||
if (!isset($this->sessions[$key])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$now = \time();
|
||||
$entries = $this->sessions[$key];
|
||||
$found = null;
|
||||
|
||||
foreach ($entries as $i => $entry) {
|
||||
if ($entry['expiresAt'] <= $now) {
|
||||
unset($entries[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!\hash_equals($entry['credentials'], $credentials)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$entry['session']->isResumable()) {
|
||||
unset($entries[$i]);
|
||||
continue;
|
||||
}
|
||||
|
||||
$found = $entry['session'];
|
||||
|
||||
// TLS 1.3 tickets are single-use; consume on take.
|
||||
if ($entry['singleUse']) {
|
||||
unset($entries[$i]);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if ($entries === []) {
|
||||
unset($this->sessions[$key]);
|
||||
} else {
|
||||
$this->sessions[$key] = \array_values($entries);
|
||||
if ($found !== null) {
|
||||
$this->touch($key);
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
public function store(
|
||||
string $key,
|
||||
string $credentials,
|
||||
#[\SensitiveParameter]
|
||||
Session $session
|
||||
): void {
|
||||
if (!$session->isResumable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$expiresAt = self::expiry($session);
|
||||
if ($expiresAt === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$list = $this->sessions[$key] ?? [];
|
||||
$list[] = [
|
||||
'session' => $session,
|
||||
'credentials' => $credentials,
|
||||
'expiresAt' => $expiresAt,
|
||||
'singleUse' => self::isTls13($session),
|
||||
];
|
||||
|
||||
if (\count($list) > self::MAX_SESSIONS_PER_KEY) {
|
||||
$list = \array_slice($list, -self::MAX_SESSIONS_PER_KEY);
|
||||
}
|
||||
|
||||
$this->sessions[$key] = $list;
|
||||
$this->touch($key);
|
||||
$this->evictExcessKeys();
|
||||
}
|
||||
|
||||
private function touch(string $key): void
|
||||
{
|
||||
if (!isset($this->sessions[$key])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$value = $this->sessions[$key];
|
||||
unset($this->sessions[$key]);
|
||||
$this->sessions[$key] = $value;
|
||||
}
|
||||
|
||||
private function evictExcessKeys(): void
|
||||
{
|
||||
while (\count($this->sessions) > $this->maxKeys) {
|
||||
\array_shift($this->sessions);
|
||||
}
|
||||
}
|
||||
|
||||
private static function isTls13(
|
||||
#[\SensitiveParameter]
|
||||
Session $session
|
||||
): bool {
|
||||
$protocol = $session->getProtocol();
|
||||
|
||||
return $protocol !== null && Psr7\Utils::caselessContains($protocol, '1.3');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute expiry timestamp, or null when the session must
|
||||
* not be cached.
|
||||
*/
|
||||
private static function expiry(
|
||||
#[\SensitiveParameter]
|
||||
Session $session
|
||||
): ?int {
|
||||
return self::expiryFromLifetimes(
|
||||
self::isTls13($session),
|
||||
$session->hasTicket(),
|
||||
$session->getTicketLifetimeHint(),
|
||||
$session->getTimeout(),
|
||||
$session->getCreatedAt(),
|
||||
\time()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides the absolute expiry timestamp from a session's scalar lifetime
|
||||
* attributes, or null when the session must not be cached.
|
||||
*
|
||||
* A non-positive session timeout is never cached. TLS 1.3 resumption
|
||||
* requires a New Session Ticket, so a TLS 1.3 session without a ticket
|
||||
* or without a positive RFC 8446 ticket lifetime is not cached, and the
|
||||
* ticket lifetime bounds the expiry together with the session timeout
|
||||
* and the seven-day cap. Pre-TLS-1.3 tickets treat a zero or missing
|
||||
* lifetime hint as unspecified per RFC 5077, so only a positive hint
|
||||
* tightens the session timeout and the one-day cap. An expiry that has
|
||||
* already passed is not cached.
|
||||
*/
|
||||
private static function expiryFromLifetimes(bool $isTls13, bool $hasTicket, ?int $ticketLifetimeHint, int $timeout, int $createdAt, int $now): ?int
|
||||
{
|
||||
if ($timeout <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$lifetime = \min($timeout, $isTls13 ? self::MAX_TLS13_LIFETIME : self::MAX_PRE_TLS13_LIFETIME);
|
||||
|
||||
if ($isTls13) {
|
||||
if (!$hasTicket || $ticketLifetimeHint === null || $ticketLifetimeHint <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$lifetime = \min($lifetime, $ticketLifetimeHint);
|
||||
} elseif ($hasTicket && $ticketLifetimeHint !== null && $ticketLifetimeHint > 0) {
|
||||
$lifetime = \min($lifetime, $ticketLifetimeHint);
|
||||
}
|
||||
|
||||
$expiresAt = $createdAt + $lifetime;
|
||||
|
||||
return $expiresAt > $now ? $expiresAt : null;
|
||||
}
|
||||
|
||||
private static function runtimeIdentity(): array
|
||||
{
|
||||
return [
|
||||
'php' => \PHP_VERSION_ID,
|
||||
'openssl' => \defined('OPENSSL_VERSION_NUMBER') ? \OPENSSL_VERSION_NUMBER : null,
|
||||
'trust' => [
|
||||
'openssl.cafile' => (string) \ini_get('openssl.cafile'),
|
||||
'openssl.capath' => (string) \ini_get('openssl.capath'),
|
||||
'SSL_CERT_FILE' => (string) \getenv('SSL_CERT_FILE'),
|
||||
'SSL_CERT_DIR' => (string) \getenv('SSL_CERT_DIR'),
|
||||
'cwd' => \getcwd(),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the host identity hashed into the cache key. Valid bracketed
|
||||
* IPv6 literals are canonicalized to their RFC 5952 form so equivalent
|
||||
* spellings of one address share a single session entry; other valid
|
||||
* hosts, such as reg-names and IPvFuture literals, fall back to ASCII
|
||||
* case folding. Text that is not a valid RFC 3986 host, such as
|
||||
* zone-bearing or malformed bracketed literals, must never become a
|
||||
* usable cache key, so it is rejected.
|
||||
*/
|
||||
private static function canonicalHost(string $host): string
|
||||
{
|
||||
if (!Psr7\Rfc3986::isValidHost($host)) {
|
||||
throw new InvalidArgumentException('Hosts used in the TLS session cache identity must be valid RFC 3986 hosts.');
|
||||
}
|
||||
|
||||
return HostIdentity::canonicalHost($host);
|
||||
}
|
||||
|
||||
private static function canonicalPeerSslContext(
|
||||
#[\SensitiveParameter]
|
||||
array $ssl
|
||||
): array {
|
||||
$context = [];
|
||||
|
||||
foreach ($ssl as $key => $value) {
|
||||
if (isset(self::USER_MANAGED_SESSION_OPTIONS[$key]) || isset(self::USER_MANAGED_PSK_OPTIONS[$key]) || isset(self::USER_MANAGED_EARLY_DATA_OPTIONS[$key]) || $key === 'passphrase') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($key === 'peer_name' && \is_string($value)) {
|
||||
$context[$key] = ['string', self::canonicalHost($value)];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($key === 'peer_fingerprint') {
|
||||
$context[$key] = self::canonicalPeerFingerprint($value);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (\in_array($key, ['cafile', 'capath', 'local_cert', 'local_pk'], true) && \is_string($value)) {
|
||||
$context[$key] = self::pathIdentity($value);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$context[$key] = self::canonicalScalar($value);
|
||||
}
|
||||
|
||||
\ksort($context);
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
private static function pathIdentity(string $path): array
|
||||
{
|
||||
$realPath = \realpath($path);
|
||||
|
||||
return [
|
||||
'path',
|
||||
$realPath !== false ? $realPath : $path,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
private static function isCanonicalScalar($value): bool
|
||||
{
|
||||
return $value === null
|
||||
|| \is_bool($value)
|
||||
|| \is_int($value)
|
||||
|| \is_float($value)
|
||||
|| \is_string($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
private static function isPeerFingerprint($value): bool
|
||||
{
|
||||
if (\is_string($value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!\is_array($value) || $value === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($value as $algorithm => $fingerprint) {
|
||||
if (!\is_string($algorithm) || !\is_string($fingerprint)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return array{0: string, 1: mixed}
|
||||
*/
|
||||
private static function canonicalScalar($value): array
|
||||
{
|
||||
if ($value === null) {
|
||||
return ['null', null];
|
||||
}
|
||||
|
||||
if (\is_bool($value)) {
|
||||
return ['bool', $value];
|
||||
}
|
||||
|
||||
if (\is_int($value)) {
|
||||
return ['int', $value];
|
||||
}
|
||||
|
||||
if (\is_float($value)) {
|
||||
return ['float', \bin2hex(\pack('E', $value))];
|
||||
}
|
||||
|
||||
if (\is_string($value)) {
|
||||
return ['string', $value];
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('SSL context values used in the TLS session cache identity must be scalar or null.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return array{0: string, 1: mixed}
|
||||
*/
|
||||
private static function canonicalPeerFingerprint($value): array
|
||||
{
|
||||
if (!self::isPeerFingerprint($value)) {
|
||||
throw new InvalidArgumentException(self::INVALID_PEER_FINGERPRINT_REASON);
|
||||
}
|
||||
|
||||
if (\is_string($value)) {
|
||||
return ['string', $value];
|
||||
}
|
||||
|
||||
if (!\is_array($value)) {
|
||||
throw new InvalidArgumentException(self::INVALID_PEER_FINGERPRINT_REASON);
|
||||
}
|
||||
|
||||
$items = [];
|
||||
foreach ($value as $algorithm => $fingerprint) {
|
||||
$items[$algorithm] = ['string', $fingerprint];
|
||||
}
|
||||
\ksort($items, \SORT_STRING);
|
||||
|
||||
return ['map', $items];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Timeout
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a request timeout option to integer milliseconds.
|
||||
*
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function toMilliseconds($value, string $option): int
|
||||
{
|
||||
if (!\is_int($value) && !\is_float($value) && (!\is_string($value) || !\is_numeric($value))) {
|
||||
throw new InvalidArgumentException($option.' must be a number of seconds');
|
||||
}
|
||||
|
||||
$seconds = (float) $value;
|
||||
if (!\is_finite($seconds) || $seconds < 0) {
|
||||
throw new InvalidArgumentException($option.' must be 0 or greater than or equal to 0.001 seconds');
|
||||
}
|
||||
|
||||
$milliseconds = (int) ($seconds * 1000);
|
||||
if ($seconds > 0 && $milliseconds === 0) {
|
||||
throw new InvalidArgumentException($option.' must be 0 or greater than or equal to 0.001 seconds');
|
||||
}
|
||||
|
||||
return $milliseconds;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class TlsVersion
|
||||
{
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function ordinal(string $option, $value): int
|
||||
{
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
|
||||
return 10;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
|
||||
return 11;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
|
||||
return 12;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
|
||||
return 13;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $min
|
||||
* @param mixed $max
|
||||
*/
|
||||
public static function assertRange($min, $max): void
|
||||
{
|
||||
if ($min === null || $max === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (self::ordinal('crypto_method_max', $max) < self::ordinal('crypto_method', $min)) {
|
||||
throw new InvalidArgumentException('Invalid crypto_method_max request option: maximum TLS version must be greater than or equal to crypto_method');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function streamProtocolVersion(string $option, $value): int
|
||||
{
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
|
||||
return \STREAM_CRYPTO_PROTO_TLSv1_0;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
|
||||
return \STREAM_CRYPTO_PROTO_TLSv1_1;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
|
||||
return \STREAM_CRYPTO_PROTO_TLSv1_2;
|
||||
}
|
||||
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
|
||||
return \STREAM_CRYPTO_PROTO_TLSv1_3;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class TransferByteCounter
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function progressValueToInt($value): int
|
||||
{
|
||||
if (\is_int($value)) {
|
||||
if ($value < 0) {
|
||||
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (!\is_float($value)) {
|
||||
throw new \UnexpectedValueException('Progress byte count must be an integer or float');
|
||||
}
|
||||
|
||||
if (
|
||||
!\is_finite($value)
|
||||
|| $value < 0
|
||||
|| $value > \PHP_INT_MAX
|
||||
|| (\PHP_INT_SIZE === 8 && $value >= (float) \PHP_INT_MAX)
|
||||
) {
|
||||
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
$intValue = (int) $value;
|
||||
if ($intValue < 0) {
|
||||
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
|
||||
}
|
||||
|
||||
return $intValue;
|
||||
}
|
||||
|
||||
public static function add(int $current, int $delta, string $message): int
|
||||
{
|
||||
if ($current < 0 || $delta < 0) {
|
||||
throw new \OverflowException($message);
|
||||
}
|
||||
|
||||
if ($delta > \PHP_INT_MAX - $current) {
|
||||
throw new \OverflowException($message);
|
||||
}
|
||||
|
||||
return $current + $delta;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\NonSerializableTrait;
|
||||
use GuzzleHttp\Psr7\StreamDecoratorTrait;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Decorates the stream that wraps a response transport so a read never waits
|
||||
* on the network while PHP still holds bytes it has already received.
|
||||
*
|
||||
* Before PHP 8.3, a blocking read longer than the bytes PHP has buffered
|
||||
* returns them only after the next packet or EOF, which holds back body bytes
|
||||
* that arrived with the headers. PHP only fixed this for TLS in 8.4.24 and
|
||||
* 8.5.9. On Windows such a read can also mark the transport as timed out
|
||||
* although it returned bytes. Capping each read at the buffered length serves
|
||||
* it from PHP's buffer alone.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class TransportStream implements StreamInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
use StreamDecoratorTrait;
|
||||
|
||||
private StreamInterface $stream;
|
||||
|
||||
public function __construct(StreamInterface $stream)
|
||||
{
|
||||
$this->stream = $stream;
|
||||
}
|
||||
|
||||
public function __clone()
|
||||
{
|
||||
// Detaching a clone must not detach this body's transport.
|
||||
$this->stream = clone $this->stream;
|
||||
}
|
||||
|
||||
public function read(int $length): string
|
||||
{
|
||||
$buffered = $this->stream->getMetadata('unread_bytes');
|
||||
|
||||
return $this->stream->read(\is_int($buffered) && $buffered > 0 ? \min($length, $buffered) : $length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class UriDiagnostic
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
public static function redactInMessage(
|
||||
#[\SensitiveParameter]
|
||||
string $message,
|
||||
#[\SensitiveParameter]
|
||||
UriInterface $uri
|
||||
): string {
|
||||
$message = Psr7\UriRedactor::redactUserInfoInString($message, (string) $uri);
|
||||
|
||||
$query = $uri->getQuery();
|
||||
if ($query !== '') {
|
||||
$message = \str_replace('?'.$query, '', $message);
|
||||
}
|
||||
|
||||
$fragment = $uri->getFragment();
|
||||
if ($fragment !== '') {
|
||||
$message = \str_replace('#'.$fragment, '', $message);
|
||||
}
|
||||
|
||||
return Psr7\DiagnosticValue::escape($message);
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\DiagnosticValue;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Creates a composed Guzzle handler function by stacking middlewares on top of
|
||||
* an HTTP handler function.
|
||||
*
|
||||
* @template THandler
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class HandlerStack
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var (callable&THandler)|null
|
||||
*/
|
||||
private $handler;
|
||||
|
||||
/**
|
||||
* @var array<int, array{0: callable(callable&THandler): (callable&THandler), 1: string|null}>
|
||||
*/
|
||||
private array $stack = [];
|
||||
|
||||
/**
|
||||
* @var (callable&THandler)|null
|
||||
*/
|
||||
private $cached;
|
||||
|
||||
/**
|
||||
* Creates a default handler stack that can be used by clients.
|
||||
*
|
||||
* The returned handler will wrap the provided handler or use the most
|
||||
* appropriate default handler for your system. The returned HandlerStack
|
||||
* has support for authentication, cookies, redirects, HTTP error
|
||||
* exceptions, and preparing a body before sending.
|
||||
*
|
||||
* The returned handler stack can be passed to a client in the "handler"
|
||||
* option.
|
||||
*
|
||||
* @param (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)|null $handler HTTP handler function to use with the stack. If no
|
||||
* handler is provided, the best handler for your
|
||||
* system will be utilized.
|
||||
*
|
||||
* @return self<callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>>
|
||||
*/
|
||||
public static function create(?callable $handler = null): self
|
||||
{
|
||||
$stack = new self($handler ?: Utils::chooseHandler());
|
||||
$stack->push(Middleware::httpErrors(), 'http_errors');
|
||||
$stack->push(Middleware::redirect(), 'allow_redirects');
|
||||
$stack->push(Middleware::auth(), 'auth');
|
||||
$stack->push(Middleware::cookies(), 'cookies');
|
||||
$stack->push(Middleware::prepareBody(), 'prepare_body');
|
||||
|
||||
return $stack;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param (callable&THandler)|null $handler Underlying handler.
|
||||
*/
|
||||
public function __construct(?callable $handler = null)
|
||||
{
|
||||
$this->handler = $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes the handler stack as a composed handler
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) {
|
||||
$handler = $this->resolve();
|
||||
|
||||
return $handler($request, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the HTTP handler that actually returns a promise.
|
||||
*
|
||||
* @param callable&THandler $handler Accepts a request and array of options and returns a value expected by the stack.
|
||||
*/
|
||||
public function setHandler(callable $handler): void
|
||||
{
|
||||
$this->handler = $handler;
|
||||
$this->cached = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the builder has a handler.
|
||||
*/
|
||||
public function hasHandler(): bool
|
||||
{
|
||||
return $this->handler !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unshift a middleware to the bottom of the stack.
|
||||
*
|
||||
* @param callable(callable&THandler): (callable&THandler) $middleware Middleware function
|
||||
* @param string $name Name to register for this middleware.
|
||||
*/
|
||||
public function unshift(callable $middleware, ?string $name = null): void
|
||||
{
|
||||
\array_unshift($this->stack, [$middleware, $name]);
|
||||
$this->cached = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push a middleware to the top of the stack.
|
||||
*
|
||||
* @param callable(callable&THandler): (callable&THandler) $middleware Middleware function
|
||||
* @param string $name Name to register for this middleware.
|
||||
*/
|
||||
public function push(callable $middleware, string $name = ''): void
|
||||
{
|
||||
$this->stack[] = [$middleware, $name];
|
||||
$this->cached = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a middleware before another middleware by name.
|
||||
*
|
||||
* @param string $findName Middleware to find
|
||||
* @param callable(callable&THandler): (callable&THandler) $middleware Middleware function
|
||||
* @param string $withName Name to register for this middleware.
|
||||
*/
|
||||
public function before(string $findName, callable $middleware, string $withName = ''): void
|
||||
{
|
||||
$this->splice($findName, $withName, $middleware, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a middleware after another middleware by name.
|
||||
*
|
||||
* @param string $findName Middleware to find
|
||||
* @param callable(callable&THandler): (callable&THandler) $middleware Middleware function
|
||||
* @param string $withName Name to register for this middleware.
|
||||
*/
|
||||
public function after(string $findName, callable $middleware, string $withName = ''): void
|
||||
{
|
||||
$this->splice($findName, $withName, $middleware, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a middleware by instance or name from the stack.
|
||||
*
|
||||
* @param (callable(callable&THandler): (callable&THandler))|string $remove Middleware to remove by instance or name.
|
||||
*/
|
||||
public function remove($remove): void
|
||||
{
|
||||
if (!\is_string($remove) && !\is_callable($remove)) {
|
||||
// TODO: Move this to the parameter definition in 9.0.
|
||||
throw new \TypeError(__METHOD__.'(): Argument #1 ($remove) must be of type callable|string');
|
||||
}
|
||||
|
||||
$this->cached = null;
|
||||
|
||||
if (\is_string($remove)) {
|
||||
$count = \count($this->stack);
|
||||
$this->stack = \array_values(\array_filter(
|
||||
$this->stack,
|
||||
static function (array $tuple) use ($remove): bool {
|
||||
return $tuple[1] !== $remove;
|
||||
}
|
||||
));
|
||||
|
||||
if ($count !== \count($this->stack) || !\is_callable($remove)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->stack = \array_values(\array_filter(
|
||||
$this->stack,
|
||||
static function (array $tuple) use ($remove): bool {
|
||||
return $tuple[0] !== $remove;
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Compose the middleware and handler into a single callable function.
|
||||
*
|
||||
* @return callable&THandler
|
||||
*/
|
||||
public function resolve(): callable
|
||||
{
|
||||
if ($this->cached === null) {
|
||||
if (($prev = $this->handler) === null) {
|
||||
throw new \LogicException('No handler has been specified');
|
||||
}
|
||||
|
||||
if (!\is_callable($prev)) {
|
||||
throw new \LogicException('Handler must be callable');
|
||||
}
|
||||
|
||||
foreach (\array_reverse($this->stack) as $fn) {
|
||||
if (!\is_array($fn) || !\array_key_exists(0, $fn) || !\is_callable($fn[0])) {
|
||||
throw new \LogicException('Middleware must be callable');
|
||||
}
|
||||
|
||||
$prev = $fn[0]($prev);
|
||||
|
||||
if (!\is_callable($prev)) {
|
||||
throw new \LogicException('Middleware must return a callable');
|
||||
}
|
||||
}
|
||||
|
||||
$this->cached = $prev;
|
||||
}
|
||||
|
||||
return $this->cached;
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
$this->handler = null;
|
||||
$this->stack = [];
|
||||
$this->cached = null;
|
||||
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
|
||||
private function findByName(string $name): int
|
||||
{
|
||||
foreach ($this->stack as $k => $v) {
|
||||
if ($v[1] === $name) {
|
||||
return $k;
|
||||
}
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException(\sprintf('Middleware not found: %s', DiagnosticValue::escape($name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Splices a function into the middleware list at a specific position.
|
||||
*
|
||||
* @param callable(callable&THandler): (callable&THandler) $middleware
|
||||
*/
|
||||
private function splice(string $findName, string $withName, callable $middleware, bool $before): void
|
||||
{
|
||||
$this->cached = null;
|
||||
$idx = $this->findByName($findName);
|
||||
$tuple = [$middleware, $withName];
|
||||
|
||||
if ($before) {
|
||||
if ($idx === 0) {
|
||||
\array_unshift($this->stack, $tuple);
|
||||
} else {
|
||||
$replacement = [$tuple, $this->stack[$idx]];
|
||||
\array_splice($this->stack, $idx, 1, $replacement);
|
||||
}
|
||||
} elseif ($idx === \count($this->stack) - 1) {
|
||||
$this->stack[] = $tuple;
|
||||
} else {
|
||||
$replacement = [$this->stack[$idx], $tuple];
|
||||
\array_splice($this->stack, $idx, 1, $replacement);
|
||||
}
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
/**
|
||||
* Shared host identity normalization for features that key state on a
|
||||
* logical host.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class HostIdentity
|
||||
{
|
||||
/**
|
||||
* Returns the identity form of a URI host. Valid bracketed IPv6 literals
|
||||
* are canonicalized to their RFC 5952 form so equivalent spellings of one
|
||||
* address share a single identity; IPvFuture literals, zone-bearing
|
||||
* values, and invalid bracketed text fall back to ASCII case folding.
|
||||
*/
|
||||
public static function canonicalHost(string $host): string
|
||||
{
|
||||
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
|
||||
try {
|
||||
return '['.Psr7\Rfc3986::canonicalizeIpv6(\substr($host, 1, -1)).']';
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
// Fall back to case folding below.
|
||||
}
|
||||
}
|
||||
|
||||
return Psr7\Utils::asciiToLower($host);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the identity form of a cookie domain. In addition to the
|
||||
* canonicalHost() rules, valid bare IPv6 addresses, which the cookie API
|
||||
* permissively accepts even though a URI host requires brackets, are
|
||||
* canonicalized to their RFC 5952 form without gaining brackets, so bare
|
||||
* and bracketed forms remain distinct identities.
|
||||
*/
|
||||
public static function canonicalCookieDomain(string $domain): string
|
||||
{
|
||||
if (!\str_starts_with($domain, '[') && \strpos($domain, ':') !== false) {
|
||||
try {
|
||||
return Psr7\Rfc3986::canonicalizeIpv6($domain);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return Psr7\Utils::asciiToLower($domain);
|
||||
}
|
||||
}
|
||||
|
||||
return self::canonicalHost($domain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a request domain matches a cookie domain according to RFC 6265.
|
||||
*
|
||||
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
|
||||
*/
|
||||
public static function cookieDomainMatches(string $domain, string $cookieDomain): bool
|
||||
{
|
||||
$domain = self::canonicalCookieDomain($domain);
|
||||
$cookieDomain = self::canonicalCookieDomain($cookieDomain);
|
||||
|
||||
if ($domain === $cookieDomain) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// A percent-escaped cookie domain can decode to another host spelling.
|
||||
// Keep it exact-match-only; decoding a request host cannot create a
|
||||
// suffix match that its original text lacked.
|
||||
if (\strpos($cookieDomain, '%') !== false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!self::isDnsSuffixEligible($domain) || !self::isDnsSuffixEligible($cookieDomain)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the identity form of a Host header value. A single bracketed
|
||||
* `host[:port]` authority, where any explicit port must be a valid decimal
|
||||
* port number, has its IPv6 literal canonicalized like canonicalHost() with
|
||||
* the port text retained; every other value, including malformed and
|
||||
* multiple values, falls back to ASCII case folding of the raw text.
|
||||
*/
|
||||
public static function canonicalHostHeader(string $header): string
|
||||
{
|
||||
if (\str_starts_with($header, '[')) {
|
||||
$end = \strpos($header, ']');
|
||||
if ($end !== false) {
|
||||
$rest = \substr($header, $end + 1);
|
||||
if ($rest === '' || (\str_starts_with($rest, ':') && Psr7\Rfc3986::isValidPort(\substr($rest, 1)))) {
|
||||
return self::canonicalHost(\substr($header, 0, $end + 1)).$rest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Psr7\Utils::asciiToLower($header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the host may participate in RFC 6265 DNS suffix matching. IP
|
||||
* literals, IP addresses, numeric hosts, literal-like text containing a
|
||||
* raw bracket or colon, and invalid host text are exact-match-only.
|
||||
*/
|
||||
private static function isDnsSuffixEligible(string $host): bool
|
||||
{
|
||||
if (\strpbrk($host, '[]:') !== false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Psr7\Rfc3986::isValidHost($host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !self::isIpAddressOrNumericHost($host);
|
||||
}
|
||||
|
||||
private static function isIpAddressOrNumericHost(string $host): bool
|
||||
{
|
||||
// Strip one root dot before detection so trailing-dot numeric hosts
|
||||
// still cannot be matched by subdomains.
|
||||
if ($host !== '' && \str_ends_with($host, '.')) {
|
||||
$host = \substr($host, 0, -1);
|
||||
}
|
||||
|
||||
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
|
||||
$host = \substr($host, 1, -1);
|
||||
}
|
||||
|
||||
if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Public DNS names do not have an all-numeric rightmost label; treat
|
||||
// those private/internal hosts as exact-match-only too.
|
||||
$labels = \explode('.', $host);
|
||||
$last = (string) \end($labels);
|
||||
|
||||
if ($last !== '' && \ctype_digit($last)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// libcurl also parses a 0x-prefixed hexadecimal rightmost label as a
|
||||
// numerical IPv4 address, such as 0x7f000001 for 127.0.0.1.
|
||||
return \str_starts_with($last, '0x') && \strlen($last) > 2 && \ctype_xdigit(\substr($last, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the four-byte binary form of a host that a transport reads as a
|
||||
* numeric IPv4 address, or null when it reads it as a name.
|
||||
*
|
||||
* The shape test is Handler\HostValidator::isNumericIpv4Host(); this
|
||||
* method adds the range checks that predicate omits: every part but the
|
||||
* last must fit one octet, and the last must fit the octets the earlier
|
||||
* parts left. A trailing root dot is not swallowed, unlike libcurl 8.21.0
|
||||
* and later, because assertRequestHost() rejects that spelling first.
|
||||
*/
|
||||
public static function numericIpv4ToBinary(string $host): ?string
|
||||
{
|
||||
if (!Handler\HostValidator::isNumericIpv4Host($host)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$values = [];
|
||||
foreach (\explode('.', $host) as $part) {
|
||||
$values[] = self::numericIpv4PartValue($part);
|
||||
}
|
||||
|
||||
// Every accepted value is a whole number no larger than 0xFFFFFFFF,
|
||||
// which a float holds exactly, so the arithmetic below is correct on a
|
||||
// 32-bit build too, where the widest part overflows an integer.
|
||||
$address = (float) \array_pop($values);
|
||||
|
||||
$packed = '';
|
||||
foreach ($values as $value) {
|
||||
if ($value > 255.0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$packed .= \chr((int) $value);
|
||||
}
|
||||
|
||||
$width = 4 - \count($values);
|
||||
if ($address >= 256.0 ** $width) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for ($shift = $width - 1; $shift >= 0; --$shift) {
|
||||
$packed .= \chr((int) \fmod(\floor($address / 256.0 ** $shift), 256.0));
|
||||
}
|
||||
|
||||
return $packed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of one accepted part as a float, so a part filling
|
||||
* all four octets such as 2130706433 stays exact on every integer width.
|
||||
*/
|
||||
private static function numericIpv4PartValue(string $part): float
|
||||
{
|
||||
if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
|
||||
return self::digitsValue((string) \substr($part, 2), 16);
|
||||
}
|
||||
|
||||
if ($part[0] === '0') {
|
||||
return self::digitsValue($part, 8);
|
||||
}
|
||||
|
||||
return (float) $part;
|
||||
}
|
||||
|
||||
private static function digitsValue(string $digits, int $base): float
|
||||
{
|
||||
$value = 0.0;
|
||||
foreach (\str_split($digits) as $digit) {
|
||||
$value = $value * $base + \hexdec($digit);
|
||||
if ($value > 0xFFFFFFFF) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
// cannot be instantiated
|
||||
}
|
||||
}
|
||||
Vendored
+106
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class Idn
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
public static function normalizeConversionOption($value): ?int
|
||||
{
|
||||
if ($value === null || $value === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($value === true) {
|
||||
return \IDNA_DEFAULT;
|
||||
}
|
||||
|
||||
if (\is_int($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('idn_conversion must be true, false, null, or an integer IDNA_* bitmask');
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function convertUri(UriInterface $uri, int $options = 0): UriInterface
|
||||
{
|
||||
if ($uri->getHost()) {
|
||||
$asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
|
||||
if ($asciiHost === false) {
|
||||
$errorBitSet = $info['errors'] ?? 0;
|
||||
|
||||
$errorConstants = array_filter(array_keys(get_defined_constants()), static function (string $name): bool {
|
||||
return substr($name, 0, 11) === 'IDNA_ERROR_';
|
||||
});
|
||||
|
||||
$errors = [];
|
||||
foreach ($errorConstants as $errorConstant) {
|
||||
if ($errorBitSet & constant($errorConstant)) {
|
||||
$errors[] = $errorConstant;
|
||||
}
|
||||
}
|
||||
|
||||
$errorMessage = 'IDN conversion failed';
|
||||
if ($errors) {
|
||||
$errorMessage .= ' (errors: '.implode(', ', $errors).')';
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException($errorMessage);
|
||||
}
|
||||
if ($uri->getHost() !== $asciiHost) {
|
||||
// The conversion can map a character to a URI delimiter.
|
||||
if (!Psr7\Rfc3986::isValidHost($asciiHost)) {
|
||||
throw new InvalidArgumentException('IDN conversion failed');
|
||||
}
|
||||
|
||||
// Replace URI only if the ASCII version is different
|
||||
try {
|
||||
$uri = $uri->withHost($asciiHost);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new InvalidArgumentException('IDN conversion failed', 0, $e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|false
|
||||
*/
|
||||
private static function idnToAsci(string $domain, int $options, ?array &$info = [])
|
||||
{
|
||||
if (\function_exists('idn_to_ascii') && \defined('INTL_IDNA_VARIANT_UTS46')) {
|
||||
// ICU can take quadratic time, and no valid name needs more bytes.
|
||||
if (\strlen($domain) > 4096) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return \idn_to_ascii($domain, $options, \INTL_IDNA_VARIANT_UTS46, $info);
|
||||
} catch (\IntlException $e) {
|
||||
// With intl.use_exceptions, a label too long to encode throws.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
throw new \Error('ext-idn or symfony/polyfill-intl-idn not loaded or too old');
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Formats log messages using variable substitutions for requests, responses,
|
||||
* and other transactional data.
|
||||
*
|
||||
* The following variable substitutions are supported:
|
||||
*
|
||||
* - {request}: Full HTTP request message
|
||||
* - {response}: Full HTTP response message
|
||||
* - {ts}: ISO 8601 date in GMT
|
||||
* - {date_iso_8601} ISO 8601 date in GMT
|
||||
* - {date_common_log} Apache common log date using the configured timezone.
|
||||
* - {host}: Host of the request
|
||||
* - {method}: Method of the request
|
||||
* - {uri}: URI of the request
|
||||
* - {version}: Protocol version
|
||||
* - {target}: Request target of the request (path + query + fragment)
|
||||
* - {hostname}: Hostname of the machine that sent the request
|
||||
* - {code}: Status code of the response (if available)
|
||||
* - {phrase}: Reason phrase of the response (if available)
|
||||
* - {error}: Any error messages (if available)
|
||||
* - {req_header_*}: Replace `*` with the lowercased name of a request header
|
||||
* to add to the message
|
||||
* - {res_header_*}: Replace `*` with the lowercased name of a response header
|
||||
* to add to the message
|
||||
* - {req_headers}: Request headers
|
||||
* - {res_headers}: Response headers
|
||||
* - {req_body}: Request body
|
||||
* - {res_body}: Response body
|
||||
*/
|
||||
final class MessageFormatter implements MessageFormatterInterface
|
||||
{
|
||||
/**
|
||||
* Apache Common Log Format.
|
||||
*
|
||||
* @see https://httpd.apache.org/docs/2.4/logs.html#common
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const CLF = '{hostname} {req_header_User-Agent} - [{date_common_log}] "{method} {target} HTTP/{version}" {code} {res_header_Content-Length}';
|
||||
public const DEBUG = ">>>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{error}";
|
||||
public const SHORT = '[{ts}] "{method} {target} HTTP/{version}" {code}';
|
||||
|
||||
/**
|
||||
* @var string Template used to format log messages
|
||||
*/
|
||||
private string $template;
|
||||
|
||||
/**
|
||||
* @param string $template Log message template
|
||||
*/
|
||||
public function __construct(?string $template = self::CLF)
|
||||
{
|
||||
$this->template = $template ?: self::CLF;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a formatted message string.
|
||||
*
|
||||
* @param RequestInterface $request Request that was sent
|
||||
* @param ResponseInterface|null $response Response that was received
|
||||
* @param \Throwable|null $error Exception that was received
|
||||
*/
|
||||
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string
|
||||
{
|
||||
$cache = [];
|
||||
|
||||
$result = \preg_replace_callback(
|
||||
'/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
|
||||
function (array $matches) use ($request, $response, $error, &$cache): string {
|
||||
if (isset($cache[$matches[1]])) {
|
||||
return $cache[$matches[1]];
|
||||
}
|
||||
|
||||
$result = '';
|
||||
switch ($matches[1]) {
|
||||
case 'request':
|
||||
$result = Psr7\Message::toString($request);
|
||||
break;
|
||||
case 'response':
|
||||
$result = $response ? Psr7\Message::toString($response) : '';
|
||||
break;
|
||||
case 'req_headers':
|
||||
$result = \trim($request->getMethod()
|
||||
.' '.$request->getRequestTarget(), " \n\r\t\0\x0B")
|
||||
.' HTTP/'.$request->getProtocolVersion()."\r\n"
|
||||
.$this->headers($request);
|
||||
break;
|
||||
case 'res_headers':
|
||||
$result = $response ?
|
||||
\sprintf(
|
||||
'HTTP/%s %d %s',
|
||||
$response->getProtocolVersion(),
|
||||
$response->getStatusCode(),
|
||||
$response->getReasonPhrase()
|
||||
)."\r\n".$this->headers($response)
|
||||
: 'NULL';
|
||||
break;
|
||||
case 'req_body':
|
||||
$result = $request->getBody()->__toString();
|
||||
break;
|
||||
case 'res_body':
|
||||
if (!$response instanceof ResponseInterface) {
|
||||
$result = 'NULL';
|
||||
break;
|
||||
}
|
||||
|
||||
$body = $response->getBody();
|
||||
|
||||
if (!$body->isSeekable()) {
|
||||
$result = 'RESPONSE_NOT_LOGGEABLE';
|
||||
break;
|
||||
}
|
||||
|
||||
$result = $response->getBody()->__toString();
|
||||
break;
|
||||
case 'ts':
|
||||
case 'date_iso_8601':
|
||||
$result = \gmdate('c');
|
||||
break;
|
||||
case 'date_common_log':
|
||||
$result = \date('d/M/Y:H:i:s O');
|
||||
break;
|
||||
case 'method':
|
||||
$result = $request->getMethod();
|
||||
break;
|
||||
case 'version':
|
||||
$result = $request->getProtocolVersion();
|
||||
break;
|
||||
case 'uri':
|
||||
case 'url':
|
||||
$result = $request->getUri()->__toString();
|
||||
break;
|
||||
case 'target':
|
||||
$result = $request->getRequestTarget();
|
||||
break;
|
||||
case 'req_version':
|
||||
$result = $request->getProtocolVersion();
|
||||
break;
|
||||
case 'res_version':
|
||||
$result = $response
|
||||
? $response->getProtocolVersion()
|
||||
: 'NULL';
|
||||
break;
|
||||
case 'host':
|
||||
$result = $request->getHeaderLine('Host');
|
||||
break;
|
||||
case 'hostname':
|
||||
$result = \gethostname();
|
||||
break;
|
||||
case 'code':
|
||||
$result = $response ? $response->getStatusCode() : 'NULL';
|
||||
break;
|
||||
case 'phrase':
|
||||
$result = $response ? $response->getReasonPhrase() : 'NULL';
|
||||
break;
|
||||
case 'error':
|
||||
$result = $error ? $error->getMessage() : 'NULL';
|
||||
break;
|
||||
default:
|
||||
// handle prefixed dynamic headers
|
||||
if (\strpos($matches[1], 'req_header_') === 0) {
|
||||
$result = $request->getHeaderLine(\substr($matches[1], 11));
|
||||
} elseif (\strpos($matches[1], 'res_header_') === 0) {
|
||||
$result = $response
|
||||
? $response->getHeaderLine(\substr($matches[1], 11))
|
||||
: 'NULL';
|
||||
}
|
||||
}
|
||||
|
||||
$result = (string) $result;
|
||||
$cache[$matches[1]] = $result;
|
||||
|
||||
return $result;
|
||||
},
|
||||
$this->template
|
||||
);
|
||||
|
||||
if ($result === null) {
|
||||
throw new \RuntimeException('Unable to format message: '.\preg_last_error_msg());
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get headers from message as string
|
||||
*/
|
||||
private function headers(MessageInterface $message): string
|
||||
{
|
||||
$result = '';
|
||||
foreach ($message->getHeaders() as $name => $values) {
|
||||
$result .= $name.': '.\implode(', ', $values)."\r\n";
|
||||
}
|
||||
|
||||
return \trim($result, " \n\r\t\0\x0B");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
interface MessageFormatterInterface
|
||||
{
|
||||
/**
|
||||
* Returns a formatted message string.
|
||||
*
|
||||
* @param RequestInterface $request Request that was sent
|
||||
* @param ResponseInterface|null $response Response that was received
|
||||
* @param \Throwable|null $error Exception that was received
|
||||
*/
|
||||
public function format(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): string;
|
||||
}
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJarInterface;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Functions used to create and wrap handlers with handler middleware.
|
||||
*/
|
||||
final class Middleware
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that applies built-in Basic authentication and handles Digest
|
||||
* authentication challenges when the "auth" request option is set.
|
||||
*
|
||||
* @param bool $reuseChallenges Whether Digest challenges may be reused preemptively.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function auth(bool $reuseChallenges = true): callable
|
||||
{
|
||||
return static function (callable $handler) use ($reuseChallenges): AuthMiddleware {
|
||||
return new AuthMiddleware($handler, null, $reuseChallenges);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that adds cookies to requests.
|
||||
*
|
||||
* The options array must be set to a CookieJarInterface in order to use
|
||||
* cookies. This is typically handled for you by a client.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function cookies(): callable
|
||||
{
|
||||
return static function (callable $handler): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler): PromiseInterface {
|
||||
if (empty($options['cookies'])) {
|
||||
return $handler($request, $options);
|
||||
} elseif (!$options['cookies'] instanceof CookieJarInterface) {
|
||||
throw new \InvalidArgumentException('cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface');
|
||||
}
|
||||
$cookieJar = $options['cookies'];
|
||||
$request = $cookieJar->withCookieHeader($request);
|
||||
|
||||
return $handler($request, $options)
|
||||
->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($cookieJar, $request): ResponseInterface {
|
||||
$cookieJar->extractCookies($request, $response);
|
||||
|
||||
return $response;
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that throws exceptions for 4xx or 5xx responses when the
|
||||
* "http_errors" request option is set to true.
|
||||
*
|
||||
* @param BodySummarizerInterface|null $bodySummarizer The body summarizer to use in exception messages.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function httpErrors(?BodySummarizerInterface $bodySummarizer = null): callable
|
||||
{
|
||||
return static function (callable $handler) use ($bodySummarizer): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler, $bodySummarizer): PromiseInterface {
|
||||
if (empty($options['http_errors'])) {
|
||||
return $handler($request, $options);
|
||||
}
|
||||
|
||||
return $handler($request, $options)->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $bodySummarizer): ResponseInterface {
|
||||
$code = $response->getStatusCode();
|
||||
if ($code < 400) {
|
||||
return $response;
|
||||
}
|
||||
throw RequestException::create($request, $response, null, $bodySummarizer);
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that pushes history data to an ArrayAccess container.
|
||||
*
|
||||
* @param array<array-key, array{request: RequestInterface, response: ResponseInterface|null, error: mixed, options: array<array-key, mixed>}>|\ArrayAccess<int, array{request: RequestInterface, response: ResponseInterface|null, error: mixed, options: array<array-key, mixed>}> $container Container to hold the history (by reference).
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*
|
||||
* @throws \InvalidArgumentException if container is not an array or ArrayAccess.
|
||||
*/
|
||||
public static function history(&$container): callable
|
||||
{
|
||||
if (!\is_array($container) && !$container instanceof \ArrayAccess) {
|
||||
throw new \InvalidArgumentException('history container must be an array or object implementing ArrayAccess');
|
||||
}
|
||||
|
||||
return static function (callable $handler) use (&$container): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler, &$container): PromiseInterface {
|
||||
return $handler($request, $options)->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $value
|
||||
) use ($request, &$container, $options): ResponseInterface {
|
||||
$container[] = [
|
||||
'request' => $request,
|
||||
'response' => $value,
|
||||
'error' => null,
|
||||
'options' => $options,
|
||||
];
|
||||
|
||||
return $value;
|
||||
},
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($request, &$container, $options): PromiseInterface {
|
||||
$container[] = [
|
||||
'request' => $request,
|
||||
'response' => null,
|
||||
'error' => $reason,
|
||||
'options' => $options,
|
||||
];
|
||||
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that observes requests and responses as they flow through the
|
||||
* stack without modifying them. This is useful for metrics, tracing, and
|
||||
* debugging.
|
||||
*
|
||||
* The provided listener cannot modify or alter the response. It simply
|
||||
* "taps" into the chain to be notified before returning the promise. The
|
||||
* before listener accepts a request and options array, and the after
|
||||
* listener accepts a request, options array, and response promise.
|
||||
*
|
||||
* @param (callable(RequestInterface, array<array-key, mixed>): mixed)|null $before Function to invoke before forwarding the request.
|
||||
* @param (callable(RequestInterface, array<array-key, mixed>, PromiseInterface<ResponseInterface, mixed>): mixed)|null $after Function invoked after forwarding.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function tap(?callable $before = null, ?callable $after = null): callable
|
||||
{
|
||||
return static function (callable $handler) use ($before, $after): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler, $before, $after): PromiseInterface {
|
||||
if ($before) {
|
||||
$before($request, $options);
|
||||
}
|
||||
$response = $handler($request, $options);
|
||||
if ($after) {
|
||||
$after($request, $options, $response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that handles request redirects.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function redirect(): callable
|
||||
{
|
||||
return static function (callable $handler): RedirectMiddleware {
|
||||
return new RedirectMiddleware($handler);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that retries requests based on the boolean result of
|
||||
* invoking the provided "decider" function.
|
||||
*
|
||||
* If no delay function is provided, a simple implementation of exponential
|
||||
* backoff will be utilized.
|
||||
*
|
||||
* @param callable(int, RequestInterface, ResponseInterface|null, mixed): bool $decider Function that accepts the number of retries,
|
||||
* a request, [response], and [rejection reason]
|
||||
* and returns true if the request is to be retried.
|
||||
* @param (callable(int, ResponseInterface|null, RequestInterface): int)|null $delay Function that accepts the number of retries,
|
||||
* [response], and request, and returns the
|
||||
* number of milliseconds to delay.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function retry(callable $decider, ?callable $delay = null): callable
|
||||
{
|
||||
return static function (callable $handler) use ($decider, $delay): RetryMiddleware {
|
||||
return new RetryMiddleware($decider, $handler, $delay);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that logs requests, responses, and errors using a message
|
||||
* formatter.
|
||||
*
|
||||
* @param LoggerInterface $logger Logs messages.
|
||||
* @param MessageFormatterInterface $formatter Formatter used to create message strings.
|
||||
* @param string $logLevel Level at which to log requests.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function log(LoggerInterface $logger, MessageFormatterInterface $formatter, string $logLevel = 'info'): callable
|
||||
{
|
||||
return static function (callable $handler) use ($logger, $formatter, $logLevel): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options = []
|
||||
) use ($handler, $logger, $formatter, $logLevel): PromiseInterface {
|
||||
return $handler($request, $options)->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($logger, $request, $formatter, $logLevel): ResponseInterface {
|
||||
$message = $formatter->format($request, $response);
|
||||
$logger->log($logLevel, $message);
|
||||
|
||||
return $response;
|
||||
},
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($logger, $request, $formatter): PromiseInterface {
|
||||
$response = $reason instanceof ResponseException ? $reason->getResponse() : null;
|
||||
$message = $formatter->format($request, $response, P\Create::exceptionFor($reason));
|
||||
$logger->error($message);
|
||||
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* This middleware adds a default content-type if possible, a default
|
||||
* content-length or transfer-encoding header, and the expect header.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function prepareBody(): callable
|
||||
{
|
||||
return static function (callable $handler): PrepareBodyMiddleware {
|
||||
return new PrepareBodyMiddleware($handler);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that applies a map function to the request before passing to
|
||||
* the next handler.
|
||||
*
|
||||
* @param callable(RequestInterface): RequestInterface $fn Function that accepts a RequestInterface and returns
|
||||
* a RequestInterface.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function mapRequest(callable $fn): callable
|
||||
{
|
||||
return static function (callable $handler) use ($fn): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler, $fn): PromiseInterface {
|
||||
return $handler($fn($request), $options);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Middleware that applies a map function to the resolved promise's
|
||||
* response.
|
||||
*
|
||||
* @param callable(ResponseInterface): ResponseInterface $fn Function that accepts a ResponseInterface and
|
||||
* returns a ResponseInterface.
|
||||
*
|
||||
* @return callable((callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)): (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)
|
||||
*/
|
||||
public static function mapResponse(callable $fn): callable
|
||||
{
|
||||
return static function (callable $handler) use ($fn): callable {
|
||||
return static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
) use ($handler, $fn): PromiseInterface {
|
||||
return $handler($request, $options)->then($fn);
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
/**
|
||||
* Multiplexing modes for the "multiplex" request option.
|
||||
*
|
||||
* NONE disables multiplexing for a whole handler when passed as the
|
||||
* "multiplex" client configuration option or, when constructing a handler
|
||||
* directly, as the CurlMultiHandler "multiplex" constructor option. As a
|
||||
* request option value it guarantees the transfer does not share its
|
||||
* connection with any concurrent transfer, and is accepted only where that
|
||||
* guarantee holds.
|
||||
*/
|
||||
final class Multiplexing
|
||||
{
|
||||
public const NONE = 'none';
|
||||
public const EAGER = 'eager';
|
||||
public const WAIT = 'wait';
|
||||
public const REQUIRE_EAGER = 'require_eager';
|
||||
public const REQUIRE_WAIT = 'require_wait';
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
trait NonSerializableTrait
|
||||
{
|
||||
public function __serialize(): array
|
||||
{
|
||||
throw new \LogicException(static::class.' should never be serialized');
|
||||
}
|
||||
|
||||
public function __unserialize(array $data): void
|
||||
{
|
||||
throw new \LogicException(static::class.' should never be unserialized');
|
||||
}
|
||||
}
|
||||
+524
@@ -0,0 +1,524 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJarInterface;
|
||||
use GuzzleHttp\Promise\EachPromise;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Promise\PromisorInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriFactoryInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Sends an iterator of requests concurrently using a capped pool size.
|
||||
*
|
||||
* The pool will read from an iterator until it is cancelled or until the
|
||||
* iterator is consumed. When a request is yielded, the request is sent after
|
||||
* applying the "options" request options (if provided in the ctor). Any
|
||||
* observer callbacks in "options" (on_headers, on_trailers, on_stats,
|
||||
* progress, and allow_redirects.on_redirect) also receive the request's
|
||||
* iterable key as a trailing argument.
|
||||
*
|
||||
* When a function is yielded by the iterator, the function is provided the
|
||||
* "options" array that should be merged on top of any existing options, and
|
||||
* the function MUST then return a response or a wait-able response promise.
|
||||
*
|
||||
* @final
|
||||
*
|
||||
* @implements PromisorInterface<mixed, mixed>
|
||||
*/
|
||||
class Pool implements PromisorInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var EachPromise<array-key, ResponseInterface, mixed>
|
||||
*/
|
||||
private EachPromise $each;
|
||||
|
||||
/**
|
||||
* @param ClientInterface $client Client used to send the requests.
|
||||
* @param iterable<array-key, RequestInterface|callable(array<array-key, mixed>): (ResponseInterface|PromiseInterface<ResponseInterface, mixed>)> $requests Requests or functions that return responses or response promises.
|
||||
* @param array{
|
||||
* concurrency?: int|(callable(int): int),
|
||||
* options?: array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* on_stats?: callable(TransferStats, int|string): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* progress?: callable(int, int, int, int, int|string): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* },
|
||||
* fulfilled?: callable(ResponseInterface, int|string, PromiseInterface<mixed, mixed>): mixed,
|
||||
* rejected?: callable(mixed, int|string, PromiseInterface<mixed, mixed>): mixed
|
||||
* } $config Pool configuration.
|
||||
*/
|
||||
public function __construct(
|
||||
ClientInterface $client,
|
||||
iterable $requests,
|
||||
#[\SensitiveParameter]
|
||||
array $config = []
|
||||
) {
|
||||
if (!isset($config['concurrency'])) {
|
||||
$config['concurrency'] = 25;
|
||||
}
|
||||
|
||||
if (isset($config['options'])) {
|
||||
$opts = $config['options'];
|
||||
unset($config['options']);
|
||||
} else {
|
||||
$opts = [];
|
||||
}
|
||||
|
||||
$requestGenerator = static function () use ($requests, $client, $opts): \Generator {
|
||||
foreach ($requests as $key => $rfn) {
|
||||
$keyedOpts = self::keyedRequestOptions($opts, $key);
|
||||
|
||||
if ($rfn instanceof RequestInterface) {
|
||||
yield $key => $client->sendAsync($rfn, $keyedOpts);
|
||||
} elseif (\is_callable($rfn)) {
|
||||
yield $key => $rfn($keyedOpts);
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr\Http\Message\ResponseInterface object.');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
$this->each = new EachPromise($requestGenerator(), $config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get promise
|
||||
*
|
||||
* @return PromiseInterface<mixed, mixed>
|
||||
*/
|
||||
public function promise(): PromiseInterface
|
||||
{
|
||||
return $this->each->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends multiple requests concurrently and returns an array of responses
|
||||
* and exceptions that uses the same ordering as the provided requests.
|
||||
*
|
||||
* IMPORTANT: This method keeps every request and response in memory, and
|
||||
* as such, is NOT recommended when sending a large number or an
|
||||
* indeterminate number of requests concurrently.
|
||||
*
|
||||
* @param ClientInterface $client Client used to send the requests
|
||||
* @param iterable<array-key, RequestInterface|callable(array<array-key, mixed>): (ResponseInterface|PromiseInterface<ResponseInterface, mixed>)> $requests Requests or functions that return responses or response promises.
|
||||
* @param array{
|
||||
* concurrency?: int|(callable(int): int),
|
||||
* options?: array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* on_stats?: callable(TransferStats, int|string): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* progress?: callable(int, int, int, int, int|string): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* },
|
||||
* fulfilled?: callable(ResponseInterface, int|string): mixed,
|
||||
* rejected?: callable(mixed, int|string): mixed
|
||||
* } $options Passes through the options available in {@see Pool::__construct}.
|
||||
*
|
||||
* @return array<array-key, mixed> Returns an array containing the response or rejection reason in the same order that the requests were sent.
|
||||
*
|
||||
* @throws \InvalidArgumentException if the event format is incorrect.
|
||||
*/
|
||||
public static function batch(
|
||||
ClientInterface $client,
|
||||
iterable $requests,
|
||||
#[\SensitiveParameter]
|
||||
array $options = []
|
||||
): array {
|
||||
$res = [];
|
||||
self::cmpCallback($options, 'fulfilled', $res);
|
||||
self::cmpCallback($options, 'rejected', $res);
|
||||
$pool = new static($client, $requests, $options);
|
||||
$pool->promise()->wait();
|
||||
\ksort($res);
|
||||
|
||||
return $res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute callback(s)
|
||||
*/
|
||||
private static function cmpCallback(array &$options, string $name, array &$results): void
|
||||
{
|
||||
if (!isset($options[$name])) {
|
||||
$options[$name] = static function (
|
||||
#[\SensitiveParameter]
|
||||
$v,
|
||||
$k
|
||||
) use (&$results): void {
|
||||
$results[$k] = $v;
|
||||
};
|
||||
} else {
|
||||
$currentFn = $options[$name];
|
||||
$options[$name] = static function (
|
||||
#[\SensitiveParameter]
|
||||
$v,
|
||||
$k
|
||||
) use (&$results, $currentFn): void {
|
||||
$currentFn($v, $k);
|
||||
$results[$k] = $v;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the request options with any observer callbacks wrapped so that
|
||||
* they also receive the request's iterable key as a trailing argument.
|
||||
*
|
||||
* @param array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface, int|string): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* on_stats?: callable(TransferStats, int|string): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface, int|string): mixed,
|
||||
* progress?: callable(int, int, int, int, int|string): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* } $options
|
||||
* @param int|string $key
|
||||
*
|
||||
* @return array{
|
||||
* base_uri?: string|UriInterface,
|
||||
* allow_redirects?: bool|array{
|
||||
* max?: int,
|
||||
* strict?: bool,
|
||||
* referer?: bool,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
|
||||
* track_redirects?: bool
|
||||
* },
|
||||
* auth?: array{
|
||||
* 0: string,
|
||||
* 1: string,
|
||||
* 2?: string|null
|
||||
* }|string|false|null,
|
||||
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
|
||||
* cert?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* cert_type?: string,
|
||||
* connect_timeout?: int|float,
|
||||
* cookies?: false|CookieJarInterface,
|
||||
* crypto_method?: int,
|
||||
* crypto_method_max?: int,
|
||||
* debug?: bool|resource,
|
||||
* decode_content?: bool|string,
|
||||
* delay?: int|float,
|
||||
* expect?: bool|int,
|
||||
* form_params?: array<array-key, string|int|float|bool|null|array>,
|
||||
* force_ip_resolve?: string,
|
||||
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
|
||||
* http_errors?: bool,
|
||||
* idn_conversion?: bool|int|null,
|
||||
* json?: mixed,
|
||||
* multipart?: array<array-key, array{
|
||||
* name: string|int,
|
||||
* contents: mixed,
|
||||
* headers?: array<array-key, string>,
|
||||
* filename?: string
|
||||
* }>,
|
||||
* multiplex?: string,
|
||||
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
|
||||
* on_stats?: callable(TransferStats): mixed,
|
||||
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
|
||||
* progress?: callable(int, int, int, int): mixed,
|
||||
* protocols?: non-empty-array<array-key, string>,
|
||||
* proxy?: string|array{
|
||||
* http?: string|null,
|
||||
* https?: string|null,
|
||||
* no?: string|array<array-key, string>|null
|
||||
* },
|
||||
* query?: array<array-key, mixed>|string,
|
||||
* read_timeout?: int|float,
|
||||
* retries?: int,
|
||||
* request_factory?: RequestFactoryInterface,
|
||||
* response_factory?: ResponseFactoryInterface,
|
||||
* sink?: resource|string|StreamInterface,
|
||||
* ssl_key?: string|array{
|
||||
* 0: string,
|
||||
* 1?: string|null
|
||||
* },
|
||||
* ssl_key_type?: string,
|
||||
* stream?: bool,
|
||||
* stream_factory?: StreamFactoryInterface,
|
||||
* stream_context?: array<array-key, mixed>,
|
||||
* synchronous?: bool,
|
||||
* timeout?: int|float,
|
||||
* uri_factory?: UriFactoryInterface,
|
||||
* verify?: bool|string,
|
||||
* version?: string|int|float,
|
||||
* curl?: array<int|string, mixed>,
|
||||
* ...
|
||||
* }
|
||||
*/
|
||||
private static function keyedRequestOptions(array $options, $key): array
|
||||
{
|
||||
if (\is_array($options['allow_redirects'] ?? null)
|
||||
&& \is_callable($options['allow_redirects']['on_redirect'] ?? null)
|
||||
) {
|
||||
$onRedirect = $options['allow_redirects']['on_redirect'];
|
||||
$options['allow_redirects']['on_redirect'] = static function (
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
UriInterface $uri
|
||||
) use ($onRedirect, $key): void {
|
||||
$onRedirect($request, $response, $uri, $key);
|
||||
};
|
||||
}
|
||||
|
||||
if (\is_callable($options['on_headers'] ?? null)) {
|
||||
$onHeaders = $options['on_headers'];
|
||||
$options['on_headers'] = static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
) use ($onHeaders, $key): void {
|
||||
$onHeaders($response, $request, $key);
|
||||
};
|
||||
}
|
||||
|
||||
if (\is_callable($options['on_stats'] ?? null)) {
|
||||
$onStats = $options['on_stats'];
|
||||
$options['on_stats'] = static function (TransferStats $stats) use ($onStats, $key): void {
|
||||
$onStats($stats, $key);
|
||||
};
|
||||
}
|
||||
|
||||
if (\is_callable($options['on_trailers'] ?? null)) {
|
||||
$onTrailers = $options['on_trailers'];
|
||||
$options['on_trailers'] = static function (
|
||||
array $trailers,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request
|
||||
) use ($onTrailers, $key): void {
|
||||
$onTrailers($trailers, $response, $request, $key);
|
||||
};
|
||||
}
|
||||
|
||||
if (\is_callable($options['progress'] ?? null)) {
|
||||
$progress = $options['progress'];
|
||||
$options['progress'] = static function (int $downloadTotal, int $downloadedBytes, int $uploadTotal, int $uploadedBytes) use ($progress, $key) {
|
||||
return $progress($downloadTotal, $downloadedBytes, $uploadTotal, $uploadedBytes, $key);
|
||||
};
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Handler\RequestFraming;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Prepares requests that contain a body, adding the Content-Length,
|
||||
* Content-Type, and Expect headers.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class PrepareBodyMiddleware
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private $nextHandler;
|
||||
|
||||
/**
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler Next handler to invoke.
|
||||
*/
|
||||
public function __construct(callable $nextHandler)
|
||||
{
|
||||
$this->nextHandler = $nextHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$fn = $this->nextHandler;
|
||||
$bodySize = RequestFraming::bodySize($request);
|
||||
|
||||
// Don't do anything if the request has no body.
|
||||
if ($bodySize === 0) {
|
||||
return $fn($request, $options);
|
||||
}
|
||||
|
||||
$modify = [];
|
||||
|
||||
// Add a default content-type if possible.
|
||||
if (!$request->hasHeader('Content-Type')) {
|
||||
if ($uri = $request->getBody()->getMetadata('uri')) {
|
||||
if (is_string($uri) && $type = Psr7\MimeType::fromFilename($uri)) {
|
||||
$modify['set_headers']['Content-Type'] = $type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add a default content-length or transfer-encoding header.
|
||||
if (!$request->hasHeader('Content-Length')
|
||||
&& !$request->hasHeader('Transfer-Encoding')
|
||||
) {
|
||||
if ($bodySize !== null) {
|
||||
$modify['set_headers']['Content-Length'] = (string) $bodySize;
|
||||
} elseif ($request->getProtocolVersion() === '1.1') {
|
||||
$modify['set_headers']['Transfer-Encoding'] = 'chunked';
|
||||
}
|
||||
}
|
||||
|
||||
// Add the expect header if needed.
|
||||
$this->addExpectHeader($request, $options, $modify, $bodySize);
|
||||
|
||||
return $fn(Psr7\Utils::modifyRequest($request, $modify), $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add expect header
|
||||
*/
|
||||
private function addExpectHeader(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
array &$modify,
|
||||
?int $bodySize
|
||||
): void {
|
||||
// Determine if the Expect header should be used
|
||||
if ($request->hasHeader('Expect')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$expect = $options['expect'] ?? null;
|
||||
|
||||
// Return if disabled or not using HTTP/1.1.
|
||||
if ($expect === false || '1.1' !== $request->getProtocolVersion()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The expect header is unconditionally enabled
|
||||
if ($expect === true) {
|
||||
$modify['set_headers']['Expect'] = '100-Continue';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// By default, send the expect header when the payload is > 1mb
|
||||
if ($expect === null) {
|
||||
$expect = 1048576;
|
||||
}
|
||||
|
||||
// Always add if the body cannot be rewound, the size cannot be
|
||||
// determined, or the size is greater than the cutoff threshold
|
||||
$body = $request->getBody();
|
||||
|
||||
if ($bodySize === null || $bodySize >= (int) $expect || !$body->isSeekable()) {
|
||||
$modify['set_headers']['Expect'] = '100-Continue';
|
||||
}
|
||||
}
|
||||
}
|
||||
+624
@@ -0,0 +1,624 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Psr7\Rfc3986;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
final class ProxyOptions
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve Guzzle's documented proxy request option for a request URI.
|
||||
*
|
||||
* @param mixed $proxy Proxy option as passed via request transfer options.
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function resolve(
|
||||
UriInterface $uri,
|
||||
#[\SensitiveParameter]
|
||||
$proxy
|
||||
): ProxySelection {
|
||||
if ($proxy === null) {
|
||||
return ProxySelection::none();
|
||||
}
|
||||
|
||||
if (!\is_array($proxy)) {
|
||||
if (!\is_string($proxy)) {
|
||||
throw new InvalidArgumentException('proxy must be a string or array');
|
||||
}
|
||||
|
||||
return ProxySelection::proxy($proxy);
|
||||
}
|
||||
|
||||
$schemeProxy = $proxy[$uri->getScheme()] ?? null;
|
||||
if ($schemeProxy !== null && !\is_string($schemeProxy)) {
|
||||
throw new InvalidArgumentException('proxy values must be strings');
|
||||
}
|
||||
|
||||
// A matching "no" entry is always a final decision, even when the
|
||||
// array selects no proxy for the request scheme. Without this, an
|
||||
// option-level bypass could fall through to handler-level environment
|
||||
// fallback and route through a proxy the user excluded.
|
||||
$noProxy = isset($proxy['no']) ? self::normalizeNoProxy($proxy['no']) : [];
|
||||
if ($noProxy !== [] && self::isUriInNoProxy($uri, $noProxy)) {
|
||||
return ProxySelection::bypassed();
|
||||
}
|
||||
|
||||
if ($schemeProxy === null) {
|
||||
return ProxySelection::none();
|
||||
}
|
||||
|
||||
return ProxySelection::proxy($schemeProxy);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a proxy URL and return its lowercased scheme.
|
||||
*
|
||||
* A proxy is an authority ([userinfo@]host[:port]) with an optional scheme;
|
||||
* a scheme-less value is an HTTP proxy. The scheme is matched anchored at
|
||||
* the start, so leading junk before it is rejected as malformed, and the
|
||||
* host and port grammar is delegated to Psr7\Rfc3986. The whole string is
|
||||
* validated up front so a malformed proxy fails the same way on every
|
||||
* handler, but the original value is what callers pin, so no normalization
|
||||
* reaches the wire. The error message never includes the proxy, which may
|
||||
* carry credentials.
|
||||
*
|
||||
* @throws InvalidArgumentException on a malformed proxy URL
|
||||
*/
|
||||
public static function proxyScheme(
|
||||
#[\SensitiveParameter]
|
||||
string $proxy
|
||||
): string {
|
||||
$parts = \explode('://', $proxy, 2);
|
||||
if (\count($parts) === 1) {
|
||||
$scheme = 'http';
|
||||
$authority = $proxy;
|
||||
} else {
|
||||
[$scheme, $authority] = $parts;
|
||||
$scheme = Psr7\Utils::asciiToLower($scheme);
|
||||
if ($scheme === '' || !Rfc3986::isValidScheme($scheme)) {
|
||||
throw new InvalidArgumentException('Invalid proxy URL.');
|
||||
}
|
||||
}
|
||||
|
||||
if (!self::isValidProxyAuthority($authority)) {
|
||||
throw new InvalidArgumentException('Invalid proxy URL.');
|
||||
}
|
||||
|
||||
return $scheme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the string is a valid proxy authority: [userinfo@]host[:port].
|
||||
*
|
||||
* A single trailing slash is tolerated; anything else after the authority
|
||||
* (a path, query, or fragment) is rejected. Userinfo is not policed here
|
||||
* (the proxy handles its own credentials); host and port grammar are
|
||||
* delegated to Psr7\Rfc3986, where a zero port is accepted and left for the
|
||||
* transport to handle as it did before.
|
||||
*/
|
||||
private static function isValidProxyAuthority(string $authority): bool
|
||||
{
|
||||
// A single trailing slash is tolerated; once removed, a proxy authority
|
||||
// ([userinfo@]host[:port]) cannot contain a path, query, or fragment
|
||||
// delimiter anywhere — including one before a later '@'.
|
||||
if (\str_ends_with($authority, '/')) {
|
||||
$authority = \substr($authority, 0, \strlen($authority) - 1);
|
||||
}
|
||||
|
||||
if ($authority === '' || \strpbrk($authority, '/?#') !== false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The host cannot contain '@', so userinfo is everything before the
|
||||
// last one. It is not validated here. A value that is only userinfo,
|
||||
// with nothing after the last '@', has no host and is rejected.
|
||||
$segments = \explode('@', $authority);
|
||||
$authority = $segments[\count($segments) - 1];
|
||||
if ($authority === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$port = null;
|
||||
if (\str_starts_with($authority, '[')) {
|
||||
$parts = \explode(']', $authority, 2);
|
||||
if (\count($parts) !== 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$host = $parts[0].']';
|
||||
$remainder = $parts[1];
|
||||
if ($remainder !== '') {
|
||||
if (!\str_starts_with($remainder, ':')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
[, $port] = \explode(':', $remainder, 2);
|
||||
}
|
||||
} elseif (\strpos($authority, ':') !== false) {
|
||||
[$host, $port] = \explode(':', $authority, 2);
|
||||
} else {
|
||||
$host = $authority;
|
||||
}
|
||||
|
||||
// A dangling "host:" carries no port, matching the previous behavior.
|
||||
if ($port === '') {
|
||||
$port = null;
|
||||
}
|
||||
|
||||
if ($host === '' || !Rfc3986::isValidHost($host)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $port === null || Rfc3986::isValidPort($port);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a no-proxy list from request options or NO_PROXY.
|
||||
*
|
||||
* @param mixed $noProxy No-proxy value as passed via request transfer options.
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function normalizeNoProxy($noProxy): array
|
||||
{
|
||||
if ($noProxy === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (\is_string($noProxy)) {
|
||||
// Entries may be separated by whitespace as well as commas,
|
||||
// matching the no_proxy environment variable conventions.
|
||||
$noProxy = \preg_split('/[\s,]+/', $noProxy);
|
||||
|
||||
if ($noProxy === false) {
|
||||
throw new \RuntimeException('Unable to split the proxy no list: '.\preg_last_error_msg());
|
||||
}
|
||||
} elseif (!\is_array($noProxy)) {
|
||||
throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings');
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($noProxy as $area) {
|
||||
if (!\is_string($area)) {
|
||||
throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings');
|
||||
}
|
||||
|
||||
$area = \trim($area, " \n\r\t\0\x0B");
|
||||
if ($area !== '') {
|
||||
$result[] = $area;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the provided URI matches any of the no-proxy areas.
|
||||
*
|
||||
* @param string[] $noProxy An array of host, host-and-port, or CIDR patterns.
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function isUriInNoProxy(UriInterface $uri, array $noProxy): bool
|
||||
{
|
||||
self::assertNoProxyList($noProxy);
|
||||
|
||||
$target = self::parseNoProxyTarget($uri);
|
||||
if ($target === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($noProxy as $area) {
|
||||
$area = \trim($area, " \n\r\t\0\x0B");
|
||||
|
||||
if ($area === '*') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$rule = self::parseNoProxyRule($area);
|
||||
if ($rule !== null && self::noProxyRuleMatches($target, $rule)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the provided host matches any of the no-proxy areas.
|
||||
*
|
||||
* This method will strip a port from the host if it is present. Domain
|
||||
* patterns are matched case-insensitively. Exact IP literal patterns are
|
||||
* matched by their normalized binary address, and a host or pattern
|
||||
* written in the inet_aton() shorthand a transport reads as an address,
|
||||
* such as 127.1 or 0x7f000001, is matched as that address.
|
||||
*
|
||||
* Areas are matched in the following cases:
|
||||
* 1. "*" (without quotes) always matches any hosts.
|
||||
* 2. An exact domain or IP literal match.
|
||||
* 3. A bare domain or a leading-dot domain matches itself and its
|
||||
* subdomains. e.g. 'mit.edu' and '.mit.edu' both match 'mit.edu'
|
||||
* and 'foo.mit.edu'.
|
||||
* 4. IP CIDR entries match IP literal hosts. e.g. '192.168.0.0/16' will
|
||||
* match '192.168.1.10' and 'fd00::/8' will match '[fd00::1]'.
|
||||
*
|
||||
* @param string $host Host to check against the patterns.
|
||||
* @param string[] $noProxy An array of host or CIDR patterns.
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
public static function isHostInNoProxy(string $host, array $noProxy): bool
|
||||
{
|
||||
if ($host === '') {
|
||||
throw new InvalidArgumentException('Empty host provided');
|
||||
}
|
||||
|
||||
self::assertNoProxyList($noProxy);
|
||||
|
||||
$target = self::parseNoProxyHostString($host);
|
||||
if ($target === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($noProxy as $area) {
|
||||
$area = \trim($area, " \n\r\t\0\x0B");
|
||||
|
||||
if ($area === '*') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$rule = self::parseNoProxyRule($area);
|
||||
if ($rule !== null && self::noProxyRuleMatches($target, $rule)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<array-key, mixed> $noProxy
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private static function assertNoProxyList(array $noProxy): void
|
||||
{
|
||||
foreach ($noProxy as $area) {
|
||||
if (!\is_string($area)) {
|
||||
throw new InvalidArgumentException('proxy no list must be null, a string, or an array of strings');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, value: string, port: int|null}|null
|
||||
*/
|
||||
private static function parseNoProxyTarget(UriInterface $uri): ?array
|
||||
{
|
||||
$host = $uri->getHost();
|
||||
if ($host === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return self::parseNoProxyHost($host, $uri->getPort() ?? self::getDefaultPort($uri->getScheme()));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, value: string, port: int|null}|null
|
||||
*/
|
||||
private static function parseNoProxyHostString(string $host): ?array
|
||||
{
|
||||
$hostAndPort = self::splitNoProxyHostAndPort($host);
|
||||
if ($hostAndPort === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$host] = $hostAndPort;
|
||||
|
||||
return self::parseNoProxyHost($host, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, value: string, port: int|null}|array{type: string, value: string, prefix: int}|null
|
||||
*/
|
||||
private static function parseNoProxyRule(string $area): ?array
|
||||
{
|
||||
$area = \trim($area, " \n\r\t\0\x0B");
|
||||
if ($area === '' || $area === '*') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// A single leading dot is ignored: ".example.com" matches
|
||||
// example.com and its subdomains exactly like a bare domain,
|
||||
// consistent with every libcurl era. The strip runs before the
|
||||
// CIDR check so ".10.0.0.0/8" is a live rule on every path.
|
||||
if ($area[0] === '.') {
|
||||
$area = \substr($area, 1);
|
||||
if ($area === '') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (\strpos($area, '/') !== false) {
|
||||
return self::parseNoProxyCidrRule($area);
|
||||
}
|
||||
|
||||
$hostAndPort = self::splitNoProxyHostAndPort($area);
|
||||
if ($hostAndPort === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$host, $port] = $hostAndPort;
|
||||
|
||||
if ($host === '*') {
|
||||
return [
|
||||
'type' => 'wildcard',
|
||||
'value' => '*',
|
||||
'port' => $port,
|
||||
];
|
||||
}
|
||||
|
||||
return self::parseNoProxyHost($host, $port);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, value: string, port: int|null}|null
|
||||
*/
|
||||
private static function parseNoProxyHost(string $host, ?int $port): ?array
|
||||
{
|
||||
if ($host !== '' && $host[0] === '[') {
|
||||
if (\substr($host, -1) !== ']') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$address = \substr($host, 1, -1);
|
||||
if (!\filter_var($address, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$host = $address;
|
||||
}
|
||||
|
||||
$packedIp = self::packHostAddress($host);
|
||||
if ($packedIp !== false) {
|
||||
return [
|
||||
'type' => 'ip',
|
||||
'value' => $packedIp,
|
||||
'port' => $port,
|
||||
];
|
||||
}
|
||||
|
||||
if ($host === '' || \strpos($host, ':') !== false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Normalize a single DNS root dot for no-proxy domain matching.
|
||||
if (\substr($host, -1) === '.') {
|
||||
$host = \substr($host, 0, -1);
|
||||
if ($host === '') {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'domain',
|
||||
'value' => Psr7\Utils::asciiToLower($host),
|
||||
'port' => $port,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: int|null}|null
|
||||
*/
|
||||
private static function splitNoProxyHostAndPort(string $area): ?array
|
||||
{
|
||||
if ($area !== '' && $area[0] === '[') {
|
||||
$closingBracket = \strpos($area, ']');
|
||||
if ($closingBracket === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$host = \substr($area, 0, $closingBracket + 1);
|
||||
$tail = \substr($area, $closingBracket + 1);
|
||||
if ($tail === '') {
|
||||
return [$host, null];
|
||||
}
|
||||
|
||||
if ($tail[0] !== ':') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$port = self::parseNoProxyPort(\substr($tail, 1));
|
||||
|
||||
return $port === null ? null : [$host, $port];
|
||||
}
|
||||
|
||||
if (self::packHostAddress($area) !== false) {
|
||||
return [$area, null];
|
||||
}
|
||||
|
||||
$colon = \strrpos($area, ':');
|
||||
if ($colon === false) {
|
||||
return [$area, null];
|
||||
}
|
||||
|
||||
$port = self::parseNoProxyPort(\substr($area, $colon + 1));
|
||||
if ($port === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [\substr($area, 0, $colon), $port];
|
||||
}
|
||||
|
||||
private static function parseNoProxyPort(string $port): ?int
|
||||
{
|
||||
return self::parseBoundedUnsignedInteger($port, 65535);
|
||||
}
|
||||
|
||||
private static function getDefaultPort(string $scheme): ?int
|
||||
{
|
||||
if ($scheme === 'http') {
|
||||
return 80;
|
||||
}
|
||||
|
||||
if ($scheme === 'https') {
|
||||
return 443;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{type: string, value: string, prefix: int}|null
|
||||
*/
|
||||
private static function parseNoProxyCidrRule(string $area): ?array
|
||||
{
|
||||
$slash = \strpos($area, '/');
|
||||
if ($slash === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prefix = \substr($area, $slash + 1);
|
||||
|
||||
$network = \substr($area, 0, $slash);
|
||||
if ($network !== '' && $network[0] === '[' && \substr($network, -1) === ']') {
|
||||
$network = \substr($network, 1, -1);
|
||||
}
|
||||
|
||||
// A bare rule denotes a host identity, but a CIDR rule uses network
|
||||
// configuration syntax, so the inet_aton() shorthand is not read as
|
||||
// a network: 127/8 would name 0.0.0.127/8 rather than 127.0.0.0/8.
|
||||
$network = self::packIpAddress($network);
|
||||
if ($network === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$prefix = self::parseBoundedUnsignedInteger($prefix, \strlen($network) * 8);
|
||||
if ($prefix === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'cidr',
|
||||
'value' => $network,
|
||||
'prefix' => $prefix,
|
||||
];
|
||||
}
|
||||
|
||||
private static function parseBoundedUnsignedInteger(string $value, int $max): ?int
|
||||
{
|
||||
if ($value === '' || !\ctype_digit($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$normalized = \ltrim($value, '0');
|
||||
$normalized = $normalized === '' ? '0' : $normalized;
|
||||
$limit = (string) $max;
|
||||
|
||||
if (\strlen($normalized) > \strlen($limit) || (\strlen($normalized) === \strlen($limit) && \strcmp($normalized, $limit) > 0)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{type: string, value: string, port: int|null} $target
|
||||
* @param array{type: string, value: string, port?: int|null, prefix?: int|null} $rule
|
||||
*/
|
||||
private static function noProxyRuleMatches(array $target, array $rule): bool
|
||||
{
|
||||
if ($rule['type'] === 'wildcard') {
|
||||
return ($rule['port'] ?? null) === null || $rule['port'] === $target['port'];
|
||||
}
|
||||
|
||||
if ($rule['type'] === 'cidr') {
|
||||
if ($target['type'] !== 'ip' || !isset($rule['prefix'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (\strlen($target['value']) !== \strlen($rule['value'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return self::ipMatchesPrefix($target['value'], $rule['value'], $rule['prefix']);
|
||||
}
|
||||
|
||||
if (($rule['port'] ?? null) !== null && $rule['port'] !== $target['port']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($rule['type'] !== $target['type']) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($rule['type'] === 'ip') {
|
||||
return $rule['value'] === $target['value'];
|
||||
}
|
||||
|
||||
if ($target['value'] === $rule['value']) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$suffix = '.'.$rule['value'];
|
||||
|
||||
return \substr($target['value'], -\strlen($suffix)) === $suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|false
|
||||
*/
|
||||
private static function packIpAddress(string $ip)
|
||||
{
|
||||
if (\filter_var($ip, \FILTER_VALIDATE_IP)) {
|
||||
return \inet_pton($ip);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|false
|
||||
*/
|
||||
private static function packHostAddress(string $host)
|
||||
{
|
||||
$packed = self::packIpAddress($host);
|
||||
if ($packed !== false) {
|
||||
return $packed;
|
||||
}
|
||||
|
||||
// A transport reads the inet_aton() shorthand as an address too, so a
|
||||
// rule and a request host that name one address have to match
|
||||
// whichever spelling each of them happens to use.
|
||||
return HostIdentity::numericIpv4ToBinary($host) ?? false;
|
||||
}
|
||||
|
||||
private static function ipMatchesPrefix(string $address, string $network, int $prefix): bool
|
||||
{
|
||||
$fullBytes = \intdiv($prefix, 8);
|
||||
$remainingBits = $prefix % 8;
|
||||
|
||||
if ($fullBytes > 0 && \substr($address, 0, $fullBytes) !== \substr($network, 0, $fullBytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($remainingBits === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$mask = (0xFF << (8 - $remainingBits)) & 0xFF;
|
||||
|
||||
return (\ord($address[$fullBytes]) & $mask) === (\ord($network[$fullBytes]) & $mask);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
final class ProxySelection
|
||||
{
|
||||
private ?string $proxy;
|
||||
|
||||
private bool $bypassed;
|
||||
|
||||
private bool $disabled;
|
||||
|
||||
private function __construct(?string $proxy, bool $bypassed, bool $disabled)
|
||||
{
|
||||
$this->proxy = $proxy;
|
||||
$this->bypassed = $bypassed;
|
||||
$this->disabled = $disabled;
|
||||
}
|
||||
|
||||
public static function none(): self
|
||||
{
|
||||
return new self(null, false, false);
|
||||
}
|
||||
|
||||
public static function proxy(string $proxy): self
|
||||
{
|
||||
return $proxy === '' ? self::disabled() : new self($proxy, false, false);
|
||||
}
|
||||
|
||||
public static function bypassed(): self
|
||||
{
|
||||
return new self(null, true, false);
|
||||
}
|
||||
|
||||
public static function disabled(): self
|
||||
{
|
||||
return new self(null, false, true);
|
||||
}
|
||||
|
||||
public function getProxy(): ?string
|
||||
{
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
public function hasProxy(): bool
|
||||
{
|
||||
return $this->proxy !== null;
|
||||
}
|
||||
|
||||
public function isBypassed(): bool
|
||||
{
|
||||
return $this->bypassed;
|
||||
}
|
||||
|
||||
public function isDisabled(): bool
|
||||
{
|
||||
return $this->disabled;
|
||||
}
|
||||
|
||||
public function shouldDisableProxy(): bool
|
||||
{
|
||||
return $this->bypassed || $this->disabled;
|
||||
}
|
||||
}
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\BadResponseException;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\ResponseException;
|
||||
use GuzzleHttp\Exception\TooManyRedirectsException;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\HttpFactory;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamFactoryInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriFactoryInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Request redirect middleware.
|
||||
*
|
||||
* Apply this middleware like other middleware using
|
||||
* {@see Middleware::redirect()}.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class RedirectMiddleware
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
public const HISTORY_HEADER = 'X-Guzzle-Redirect-History';
|
||||
|
||||
public const STATUS_HISTORY_HEADER = 'X-Guzzle-Redirect-Status-History';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
public const DEFAULT_SETTINGS = [
|
||||
'max' => 5,
|
||||
'protocols' => ['http', 'https'],
|
||||
'strict' => false,
|
||||
'referer' => false,
|
||||
'track_redirects' => false,
|
||||
];
|
||||
|
||||
/**
|
||||
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private $nextHandler;
|
||||
|
||||
/**
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler Next handler to invoke.
|
||||
*/
|
||||
public function __construct(callable $nextHandler)
|
||||
{
|
||||
$this->nextHandler = $nextHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
$fn = $this->nextHandler;
|
||||
|
||||
if (empty($options['allow_redirects'])) {
|
||||
return $fn($request, $options);
|
||||
}
|
||||
|
||||
if ($options['allow_redirects'] === true) {
|
||||
$options['allow_redirects'] = self::DEFAULT_SETTINGS;
|
||||
} elseif (!\is_array($options['allow_redirects'])) {
|
||||
throw new InvalidArgumentException('allow_redirects must be true, false, or array');
|
||||
} else {
|
||||
// Merge the default settings with the provided settings
|
||||
$options['allow_redirects'] += self::DEFAULT_SETTINGS;
|
||||
}
|
||||
|
||||
if (empty($options['allow_redirects']['max'])) {
|
||||
return $fn($request, $options);
|
||||
}
|
||||
|
||||
return $fn($request, $options)
|
||||
->then(function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($request, $options) {
|
||||
return $this->checkRedirect($request, $options, $response);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ResponseInterface|PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function checkRedirect(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) {
|
||||
if (!self::isRedirectStatusCode($response->getStatusCode())
|
||||
|| !$response->hasHeader('Location')
|
||||
) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$this->guardMax($request, $response, $options);
|
||||
$nextRequest = $this->modifyRequest($request, $options, $response);
|
||||
|
||||
// Remove HTTP origin credentials if URI is cross-origin.
|
||||
if (Psr7\UriComparator::isCrossOrigin($request->getUri(), $nextRequest->getUri())) {
|
||||
unset($options['auth'], $options['__guzzle_digest_retries']);
|
||||
|
||||
if (defined('\CURLOPT_HTTPAUTH') && defined('\CURLOPT_USERPWD')) {
|
||||
unset(
|
||||
$options['curl'][\CURLOPT_HTTPAUTH],
|
||||
$options['curl'][\CURLOPT_USERPWD]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($options['allow_redirects']['on_redirect'])) {
|
||||
($options['allow_redirects']['on_redirect'])(
|
||||
$request,
|
||||
$response,
|
||||
$nextRequest->getUri()
|
||||
);
|
||||
}
|
||||
|
||||
// The caller's delay applies once, before the initial request, not
|
||||
// before each followed redirect.
|
||||
unset($options['delay']);
|
||||
|
||||
$promise = $this($nextRequest, $options);
|
||||
|
||||
// Add headers to be able to track history of redirects.
|
||||
if (!empty($options['allow_redirects']['track_redirects'])) {
|
||||
return $this->withTracking(
|
||||
$promise,
|
||||
(string) $nextRequest->getUri(),
|
||||
$response->getStatusCode()
|
||||
);
|
||||
}
|
||||
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable tracking on promise.
|
||||
*
|
||||
* @param PromiseInterface<ResponseInterface, mixed> $promise
|
||||
*
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function withTracking(
|
||||
PromiseInterface $promise,
|
||||
#[\SensitiveParameter]
|
||||
string $uri,
|
||||
int $statusCode
|
||||
): PromiseInterface {
|
||||
return $promise->then(
|
||||
static function (
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
) use ($uri, $statusCode): ResponseInterface {
|
||||
// Note that we are pushing to the front of the list as this
|
||||
// would be an earlier response than what is currently present
|
||||
// in the history header.
|
||||
$historyHeader = $response->getHeader(self::HISTORY_HEADER);
|
||||
$statusHeader = $response->getHeader(self::STATUS_HISTORY_HEADER);
|
||||
\array_unshift($historyHeader, $uri);
|
||||
\array_unshift($statusHeader, (string) $statusCode);
|
||||
|
||||
return $response->withHeader(self::HISTORY_HEADER, $historyHeader)
|
||||
->withHeader(self::STATUS_HISTORY_HEADER, $statusHeader);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for too many redirects.
|
||||
*
|
||||
* @throws TooManyRedirectsException Too many redirects.
|
||||
*/
|
||||
private function guardMax(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
#[\SensitiveParameter]
|
||||
array &$options
|
||||
): void {
|
||||
$current = $options['__redirect_count']
|
||||
?? 0;
|
||||
$options['__redirect_count'] = $current + 1;
|
||||
$max = $options['allow_redirects']['max'];
|
||||
|
||||
if ($options['__redirect_count'] > $max) {
|
||||
throw new TooManyRedirectsException("Will not follow more than {$max} redirects", $request, $response);
|
||||
}
|
||||
}
|
||||
|
||||
public function modifyRequest(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): RequestInterface {
|
||||
$modify = self::getRedirectRequestModifiers($request, $options, $response);
|
||||
$protocols = $options['allow_redirects']['protocols'];
|
||||
|
||||
$uriFactory = $options[RequestOptions::URI_FACTORY] ?? new HttpFactory();
|
||||
if (!$uriFactory instanceof UriFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::URI_FACTORY,
|
||||
UriFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
// A server must not be able to raise the psr7 host deprecation.
|
||||
$scope = new Psr7\ErrorScope(\E_USER_DEPRECATED);
|
||||
|
||||
$modify['uri'] = $scope->run(static function () use ($uriFactory, $request, $response, $protocols, $options): UriInterface {
|
||||
$uri = self::redirectUri($uriFactory, $request, $response, $protocols);
|
||||
$idnOptions = Idn::normalizeConversionOption($options['idn_conversion'] ?? null);
|
||||
|
||||
return $idnOptions === null ? $uri : Idn::convertUri($uri, $idnOptions);
|
||||
});
|
||||
|
||||
// The body only needs to be rewound when the next request reuses it.
|
||||
if (!isset($modify['body'])) {
|
||||
try {
|
||||
Psr7\Message::rewindBody($request);
|
||||
} catch (\Exception $e) {
|
||||
throw new ResponseException(
|
||||
'Redirect failed because the request body could not be rewound',
|
||||
$request,
|
||||
$response,
|
||||
$e
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$crossOrigin = Psr7\UriComparator::isCrossOrigin($request->getUri(), $modify['uri']);
|
||||
|
||||
// Add a Referer only when the scheme is unchanged, and reduce it to the
|
||||
// origin on cross-origin redirects so a secret-bearing path or query is
|
||||
// not leaked (strict-origin-when-cross-origin, like modern browsers).
|
||||
if ($options['allow_redirects']['referer']
|
||||
&& $modify['uri']->getScheme() === $request->getUri()->getScheme()
|
||||
) {
|
||||
$referer = $request->getUri()->withUserInfo('')->withFragment('');
|
||||
if ($crossOrigin) {
|
||||
$referer = $referer->withPath('/')->withQuery('');
|
||||
}
|
||||
$modify['set_headers']['Referer'] = (string) $referer;
|
||||
} else {
|
||||
$modify['remove_headers'][] = 'Referer';
|
||||
}
|
||||
|
||||
// Remove Authorization and Cookie headers if URI is cross-origin.
|
||||
if ($crossOrigin) {
|
||||
$modify['remove_headers'][] = 'Authorization';
|
||||
$modify['remove_headers'][] = 'Cookie';
|
||||
}
|
||||
|
||||
return $scope->run(static function () use ($request, $modify): RequestInterface {
|
||||
return Psr7\Utils::modifyRequest($request, $modify);
|
||||
});
|
||||
}
|
||||
|
||||
private static function isRedirectStatusCode(int $statusCode): bool
|
||||
{
|
||||
return \in_array($statusCode, [301, 302, 303, 307, 308], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* method?: string,
|
||||
* body?: StreamInterface,
|
||||
* remove_headers?: list<string>
|
||||
* }
|
||||
*/
|
||||
private static function getRedirectRequestModifiers(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response
|
||||
): array {
|
||||
$statusCode = $response->getStatusCode();
|
||||
if ($statusCode !== 303
|
||||
&& ($statusCode > 302 || $options['allow_redirects']['strict'])
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$requestMethod = $request->getMethod();
|
||||
|
||||
if ($requestMethod === 'QUERY' && \in_array($statusCode, [301, 302], true)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$streamFactory = $options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory();
|
||||
if (!$streamFactory instanceof StreamFactoryInterface) {
|
||||
throw new InvalidArgumentException(\sprintf(
|
||||
'%s must be an instance of %s',
|
||||
RequestOptions::STREAM_FACTORY,
|
||||
StreamFactoryInterface::class
|
||||
));
|
||||
}
|
||||
|
||||
return [
|
||||
'method' => \in_array($requestMethod, ['GET', 'HEAD', 'OPTIONS'], true) ? $requestMethod : 'GET',
|
||||
'body' => $streamFactory->createStream(''),
|
||||
'remove_headers' => ['Content-Length', 'Transfer-Encoding'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the appropriate URL on the request based on the location header.
|
||||
*/
|
||||
private static function redirectUri(
|
||||
UriFactoryInterface $uriFactory,
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
ResponseInterface $response,
|
||||
array $protocols
|
||||
): UriInterface {
|
||||
$location = $response->getHeaderLine('Location');
|
||||
|
||||
try {
|
||||
$locationUri = $uriFactory->createUri($location);
|
||||
$resolvedUri = Psr7\UriResolver::resolve(
|
||||
$request->getUri(),
|
||||
$locationUri
|
||||
);
|
||||
|
||||
if (!$uriFactory instanceof HttpFactory
|
||||
&& $locationUri->getScheme() === ''
|
||||
&& $locationUri->getAuthority() === ''
|
||||
) {
|
||||
$resolvedUri = $uriFactory->createUri((string) $resolvedUri);
|
||||
}
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw new BadResponseException(\sprintf('Redirect URI, %s, is invalid.', Psr7\UriRedactor::redactUriStringForMessage($location)), $request, $response, $e);
|
||||
}
|
||||
|
||||
// Ensure that the redirect URI is allowed based on the protocols.
|
||||
if (!\in_array($resolvedUri->getScheme(), $protocols, true)) {
|
||||
throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', Psr7\UriRedactor::redactUriForMessage($resolvedUri), \implode(', ', $protocols)), $request, $response);
|
||||
}
|
||||
|
||||
return $resolvedUri;
|
||||
}
|
||||
}
|
||||
+526
@@ -0,0 +1,526 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* This class contains a list of built-in Guzzle request options.
|
||||
*
|
||||
* @see https://github.com/guzzle/guzzle/blob/8.5/docs/request-options.md
|
||||
*/
|
||||
final class RequestOptions
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* allow_redirects: (bool|array) Controls redirect behavior. Pass false
|
||||
* to disable redirects, pass true to enable redirects, or pass an
|
||||
* associative array to provide custom redirect settings. Clients enable
|
||||
* redirects by default when the default redirect middleware is present.
|
||||
* This option only works if your handler has the RedirectMiddleware. When
|
||||
* passing an associative array, you can provide the following key value
|
||||
* pairs. Only 301, 302, 303, 307, and 308 responses with a Location header
|
||||
* are followed.
|
||||
*
|
||||
* - max: (int, default=5) maximum number of allowed redirects.
|
||||
* - strict: (bool, default=false) Set to true to use strict redirects
|
||||
* meaning redirect POST requests with POST requests vs. doing what most
|
||||
* browsers do which is redirect POST requests with GET requests. The
|
||||
* QUERY method keeps its method and body across non-strict 301 and 302
|
||||
* redirects, and a 303 redirect is followed with a body-less GET.
|
||||
* - referer: (bool, default=false) Set to true to enable the Referer
|
||||
* header.
|
||||
* - protocols: (non-empty-array<array-key, 'http'|'https'>,
|
||||
* default=['http', 'https']) Allowed redirect protocols. Values are
|
||||
* case-sensitive; only "http" and "https" are accepted.
|
||||
* - on_redirect: (callable(RequestInterface, ResponseInterface, UriInterface): mixed)
|
||||
* PHP callable that is invoked when a redirect is encountered. The
|
||||
* callable is invoked with the request, the redirect response that was
|
||||
* received, and the effective URI. Any return value is ignored. When
|
||||
* this callback is supplied via GuzzleHttp\Pool's "options"
|
||||
* configuration, the pool appends the request's iterable key as a
|
||||
* fourth argument.
|
||||
* - track_redirects: (bool, default=false) Track redirected URI and status
|
||||
* history in response headers.
|
||||
*/
|
||||
public const ALLOW_REDIRECTS = 'allow_redirects';
|
||||
|
||||
/**
|
||||
* auth: (array{0: string, 1: string, 2?: string|null}|string|false|null)
|
||||
* Pass an array of HTTP authentication parameters to use with the request.
|
||||
* The array must contain the username in index [0], the password in index
|
||||
* [1], and you can optionally provide a built-in authentication type in
|
||||
* index [2]. Pass false or null to disable authentication for a request.
|
||||
* Built-in Basic and Digest authentication are applied by the auth
|
||||
* middleware, normally from HandlerStack::create(). String values are
|
||||
* passed through for custom handlers. Built-in Basic usernames must not
|
||||
* contain a colon, and neither Basic usernames nor passwords may contain
|
||||
* ASCII control characters. Basic passwords may contain colons.
|
||||
*/
|
||||
public const AUTH = 'auth';
|
||||
|
||||
/**
|
||||
* body: (resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable)
|
||||
* Body to send in the request. Resource and stringable object values are
|
||||
* converted using the configured stream_factory. Callable and iterator
|
||||
* bodies use Guzzle's existing stream handling. Strings are used as literal
|
||||
* body contents, even when they name a callable. Callable bodies may be
|
||||
* closures or invokable objects; arrays, int, float, bool, and generic
|
||||
* objects without __toString() are not valid body values.
|
||||
*/
|
||||
public const BODY = 'body';
|
||||
|
||||
/**
|
||||
* cert: (string|array{0: string, 1?: string|null}) Set to a string to
|
||||
* specify the path to a client certificate file. PEM is the default
|
||||
* certificate format. If a password is required, set cert to an array
|
||||
* containing the certificate path in the first array element followed by
|
||||
* the certificate password in the second array element. A null password is
|
||||
* treated the same as omitting it. Use cert_type to specify another
|
||||
* supported certificate format.
|
||||
*
|
||||
* @see self::CERT_TYPE
|
||||
*/
|
||||
public const CERT = 'cert';
|
||||
|
||||
/**
|
||||
* cert_type: (string) Specify the SSL client certificate file type.
|
||||
*/
|
||||
public const CERT_TYPE = 'cert_type';
|
||||
|
||||
/**
|
||||
* cookies: (false|GuzzleHttp\Cookie\CookieJarInterface, default=false)
|
||||
* Specifies whether or not cookies are used in a request or what cookie
|
||||
* jar to use or what cookies to send. This option only works if your
|
||||
* handler has the `cookie` middleware. Valid values are `false` and
|
||||
* an instance of {@see Cookie\CookieJarInterface}.
|
||||
*/
|
||||
public const COOKIES = 'cookies';
|
||||
|
||||
/**
|
||||
* connect_timeout: (int|float, default=60) Number of seconds to wait
|
||||
* while trying to connect to a server. Use 0 to disable the connect
|
||||
* timeout. Positive values below 0.001 seconds are rejected by the
|
||||
* built-in cURL handler.
|
||||
*/
|
||||
public const CONNECT_TIMEOUT = 'connect_timeout';
|
||||
|
||||
/**
|
||||
* crypto_method: (int) A value describing the minimum TLS protocol
|
||||
* version to use. The built-in cURL and stream handlers default HTTPS
|
||||
* requests to TLS 1.2 or newer.
|
||||
*
|
||||
* This setting must be set to one of the
|
||||
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. cURL 7.52.0 or higher
|
||||
* is required to use TLS 1.3 with the cURL handler.
|
||||
*/
|
||||
public const CRYPTO_METHOD = 'crypto_method';
|
||||
|
||||
/**
|
||||
* crypto_method_max: (int) A value describing the maximum TLS protocol
|
||||
* version to use. The built-in cURL and stream handlers default HTTPS
|
||||
* requests to TLS 1.2 or newer, so a lower maximum requires explicitly
|
||||
* lowering crypto_method too.
|
||||
*
|
||||
* This setting must be set to one of the
|
||||
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. cURL 7.54.0 or higher
|
||||
* is required in order to specify a maximum TLS version with the cURL
|
||||
* handler.
|
||||
*/
|
||||
public const CRYPTO_METHOD_MAX = 'crypto_method_max';
|
||||
|
||||
/**
|
||||
* curl: (array) Raw cURL options to apply when using a built-in cURL
|
||||
* handler.
|
||||
*/
|
||||
public const CURL = 'curl';
|
||||
|
||||
/**
|
||||
* debug: (bool|resource) Set to true or set to a PHP stream returned by
|
||||
* fopen() to enable debug output with the handler used to send a request.
|
||||
* For example, when using cURL to transfer requests, cURL's verbose of
|
||||
* CURLOPT_VERBOSE will be emitted. When using the PHP stream wrapper,
|
||||
* stream wrapper notifications will be emitted. If set to true, the output
|
||||
* is written to PHP's STDOUT. If a PHP stream is provided, output is
|
||||
* written to the stream.
|
||||
*/
|
||||
public const DEBUG = 'debug';
|
||||
|
||||
/**
|
||||
* decode_content: (bool|string, default=true) Specify whether or not
|
||||
* Content-Encoding responses (gzip, deflate, etc.) are automatically
|
||||
* decoded.
|
||||
*/
|
||||
public const DECODE_CONTENT = 'decode_content';
|
||||
|
||||
/**
|
||||
* delay: (int|float) The finite, non-negative amount of time to delay
|
||||
* before sending in milliseconds.
|
||||
*/
|
||||
public const DELAY = 'delay';
|
||||
|
||||
/**
|
||||
* expect: (bool|integer) Controls the behavior of the
|
||||
* "Expect: 100-Continue" header.
|
||||
*
|
||||
* Set to `true` to enable the "Expect: 100-Continue" header for all
|
||||
* requests that sends a body. Set to `false` to disable the
|
||||
* "Expect: 100-Continue" header for all requests. Set to a number so that
|
||||
* the size of the payload must be greater than the number in order to send
|
||||
* the Expect header. Setting to a number will send the Expect header for
|
||||
* all requests in which the size of the payload cannot be determined or
|
||||
* where the body is not rewindable.
|
||||
*
|
||||
* By default, Guzzle will add the "Expect: 100-Continue" header when the
|
||||
* size of the body of a request is greater than 1 MB and a request is
|
||||
* using HTTP/1.1.
|
||||
*/
|
||||
public const EXPECT = 'expect';
|
||||
|
||||
/**
|
||||
* form_params: (array<array-key, string|int|float|bool|null|array>)
|
||||
* Associative array of form field names to scalar, null, or nested array
|
||||
* values. Sets the Content-Type header to application/x-www-form-urlencoded
|
||||
* when no Content-Type header is already present.
|
||||
*/
|
||||
public const FORM_PARAMS = 'form_params';
|
||||
|
||||
/**
|
||||
* headers: (array<array-key, string|non-empty-array<array-key, string>>|null)
|
||||
* Associative array of HTTP headers. Each value MUST be a string or
|
||||
* non-empty array of strings.
|
||||
*/
|
||||
public const HEADERS = 'headers';
|
||||
|
||||
/**
|
||||
* http_errors: (bool, default=true) Set to false to disable exceptions
|
||||
* when a non-successful HTTP response is received. By default,
|
||||
* exceptions will be thrown for 4xx and 5xx responses. This option only
|
||||
* works if your handler has the `httpErrors` middleware.
|
||||
*/
|
||||
public const HTTP_ERRORS = 'http_errors';
|
||||
|
||||
/**
|
||||
* idn_conversion: (bool|int|null, default=false) A combination of IDNA_*
|
||||
* constants for PHP's idn_to_ascii() function. Set to false or null to
|
||||
* disable IDN support, or true to use the default configuration
|
||||
* (IDNA_DEFAULT constant).
|
||||
*/
|
||||
public const IDN_CONVERSION = 'idn_conversion';
|
||||
|
||||
/**
|
||||
* json: (mixed) Adds JSON data to a request. The provided value is JSON
|
||||
* encoded and a Content-Type header of application/json will be added to
|
||||
* the request if no Content-Type header is already present. An Accept
|
||||
* header is not added automatically.
|
||||
*/
|
||||
public const JSON = 'json';
|
||||
|
||||
/**
|
||||
* multipart: (array) Array of part arrays, each containing a required
|
||||
* "name" key mapping to the string or integer form field name, a required
|
||||
* "contents" key mapping to any non-array value accepted by PSR-7
|
||||
* Utils::streamFor() or a nested array of field values, an optional
|
||||
* "headers" array of string custom header values, and an optional
|
||||
* "filename" key mapping to a string to send as the filename in the part.
|
||||
* "headers" and "filename" cannot be used when "contents" is an array.
|
||||
*/
|
||||
public const MULTIPART = 'multipart';
|
||||
|
||||
/**
|
||||
* multiplex: (string, default=GuzzleHttp\Multiplexing::WAIT) Controls how a
|
||||
* request sent through a built-in cURL handler relates to shared,
|
||||
* multiplexed connections: how an HTTP/2 or HTTP/3 request pursues one, or,
|
||||
* with Multiplexing::NONE, whether the transfer may share its connection at
|
||||
* all. Use Multiplexing::EAGER to avoid waiting for pending connections,
|
||||
* Multiplexing::WAIT to wait on libcurl-eligible pending connections with
|
||||
* CURLOPT_PIPEWAIT, normally to the same origin,
|
||||
* Multiplexing::REQUIRE_EAGER to fail unless a multiplexed protocol is
|
||||
* guaranteed while dialing eagerly, or Multiplexing::REQUIRE_WAIT for the
|
||||
* same guarantee while also waiting on pending connections. The required
|
||||
* modes require a handler that permits actual multiplexing, not merely a
|
||||
* multiplexed protocol, and are rejected on a Multiplexing::NONE handler.
|
||||
* The stream handler ignores EAGER and WAIT, and rejects the required
|
||||
* family; CurlHandler has no multi handle to multiplex over. The required
|
||||
* family also rejects final CURLOPT_HTTPAUTH masks that permit NTLM, which
|
||||
* libcurl retries over HTTP/1.1. Multiplexing::NONE disables multiplexing
|
||||
* for a whole handler when passed as the "multiplex" client configuration
|
||||
* option, which configures the default handler and also becomes the default
|
||||
* request option, or, when constructing a handler directly, as the
|
||||
* CurlMultiHandler "multiplex" constructor option. A handler configured
|
||||
* with Multiplexing::NONE wins over the default WAIT: default requests run
|
||||
* without waiting, explicitly requested wait modes are rejected as a
|
||||
* configuration conflict when the transfer would actually wait, and the
|
||||
* required modes are always rejected, because they require a handler that
|
||||
* permits actual multiplexing, not merely a multiplexed protocol. As a
|
||||
* request option value, Multiplexing::NONE guarantees the transfer does not
|
||||
* share its connection with any concurrent transfer. Multiplexing::NONE
|
||||
* does not force HTTP/1.1: on a Multiplexing::NONE handler, HTTP/2 still
|
||||
* negotiates and each transfer keeps its connection to itself.
|
||||
*
|
||||
* The request option value is accepted exactly where the guarantee holds
|
||||
* and can be verified: on a CurlMultiHandler configured with
|
||||
* Multiplexing::NONE, for requests whose declared protocol version is
|
||||
* HTTP/1.x, on CurlHandler, and on the stream handler, which never
|
||||
* multiplexes. An HTTP/2 or HTTP/3 request with a Multiplexing::NONE
|
||||
* request option is rejected on a CurlMultiHandler that permits
|
||||
* multiplexing. Acceptance is decided from the request's declared protocol
|
||||
* version, before any transport-level downgrade: an HTTP/3 request sent
|
||||
* through a proxy is delivered over HTTP/2 or HTTP/1.1 on the wire, but is
|
||||
* still rejected. On a CurlMultiHandler that permits multiplexing,
|
||||
* Multiplexing::NONE is also rejected with a custom "handle_factory", when
|
||||
* the handler requires persistent transport sharing (the safeguards can
|
||||
* require a fresh connection, which required sharing forbids), when the
|
||||
* request carries an Expect: 100-continue header (its 417 retries select
|
||||
* connections outside the safeguards; remove an explicitly supplied
|
||||
* header, or set the "expect" request option to false to prevent it being
|
||||
* added automatically), and combined with a raw CURLOPT_HTTPAUTH cURL
|
||||
* option, whose authentication retries do the same.
|
||||
*
|
||||
* On a client whose multi handler permits multiplexing, the ordinary
|
||||
* non-streaming default stack - both cURL handlers available and no
|
||||
* connection caps forcing multi-only routing - runs synchronous requests on
|
||||
* the CurlHandler path, which satisfies the guarantee for any protocol
|
||||
* version, while asynchronous requests run on the CurlMultiHandler, so an
|
||||
* HTTP/2 request with Multiplexing::NONE succeeds synchronously and is
|
||||
* rejected asynchronously on the same client. Keep-alive reuse between
|
||||
* consecutive transfers is unaffected, except on libcurl versions below
|
||||
* 7.77.0 and from 8.11.0 through 8.12.1, where an accepted HTTP/1.x request
|
||||
* on a multiplexing CurlMultiHandler forces a fresh connection. Custom
|
||||
* handlers receive the "multiplex" option unchanged: its semantics are
|
||||
* handler-defined, Guzzle does not guarantee it is honored, and a
|
||||
* client-level Multiplexing::NONE with a custom handler flows to it as a
|
||||
* default request option without client-side enforcement.
|
||||
*/
|
||||
public const MULTIPLEX = 'multiplex';
|
||||
|
||||
/**
|
||||
* on_headers: (callable(ResponseInterface, RequestInterface): mixed) A
|
||||
* callable that is invoked when the HTTP headers of the final response, or
|
||||
* a 101 Switching Protocols response, have been received but the body has
|
||||
* not yet begun to download. The callable is passed the response and
|
||||
* request as {@see ResponseInterface} and {@see RequestInterface} objects,
|
||||
* respectively. If it throws, the request promise is rejected with a
|
||||
* GuzzleHttp\Exception\ResponseException (a RequestException subtype)
|
||||
* wrapping the thrown exception. When this callback is supplied via
|
||||
* GuzzleHttp\Pool's "options" configuration, the pool appends the request's
|
||||
* iterable key as a third argument.
|
||||
*/
|
||||
public const ON_HEADERS = 'on_headers';
|
||||
|
||||
/**
|
||||
* on_stats: (callable(TransferStats): mixed) allows you to get access to
|
||||
* transfer statistics of a request and access the lower level transfer
|
||||
* details of the handler associated with your client. ``on_stats`` is a
|
||||
* callable that is invoked when a handler has finished sending a request.
|
||||
* The callback is invoked with transfer statistics about the request, the
|
||||
* response received, or the error encountered. Included in the data is the
|
||||
* total amount of time taken to send the request. Exceptions thrown by
|
||||
* on_stats are not wrapped by Guzzle. Built-in handlers reject non-callable
|
||||
* values before starting the transfer. The built-in cURL handlers release
|
||||
* native easy handles before invoking on_stats and invoke it per low-level
|
||||
* transfer attempt. When this callback is supplied via GuzzleHttp\Pool's
|
||||
* "options" configuration, the pool appends the request's iterable key as a
|
||||
* second argument.
|
||||
*/
|
||||
public const ON_STATS = 'on_stats';
|
||||
|
||||
/**
|
||||
* on_trailers: (callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed)
|
||||
* A callable that is invoked exactly once when a transfer completes
|
||||
* successfully, with the HTTP trailer fields of the response. The callable
|
||||
* is passed an associative array of trailer field names mapped to lists of
|
||||
* field values, the response, and the request. The array is empty when the
|
||||
* response carried no trailer fields, and trailer field names are
|
||||
* lowercased and grouped case-insensitively while values keep their wire
|
||||
* order. The callable is never invoked for failed transfers. If it throws,
|
||||
* the request promise is rejected with a
|
||||
* GuzzleHttp\Exception\ResponseException (a RequestException subtype)
|
||||
* wrapping the thrown exception. Only the built-in cURL handlers invoke
|
||||
* on_trailers; the built-in stream handler rejects the option because it
|
||||
* cannot observe trailer fields, and the mock handler ignores it.
|
||||
* Malformed trailer field lines are discarded before parsing. Trailer
|
||||
* fields are reported separately from response headers and are never
|
||||
* merged into the response. When this callback is supplied via
|
||||
* GuzzleHttp\Pool's "options" configuration, the pool appends the
|
||||
* request's iterable key as a fourth argument.
|
||||
*/
|
||||
public const ON_TRAILERS = 'on_trailers';
|
||||
|
||||
/**
|
||||
* progress: (callable(int, int, int, int): mixed)
|
||||
* Defines a function to invoke when transfer progress is made. The function
|
||||
* accepts the following positional arguments: the total number of bytes
|
||||
* expected to be downloaded, the number of bytes downloaded so far, the
|
||||
* number of bytes expected to be uploaded, the number of bytes uploaded so
|
||||
* far. With the built-in cURL handlers, returning a truthy value aborts the
|
||||
* transfer and throwing rejects the promise with a RequestException. The
|
||||
* built-in stream handler ignores return values. When this callback is
|
||||
* supplied via GuzzleHttp\Pool's "options" configuration, the pool appends
|
||||
* the request's iterable key as a fifth argument.
|
||||
*/
|
||||
public const PROGRESS = 'progress';
|
||||
|
||||
/**
|
||||
* protocols: (non-empty-array<array-key, 'http'|'https'>,
|
||||
* default=['http', 'https']) Allowed URI schemes. Values are
|
||||
* case-sensitive; only "http" and "https" are accepted.
|
||||
*/
|
||||
public const PROTOCOLS = 'protocols';
|
||||
|
||||
/**
|
||||
* proxy: (string|array) Pass a string to specify an HTTP proxy, or an array
|
||||
* to specify different proxies for different protocols (where the key is
|
||||
* the protocol and the value is a proxy string or null). Provide a "no" key
|
||||
* as a comma- or whitespace-delimited string, array of strings, or null to
|
||||
* specify hosts, host-and-port pairs, IP literals, IP CIDR rules, or
|
||||
* wildcard rules that should not be proxied. Domain rules are matched
|
||||
* case-insensitively. Exact IP literals are normalized before matching,
|
||||
* including the inet_aton() shorthand spellings a transport reads as an
|
||||
* address. CIDR rules match IP literals only and are not port-specific.
|
||||
* Custom handlers can use ProxyOptions::resolve() to apply
|
||||
* Guzzle-compatible proxy selection; the built-in handlers'
|
||||
* environment-variable fallback is not part of that helper.
|
||||
*/
|
||||
public const PROXY = 'proxy';
|
||||
|
||||
/**
|
||||
* query: (array<array-key, mixed>|string) Associative array of query string
|
||||
* values to add to the request. This option uses PHP's http_build_query()
|
||||
* to create the string representation. Pass a string value if you need
|
||||
* more control than what this method provides
|
||||
*/
|
||||
public const QUERY = 'query';
|
||||
|
||||
/**
|
||||
* request_factory: (Psr\Http\Message\RequestFactoryInterface) PSR-17
|
||||
* request factory used when creating requests through request() and
|
||||
* requestAsync().
|
||||
*/
|
||||
public const REQUEST_FACTORY = 'request_factory';
|
||||
|
||||
/**
|
||||
* stream_factory: (Psr\Http\Message\StreamFactoryInterface) PSR-17
|
||||
* stream factory used when creating request body streams from body,
|
||||
* form_params, and json request options, and when the built-in handlers
|
||||
* create response body streams.
|
||||
*/
|
||||
public const STREAM_FACTORY = 'stream_factory';
|
||||
|
||||
/**
|
||||
* response_factory: (Psr\Http\Message\ResponseFactoryInterface) PSR-17
|
||||
* response factory used by the built-in handlers when creating the
|
||||
* response message.
|
||||
*/
|
||||
public const RESPONSE_FACTORY = 'response_factory';
|
||||
|
||||
/**
|
||||
* sink: (resource|string|StreamInterface) Where the data of the
|
||||
* response is written to. Defaults to a PHP temp stream. Providing a
|
||||
* string will write data to a file by the given name. Built-in handlers
|
||||
* treat PHP resources as caller-owned; callers are responsible for closing
|
||||
* resource sinks.
|
||||
*/
|
||||
public const SINK = 'sink';
|
||||
|
||||
/**
|
||||
* synchronous: (bool) Set to true to inform HTTP handlers that you intend
|
||||
* on waiting on the response. This can be useful for optimizations. Note
|
||||
* that a promise is still returned if you are using one of the async
|
||||
* client methods.
|
||||
*/
|
||||
public const SYNCHRONOUS = 'synchronous';
|
||||
|
||||
/**
|
||||
* ssl_key: (array{0: string, 1?: string|null}|string) Specify the path to
|
||||
* a private SSL key file. PEM is the default private key format. If a
|
||||
* password is required, set ssl_key to an array containing the key path in
|
||||
* the first array element followed by the key password in the second
|
||||
* element. A null password is treated the same as omitting it. Use
|
||||
* ssl_key_type to specify another supported key format.
|
||||
*
|
||||
* @see self::SSL_KEY_TYPE
|
||||
*/
|
||||
public const SSL_KEY = 'ssl_key';
|
||||
|
||||
/**
|
||||
* ssl_key_type: (string) Specify the SSL private key file type.
|
||||
*/
|
||||
public const SSL_KEY_TYPE = 'ssl_key_type';
|
||||
|
||||
/**
|
||||
* stream: (bool) Set to true to attempt to stream a response rather than
|
||||
* download it all up-front.
|
||||
*/
|
||||
public const STREAM = 'stream';
|
||||
|
||||
/**
|
||||
* stream_context: (array) PHP stream context options to merge into the
|
||||
* context used by the built-in stream handler.
|
||||
*/
|
||||
public const STREAM_CONTEXT = 'stream_context';
|
||||
|
||||
/**
|
||||
* verify: (bool|string, default=true) Describes the SSL certificate
|
||||
* verification behavior of a request. Set to true to enable SSL
|
||||
* certificate verification using the system CA bundle when available
|
||||
* (the default). Set to false to disable certificate verification (this
|
||||
* is insecure!). Set to a string to provide the path to a CA bundle on
|
||||
* disk to enable verification using a custom certificate.
|
||||
*/
|
||||
public const VERIFY = 'verify';
|
||||
|
||||
/**
|
||||
* timeout: (int|float, default=0) Number of seconds to use as the total
|
||||
* timeout of the request. Use 0 to disable the total timeout (the default
|
||||
* behavior). Positive values below 0.001 seconds are rejected by the
|
||||
* built-in handlers.
|
||||
*/
|
||||
public const TIMEOUT = 'timeout';
|
||||
|
||||
/**
|
||||
* read_timeout: (int|float, default=60) Number of seconds the connection
|
||||
* may sit silent at any stage of the request. Use 0 to disable the idle
|
||||
* timeout. Positive values below 0.001 seconds are rejected by the
|
||||
* built-in stream handler.
|
||||
*/
|
||||
public const READ_TIMEOUT = 'read_timeout';
|
||||
|
||||
/**
|
||||
* retries: (int) Current retry count used by the retry middleware.
|
||||
*/
|
||||
public const RETRIES = 'retries';
|
||||
|
||||
/**
|
||||
* uri_factory: (Psr\Http\Message\UriFactoryInterface) PSR-17 URI factory
|
||||
* used when creating URI objects from string request URI, base_uri, and
|
||||
* redirect Location values.
|
||||
*/
|
||||
public const URI_FACTORY = 'uri_factory';
|
||||
|
||||
/**
|
||||
* version: (string|int|float, default=1.1) Specifies the HTTP protocol
|
||||
* version to attempt to use.
|
||||
*
|
||||
* Guzzle defaults to HTTP/1.1. The built-in stream handler supports
|
||||
* HTTP/1.0 and HTTP/1.1. The built-in cURL handler also supports HTTP/2
|
||||
* and HTTP/3 when the installed cURL stack reports those features. For
|
||||
* HTTP/2 and HTTP/3, libcurl may use a lower HTTP version when
|
||||
* negotiation or connection setup falls back.
|
||||
*/
|
||||
public const VERSION = 'version';
|
||||
|
||||
/**
|
||||
* force_ip_resolve: ("v4"|"v6") Set to "v4" to force IPv4 resolution or
|
||||
* "v6" to force IPv6 resolution when supported by the handler.
|
||||
*/
|
||||
public const FORCE_IP_RESOLVE = 'force_ip_resolve';
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
/**
|
||||
* Middleware that retries requests based on the boolean result of
|
||||
* invoking the provided "decider" function.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class RetryMiddleware
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private $nextHandler;
|
||||
|
||||
/**
|
||||
* @var callable(int, RequestInterface, ResponseInterface|null, mixed): bool
|
||||
*/
|
||||
private $decider;
|
||||
|
||||
/**
|
||||
* @var callable(int, ResponseInterface|null, RequestInterface): int
|
||||
*/
|
||||
private $delay;
|
||||
|
||||
/**
|
||||
* @param callable(int, RequestInterface, ResponseInterface|null, mixed): bool $decider Function that accepts the number of retries,
|
||||
* a request, [response], and [rejection reason]
|
||||
* and returns true if the request is to be retried.
|
||||
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler Next handler to invoke.
|
||||
* @param (callable(int, ResponseInterface|null, RequestInterface): int)|null $delay Function that returns the number of milliseconds to delay.
|
||||
*/
|
||||
public function __construct(callable $decider, callable $nextHandler, ?callable $delay = null)
|
||||
{
|
||||
$this->decider = $decider;
|
||||
$this->nextHandler = $nextHandler;
|
||||
$this->delay = $delay ?: static function (int $retries): int {
|
||||
return (int) ((2 ** ($retries - 1)) * 1000);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
public function __invoke(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options
|
||||
): PromiseInterface {
|
||||
if (!isset($options['retries'])) {
|
||||
$options['retries'] = 0;
|
||||
} elseif (!\is_int($options['retries'])) {
|
||||
throw new \InvalidArgumentException('retries must be an integer');
|
||||
}
|
||||
|
||||
/** @var PromiseInterface<ResponseInterface, mixed> */
|
||||
return ($this->nextHandler)($request, $options)
|
||||
->then(
|
||||
$this->onFulfilled($request, $options),
|
||||
$this->onRejected($request, $options)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute fulfilled closure
|
||||
*/
|
||||
private function onFulfilled(RequestInterface $request, array $options): callable
|
||||
{
|
||||
return function (
|
||||
#[\SensitiveParameter]
|
||||
$value
|
||||
) use ($request, $options) {
|
||||
if (!($this->decider)(
|
||||
$options['retries'],
|
||||
$request,
|
||||
$value,
|
||||
null
|
||||
)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return $this->doRetry($request, $options, $value);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute rejected closure
|
||||
*/
|
||||
private function onRejected(RequestInterface $req, array $options): callable
|
||||
{
|
||||
return function (
|
||||
#[\SensitiveParameter]
|
||||
$reason
|
||||
) use ($req, $options): PromiseInterface {
|
||||
if (!($this->decider)(
|
||||
$options['retries'],
|
||||
$req,
|
||||
null,
|
||||
$reason
|
||||
)) {
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
|
||||
/** @var PromiseInterface<mixed, mixed> */
|
||||
return $this->doRetry($req, $options);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private function doRetry(
|
||||
#[\SensitiveParameter]
|
||||
RequestInterface $request,
|
||||
#[\SensitiveParameter]
|
||||
array $options,
|
||||
#[\SensitiveParameter]
|
||||
?ResponseInterface $response = null
|
||||
): PromiseInterface {
|
||||
++$options['retries'];
|
||||
$options['delay'] = ($this->delay)($options['retries'], $response, $request);
|
||||
|
||||
return $this($request, $options);
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Represents data at the point after it was transferred either successfully
|
||||
* or after a network error.
|
||||
*/
|
||||
final class TransferStats
|
||||
{
|
||||
private RequestInterface $request;
|
||||
|
||||
private ?ResponseInterface $response;
|
||||
|
||||
private ?float $transferTime;
|
||||
|
||||
private array $handlerStats;
|
||||
|
||||
/**
|
||||
* @var mixed|null
|
||||
*/
|
||||
private $handlerErrorData;
|
||||
|
||||
/**
|
||||
* @param RequestInterface $request Request that was sent.
|
||||
* @param ResponseInterface|null $response Response received (if any)
|
||||
* @param float|null $transferTime Total handler transfer time.
|
||||
* @param mixed $handlerErrorData Handler error data.
|
||||
* @param array $handlerStats Handler specific stats.
|
||||
*/
|
||||
public function __construct(
|
||||
RequestInterface $request,
|
||||
?ResponseInterface $response = null,
|
||||
?float $transferTime = null,
|
||||
$handlerErrorData = null,
|
||||
array $handlerStats = []
|
||||
) {
|
||||
$this->request = $request;
|
||||
$this->response = $response;
|
||||
$this->transferTime = $transferTime;
|
||||
$this->handlerErrorData = $handlerErrorData;
|
||||
$this->handlerStats = $handlerStats;
|
||||
}
|
||||
|
||||
public function getRequest(): RequestInterface
|
||||
{
|
||||
return $this->request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the response that was received (if any).
|
||||
*/
|
||||
public function getResponse(): ?ResponseInterface
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a response was received.
|
||||
*/
|
||||
public function hasResponse(): bool
|
||||
{
|
||||
return $this->response !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets handler specific error data.
|
||||
*
|
||||
* This might be an exception, a integer representing an error code, or
|
||||
* anything else. Relying on this value assumes that you know what handler
|
||||
* you are using.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getHandlerErrorData()
|
||||
{
|
||||
return $this->handlerErrorData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the effective URI the request was sent to.
|
||||
*/
|
||||
public function getEffectiveUri(): UriInterface
|
||||
{
|
||||
return $this->request->getUri();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the estimated time the request was being transferred by the handler.
|
||||
*
|
||||
* @return float|null Time in seconds.
|
||||
*/
|
||||
public function getTransferTime(): ?float
|
||||
{
|
||||
return $this->transferTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of all of the handler specific transfer data.
|
||||
*/
|
||||
public function getHandlerStats(): array
|
||||
{
|
||||
return $this->handlerStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific handler statistic from the handler by name.
|
||||
*
|
||||
* @param string $stat Handler specific transfer stat to retrieve.
|
||||
*
|
||||
* @return mixed|null
|
||||
*/
|
||||
public function getHandlerStat(string $stat)
|
||||
{
|
||||
return $this->handlerStats[$stat] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
final class TransportSharing
|
||||
{
|
||||
public const NONE = 'none';
|
||||
public const HANDLER_PREFER = 'handler_prefer';
|
||||
public const HANDLER_REQUIRE = 'handler_require';
|
||||
public const PERSISTENT_PREFER = 'persistent_prefer';
|
||||
public const PERSISTENT_REQUIRE = 'persistent_require';
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
}
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Handler\CurlHandler;
|
||||
use GuzzleHttp\Handler\CurlMultiHandler;
|
||||
use GuzzleHttp\Handler\CurlShareHandleState;
|
||||
use GuzzleHttp\Handler\CurlVersion;
|
||||
use GuzzleHttp\Handler\DebugResource;
|
||||
use GuzzleHttp\Handler\HeaderProcessor;
|
||||
use GuzzleHttp\Handler\Protocols;
|
||||
use GuzzleHttp\Handler\Proxy;
|
||||
use GuzzleHttp\Handler\StreamHandler;
|
||||
use GuzzleHttp\Handler\StreamTlsSessionCache;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
final class Utils
|
||||
{
|
||||
/**
|
||||
* @var (callable(array<string, mixed>, callable(): callable): callable)|null
|
||||
*/
|
||||
private static $defaultHandlerFactory;
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an array of header lines into an associative array of headers.
|
||||
*
|
||||
* @param iterable $lines Header lines array of strings in the following
|
||||
* format: "Name: Value"
|
||||
*
|
||||
* @deprecated Utils::headersFromLines() will be removed in
|
||||
* guzzlehttp/guzzle:9.0.
|
||||
*/
|
||||
public static function headersFromLines(iterable $lines): array
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'8.5',
|
||||
'%s() is deprecated and will be removed in 9.0.',
|
||||
__METHOD__
|
||||
);
|
||||
|
||||
return HeaderProcessor::headersFromLines($lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a debug stream based on the provided variable.
|
||||
*
|
||||
* @param mixed $value Optional value
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @deprecated Utils::debugResource() will be removed in
|
||||
* guzzlehttp/guzzle:9.0.
|
||||
*/
|
||||
public static function debugResource($value = null)
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'8.5',
|
||||
'%s() is deprecated and will be removed in 9.0.',
|
||||
__METHOD__
|
||||
);
|
||||
|
||||
return DebugResource::from($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a factory that creates the default handler in place of the built-in
|
||||
* selection.
|
||||
*
|
||||
* The factory receives the handler options and a callable that returns the
|
||||
* handler Guzzle would have chosen. It is consulted each time a default
|
||||
* handler is chosen, after the handler options have been checked for type
|
||||
* and value. Passing null restores the built-in selection.
|
||||
*
|
||||
* The factory is process-wide, so set it from application bootstrap code,
|
||||
* not from a library.
|
||||
*
|
||||
* @param (callable(array<string, mixed>, callable(): callable): callable)|null $factory
|
||||
*/
|
||||
public static function setDefaultHandlerFactory(?callable $factory): void
|
||||
{
|
||||
self::$defaultHandlerFactory = $factory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Chooses and creates a default handler to use based on the environment.
|
||||
*
|
||||
* The returned handler is not wrapped by any default middlewares.
|
||||
*
|
||||
* A factory set with setDefaultHandlerFactory() creates the handler in
|
||||
* place of the built-in selection.
|
||||
*
|
||||
* @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options.
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the best handler for the given system.
|
||||
*
|
||||
* @throws \RuntimeException if no viable Handler is available.
|
||||
*/
|
||||
public static function chooseHandler(array $handlerOptions = []): callable
|
||||
{
|
||||
$sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing');
|
||||
$sharingRequired = self::isTransportSharingRequired($sharingMode);
|
||||
$connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions);
|
||||
|
||||
$maxIdleHandles = $handlerOptions['max_idle_handles'] ?? null;
|
||||
if ($maxIdleHandles !== null && (!\is_int($maxIdleHandles) || $maxIdleHandles < 0)) {
|
||||
throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.');
|
||||
}
|
||||
|
||||
if (self::$defaultHandlerFactory === null) {
|
||||
return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions);
|
||||
}
|
||||
|
||||
return (self::$defaultHandlerFactory)($handlerOptions, static function () use ($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions): callable {
|
||||
return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private static function chooseBuiltInHandler(string $sharingMode, bool $sharingRequired, bool $connectionCapsRequired, array $handlerOptions): callable
|
||||
{
|
||||
$sharedPoolCapsSupported = CurlVersion::supportsSharedPoolConnectionCaps();
|
||||
|
||||
if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_REQUIRE) {
|
||||
throw new InvalidArgumentException(\sprintf('The "max_host_connections" and "max_total_connections" options cannot be combined with required persistent transport sharing because applying connection caps to shared connection pools requires libcurl %s or higher.', CurlVersion::SHARED_POOL_CONNECTION_CAP_VERSION));
|
||||
}
|
||||
|
||||
if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_PREFER) {
|
||||
// libcurl below 8.22.0 does not apply cURL multi connection caps to
|
||||
// transfers using a shared connection pool (curl #22265), so the
|
||||
// best honorable offer for preferred persistent sharing is a
|
||||
// handler-lifetime share.
|
||||
$sharingMode = TransportSharing::HANDLER_PREFER;
|
||||
}
|
||||
|
||||
$handler = self::createCurlHandler($sharingMode, $handlerOptions);
|
||||
|
||||
// Handler-scoped required sharing can also be satisfied by the stream
|
||||
// handler's TLS session resumption (PHP 8.6+); persistent required
|
||||
// sharing is cURL-only.
|
||||
$streamCanShareSessions = (bool) \ini_get('allow_url_fopen') && StreamTlsSessionCache::isSupported();
|
||||
|
||||
if ($sharingRequired && $handler === null) {
|
||||
if ($sharingMode === TransportSharing::PERSISTENT_REQUIRE) {
|
||||
throw new \RuntimeException('Required persistent transport sharing requires the PHP cURL extension, curl_exec() or curl_multi_exec(), and a supported libcurl version with SSL support.');
|
||||
}
|
||||
|
||||
if (!$streamCanShareSessions) {
|
||||
throw new \RuntimeException('Required transport sharing requires the PHP cURL extension (curl_exec()/curl_multi_exec()) with a supported libcurl version and SSL support, or PHP 8.6+ with the OpenSSL TLS session API and the allow_url_fopen ini setting.');
|
||||
}
|
||||
}
|
||||
|
||||
if (\ini_get('allow_url_fopen')) {
|
||||
return self::addStreamHandler($handler, $sharingMode, self::connectionCapOptions($handlerOptions));
|
||||
}
|
||||
|
||||
if ($handler !== null) {
|
||||
return $handler;
|
||||
}
|
||||
|
||||
if ($connectionCapsRequired) {
|
||||
throw new \RuntimeException('Connection cap options require a cap-capable cURL multi handler or the allow_url_fopen ini setting for stream fallback.');
|
||||
}
|
||||
|
||||
throw new \RuntimeException('GuzzleHttp requires a supported cURL version with SSL support, the allow_url_fopen ini setting, or a custom HTTP handler.');
|
||||
}
|
||||
|
||||
private static function isTransportSharingRequired(string $sharingMode): bool
|
||||
{
|
||||
return \in_array($sharingMode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
|
||||
*/
|
||||
private static function hasConnectionCapOptions(array $handlerOptions): bool
|
||||
{
|
||||
return self::connectionCapOptions($handlerOptions) !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions
|
||||
*
|
||||
* @return (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)|null
|
||||
*/
|
||||
private static function createCurlHandler(string $sharingMode, array $handlerOptions): ?callable
|
||||
{
|
||||
if (!CurlVersion::supportsCurlHandler()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($sharingMode === TransportSharing::HANDLER_REQUIRE && !CurlShareHandleState::supportsHandlerRequireShare()) {
|
||||
// Required handler sharing can also be satisfied by the stream
|
||||
// handler's TLS session resumption, so a cURL install that cannot
|
||||
// share is skipped instead of failing handler selection.
|
||||
return null;
|
||||
}
|
||||
|
||||
$connectionCapOptions = self::connectionCapOptions($handlerOptions);
|
||||
if ($connectionCapOptions !== [] && !\function_exists('curl_multi_exec')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$curlHandlerOptions = self::createCurlHandlerOptions($sharingMode);
|
||||
if (isset($handlerOptions['max_idle_handles'])) {
|
||||
$curlHandlerOptions['max_idle_handles'] = $handlerOptions['max_idle_handles'];
|
||||
}
|
||||
$curlMultiHandlerOptions = $curlHandlerOptions + $connectionCapOptions;
|
||||
if (($handlerOptions['multiplex'] ?? null) === Multiplexing::NONE) {
|
||||
// Forwarded to the CurlMultiHandler only: CurlHandler and
|
||||
// StreamHandler validate known options, and both satisfy NONE
|
||||
// per-request without a handler option.
|
||||
$curlMultiHandlerOptions['multiplex'] = Multiplexing::NONE;
|
||||
}
|
||||
|
||||
if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
|
||||
$multiHandler = new CurlMultiHandler($curlMultiHandlerOptions);
|
||||
|
||||
if ($connectionCapOptions !== []) {
|
||||
// Connection caps only govern transfers on the multi handle, so
|
||||
// the synchronous CurlHandler fast path would escape them.
|
||||
return $multiHandler;
|
||||
}
|
||||
|
||||
return Proxy::wrapSync($multiHandler, new CurlHandler($curlHandlerOptions));
|
||||
}
|
||||
|
||||
if ($connectionCapOptions === [] && \function_exists('curl_exec')) {
|
||||
return new CurlHandler($curlHandlerOptions);
|
||||
}
|
||||
|
||||
if (\function_exists('curl_multi_exec')) {
|
||||
return new CurlMultiHandler($curlMultiHandlerOptions);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function createCurlHandlerOptions(string $sharingMode): array
|
||||
{
|
||||
if ($sharingMode === TransportSharing::NONE) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$shareState = CurlShareHandleState::fromOption($sharingMode);
|
||||
|
||||
return $shareState === null ? [] : ['transport_sharing' => $shareState];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{max_host_connections?: mixed, max_total_connections?: mixed} $handlerOptions
|
||||
*
|
||||
* @return array{max_host_connections?: int, max_total_connections?: int}
|
||||
*/
|
||||
private static function connectionCapOptions(array $handlerOptions): array
|
||||
{
|
||||
$options = [];
|
||||
foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
|
||||
$value = $handlerOptions[$capOption] ?? null;
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!\is_int($value) || $value < 1) {
|
||||
throw new InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption));
|
||||
}
|
||||
|
||||
$options[$capOption] = $value;
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param (callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>)|null $handler
|
||||
* @param array{max_host_connections?: int, max_total_connections?: int} $connectionCapOptions
|
||||
*
|
||||
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
|
||||
*/
|
||||
private static function addStreamHandler(?callable $handler, string $sharingMode, array $connectionCapOptions): callable
|
||||
{
|
||||
$streamHandler = new StreamHandler(['transport_sharing' => $sharingMode] + $connectionCapOptions);
|
||||
|
||||
return $handler
|
||||
? Proxy::wrapStreaming($handler, $streamHandler)
|
||||
: $streamHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default User-Agent string to use with Guzzle.
|
||||
*
|
||||
* @deprecated Utils::defaultUserAgent() will be removed in
|
||||
* guzzlehttp/guzzle:9.0. Use ClientInterface::MAJOR_VERSION
|
||||
* to build the string instead.
|
||||
*/
|
||||
public static function defaultUserAgent(): string
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'8.5',
|
||||
'%s() is deprecated and will be removed in 9.0. Use %s::MAJOR_VERSION to build the string instead.',
|
||||
__METHOD__,
|
||||
ClientInterface::class
|
||||
);
|
||||
|
||||
return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an associative array of lowercase header names to the actual
|
||||
* header casing.
|
||||
*
|
||||
* @deprecated Utils::normalizeHeaderKeys() will be removed in
|
||||
* guzzlehttp/guzzle:9.0.
|
||||
*/
|
||||
public static function normalizeHeaderKeys(array $headers): array
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'8.5',
|
||||
'%s() is deprecated and will be removed in 9.0.',
|
||||
__METHOD__
|
||||
);
|
||||
|
||||
return HeaderProcessor::normalizeHeaderKeys($headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $protocols
|
||||
*
|
||||
* @return string[]
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*
|
||||
* @deprecated Utils::normalizeProtocols() will be removed in
|
||||
* guzzlehttp/guzzle:9.0.
|
||||
*/
|
||||
public static function normalizeProtocols($protocols): array
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'8.5',
|
||||
'%s() is deprecated and will be removed in 9.0.',
|
||||
__METHOD__
|
||||
);
|
||||
|
||||
return Protocols::normalize($protocols);
|
||||
}
|
||||
}
|
||||
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
# Agent Guidelines
|
||||
|
||||
## Code and tooling
|
||||
|
||||
- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer
|
||||
only under a PHP 7.4.x runtime; never run either tool under any other PHP
|
||||
major.minor version.
|
||||
- Use fully qualified `#[\SensitiveParameter]` on concrete executable
|
||||
parameters when their established role normally carries a secret,
|
||||
credential-bearing aggregate, or confidential Guzzle-owned container, and
|
||||
the active frame can throw or invoke throwing code.
|
||||
- Repeat the attribute on every qualifying owned caller, callee, concrete trait
|
||||
method, and closure parameter. Do not add it to interfaces, abstract-only
|
||||
declarations, pure/no-realistic-throw helpers, assignment-only sites,
|
||||
arbitrary generic payloads, or completed non-recoverable derivatives.
|
||||
- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and
|
||||
the parameter on the following line, expand the complete parameter list, and
|
||||
never add a comma after the final parameter. Native trace redaction starts on
|
||||
PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured
|
||||
variables, return values, or the separate backtrace `$this`/`object`.
|
||||
- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`;
|
||||
never rely on the default characters.
|
||||
- Handle `preg_*` engine failures: when the result is used as data, test for
|
||||
`false` or `null` and throw a `\RuntimeException` including
|
||||
`preg_last_error_msg()`; boolean validation guards must compare strictly, such
|
||||
as `=== 1`, so an engine failure can only ever fail closed. Diagnostic
|
||||
escaping is the narrow exception: use a deterministic bytewise fallback rather
|
||||
than throwing, so it cannot obscure the original exception.
|
||||
- Anchor validation patterns to the true end of input with the `D` modifier or
|
||||
`\z`; a bare `$` accepts a trailing newline.
|
||||
- Never embed raw control bytes in exception messages and other diagnostics;
|
||||
escape or redact the offending value first.
|
||||
- Helper classes that expose only public static methods are `final` and have a
|
||||
private constructor.
|
||||
- Resist native PHP serialization when a class holds live state (streams,
|
||||
resources, handles, callbacks, credentials); plain data holders remain
|
||||
serializable.
|
||||
- To resist, `__serialize()` and `__unserialize()` both throw
|
||||
`\LogicException(static::class.' should never be serialized')` and its
|
||||
unserialized counterpart, via the `@internal` `NonSerializableTrait`.
|
||||
- In general, numeric inputs should not accept non-finite floats. In situations
|
||||
where they are accepted and we need to cast to a string, we should branch on
|
||||
`\is_finite($value)`, using `(string) $value` for the finite case and
|
||||
`\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise.
|
||||
- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or
|
||||
other locale-sensitive case functions; fold ASCII case with
|
||||
`strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`
|
||||
and its inverse instead.
|
||||
- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of
|
||||
the target branch and an `UPGRADING.md` note when the behavior differs between
|
||||
major versions.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never
|
||||
split a markdown link or an inline code span across a line break; a line that
|
||||
cannot be broken may exceed the limit. Avoid em dashes.
|
||||
- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is
|
||||
deliberately word-for-word identical, including boilerplate copied verbatim
|
||||
between related functions, so apply the same edit to every copy. Only
|
||||
formatting and linking may differ, such as a docs link becoming a PHPDoc
|
||||
`@see` tag; the wording must never drift.
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
# CHANGELOG
|
||||
|
||||
|
||||
## 3.2.0 - 2026-11-21
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `Coroutine` to forward cancellation from chained promises
|
||||
- Changed `TaskQueue` to remove tasks in constant time
|
||||
|
||||
|
||||
## 3.1.2 - 2026-11-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `LogicException` when a callback settles its own promise
|
||||
|
||||
|
||||
## 3.1.1 - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `Promise` losing its handlers when a thenable's `then()` throws
|
||||
- Fixed `Create::promiseFor()` throwing when a thenable's `then()` throws
|
||||
- Fixed quadratic handler forwarding through chains of pending promises
|
||||
- Fixed `Utils::inspect()` losing the outcome of a chained promise
|
||||
|
||||
|
||||
## 3.1.0 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- Added `State` promise state checks as a replacement for `Is`
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Deprecated `Is` because PHP 8.6 deprecates `is` as a class name
|
||||
|
||||
|
||||
## 3.0.2 - 2026-08-24
|
||||
|
||||
### Added
|
||||
|
||||
- Added support for PHP 8.6
|
||||
|
||||
|
||||
## 3.0.1 - 2026-08-05
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed the default `TReason` of `FulfilledPromise` and `Create::promiseFor()` to `never`
|
||||
- Changed the default `TValue` of `RejectedPromise` and `Create::rejectionFor()` to `never`
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `EachPromise` abandoning its aggregate when the pending window drains unsettled
|
||||
- Fixed `EachPromise` admitting new work after its aggregate has settled
|
||||
|
||||
|
||||
## 3.0.0 - 2026-07-20
|
||||
|
||||
### Added
|
||||
|
||||
- Added `concurrency` config support to `Utils::all()` and `Each::of()`
|
||||
- Added generic PHPDoc annotations to promise APIs and collection callbacks
|
||||
- Added recursive and `concurrency` config support to `Utils::settle()`
|
||||
- Allowed promises to be resolved without passing a value
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `Utils::inspect()` to return actual rejection reasons
|
||||
- Changed `Utils::inspect()` to prefer the settled state over late wait function exceptions
|
||||
- Changed late rejection callbacks to follow rejected promises
|
||||
- Reject native PHP serialization of in-flight runtime objects
|
||||
- Made static helper classes non-instantiable
|
||||
- Require iterable inputs for promise collection helpers and `EachPromise`
|
||||
- Iterate `IteratorAggregate` inputs to collection helpers instead of treating them as a single value
|
||||
- Improved recursive `Utils::all()` handling of dynamically-added settled values and raw values
|
||||
|
||||
### Removed
|
||||
|
||||
- Dropped support for PHP 7.2 and 7.3
|
||||
|
||||
|
||||
## 2.5.1 - 2026-07-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed recursive `Utils::all()` rejecting generator inputs
|
||||
|
||||
|
||||
## 2.5.0 - 2026-06-02
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Deprecated passing non-iterable inputs to promise collection helpers and `EachPromise`
|
||||
|
||||
|
||||
## 2.4.1 - 2026-05-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed cancelling settled coroutines when no current promise remains
|
||||
|
||||
|
||||
## 2.4.0 - 2026-05-20
|
||||
|
||||
### Changed
|
||||
|
||||
- Empty `EachPromise` instances now resolve when the task queue runs without `wait()`
|
||||
|
||||
|
||||
## 2.3.1 - 2026-05-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `Utils::inspect()` returning the internal reason array instead of the `AggregateException`
|
||||
|
||||
|
||||
## 2.3.0 - 2025-08-22
|
||||
|
||||
### Added
|
||||
|
||||
- PHP 8.5 support
|
||||
|
||||
|
||||
## 2.2.0 - 2025-03-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- Revert "Allow an empty EachPromise to be resolved by running the queue"
|
||||
|
||||
|
||||
## 2.1.0 - 2025-03-27
|
||||
|
||||
### Added
|
||||
|
||||
- Allow an empty EachPromise to be resolved by running the queue
|
||||
|
||||
|
||||
## 2.0.4 - 2024-10-17
|
||||
|
||||
### Fixed
|
||||
|
||||
- Once settled, don't allow further rejection of additional promises
|
||||
|
||||
|
||||
## 2.0.3 - 2024-07-18
|
||||
|
||||
### Changed
|
||||
|
||||
- PHP 8.4 support
|
||||
|
||||
|
||||
## 2.0.2 - 2023-12-03
|
||||
|
||||
### Changed
|
||||
|
||||
- Replaced `call_user_func*` with native calls
|
||||
|
||||
|
||||
## 2.0.1 - 2023-08-03
|
||||
|
||||
### Changed
|
||||
|
||||
- PHP 8.3 support
|
||||
|
||||
|
||||
## 2.0.0 - 2023-05-21
|
||||
|
||||
### Added
|
||||
|
||||
- Added PHP 7 type hints
|
||||
|
||||
### Changed
|
||||
|
||||
- All previously non-final non-exception classes have been marked as soft-final
|
||||
|
||||
### Removed
|
||||
|
||||
- Dropped PHP < 7.2 support
|
||||
- All functions in the `GuzzleHttp\Promise` namespace
|
||||
|
||||
|
||||
## 1.5.3 - 2023-05-21
|
||||
|
||||
### Changed
|
||||
|
||||
- Removed remaining usage of deprecated functions
|
||||
|
||||
|
||||
## 1.5.2 - 2022-08-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Officially support PHP 8.2
|
||||
|
||||
|
||||
## 1.5.1 - 2021-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Revert "Call handler when waiting on fulfilled/rejected Promise"
|
||||
- Fix pool memory leak when empty array of promises provided
|
||||
|
||||
|
||||
## 1.5.0 - 2021-10-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Call handler when waiting on fulfilled/rejected Promise
|
||||
- Officially support PHP 8.1
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix manually settle promises generated with `Utils::task`
|
||||
|
||||
|
||||
## 1.4.1 - 2021-02-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `each_limit` skipping promises and failing
|
||||
|
||||
|
||||
## 1.4.0 - 2020-09-30
|
||||
|
||||
### Added
|
||||
|
||||
- Support for PHP 8
|
||||
- Optional `$recursive` flag to `all`
|
||||
- Replaced functions by static methods
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix empty `each` processing
|
||||
- Fix promise handling for Iterators of non-unique keys
|
||||
- Fixed `method_exists` crashes on PHP 8
|
||||
- Memory leak on exceptions
|
||||
|
||||
|
||||
## 1.3.1 - 2016-12-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- `wait()` foreign promise compatibility
|
||||
|
||||
|
||||
## 1.3.0 - 2016-11-18
|
||||
|
||||
### Added
|
||||
|
||||
- Adds support for custom task queues.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed coroutine promise memory leak.
|
||||
|
||||
|
||||
## 1.2.0 - 2016-05-18
|
||||
|
||||
### Changed
|
||||
|
||||
- Update to now catch `\Throwable` on PHP 7+
|
||||
|
||||
|
||||
## 1.1.0 - 2016-03-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Update EachPromise to prevent recurring on a iterator when advancing, as this
|
||||
could trigger fatal generator errors.
|
||||
- Update Promise to allow recursive waiting without unwrapping exceptions.
|
||||
|
||||
|
||||
## 1.0.3 - 2015-10-15
|
||||
|
||||
### Changed
|
||||
|
||||
- Update EachPromise to immediately resolve when the underlying promise iterator
|
||||
is empty. Previously, such a promise would throw an exception when its `wait`
|
||||
function was called.
|
||||
|
||||
|
||||
## 1.0.2 - 2015-05-15
|
||||
|
||||
### Changed
|
||||
|
||||
- Conditionally require functions.php.
|
||||
|
||||
|
||||
## 1.0.1 - 2015-06-24
|
||||
|
||||
### Changed
|
||||
|
||||
- Updating EachPromise to call next on the underlying promise iterator as late
|
||||
as possible to ensure that generators that generate new requests based on
|
||||
callbacks are not iterated until after callbacks are invoked.
|
||||
|
||||
|
||||
## 1.0.0 - 2015-05-12
|
||||
|
||||
- Initial release
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Michael Dowling <mtdowling@gmail.com>
|
||||
Copyright (c) 2015 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
Copyright (c) 2017 Tobias Schultze <webmaster@tubo-world.de>
|
||||
Copyright (c) 2020 Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
# Guzzle Promises
|
||||
|
||||
`guzzlehttp/promises` is a small promise library used by Guzzle for asynchronous
|
||||
operations. It implements promise chaining, synchronous waiting, cancellation,
|
||||
and helpers for working with groups of promises.
|
||||
|
||||
Most application developers use this package through
|
||||
[`guzzlehttp/guzzle`](https://github.com/guzzle/guzzle/blob/8.0/README.md) by
|
||||
calling methods such as `requestAsync()`. Install this package directly when you
|
||||
need promise composition without the full HTTP client.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
composer require guzzlehttp/promises
|
||||
```
|
||||
|
||||
## Version Guidance
|
||||
|
||||
| Version | Status | PHP Version |
|
||||
|---------|--------------|--------------|
|
||||
| 3.2 | Latest | >=7.4,<8.7 |
|
||||
| 2.6 | Maintenance | >=7.2.5,<8.7 |
|
||||
| 1.5 | End of Life | >=5.5,<8.3 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
|
||||
$promise->then(
|
||||
function ($value) {
|
||||
echo 'Fulfilled: ' . $value;
|
||||
},
|
||||
function ($reason) {
|
||||
echo 'Rejected: ' . $reason;
|
||||
}
|
||||
);
|
||||
|
||||
$promise->resolve('done');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
You can wait for a promise to complete synchronously:
|
||||
|
||||
```php
|
||||
$value = $promise->wait();
|
||||
```
|
||||
|
||||
A promise's `getState()` describes how it was settled, not the eventual
|
||||
outcome: a promise that was resolved with another promise, directly or by
|
||||
returning one from a `then()` handler, reports `fulfilled` while the inner
|
||||
promise may still be pending, and `wait()` can still throw if the inner
|
||||
promise rejects. Poll the state only on promises settled with plain values,
|
||||
or call `wait()` first (see
|
||||
[guzzle/promises#101](https://github.com/guzzle/promises/issues/101)).
|
||||
|
||||
When using Guzzle HTTP requests, asynchronous methods return
|
||||
`GuzzleHttp\Promise\PromiseInterface` instances:
|
||||
|
||||
```php
|
||||
$promise = $client->requestAsync('GET', 'https://example.com');
|
||||
$response = $promise->wait();
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Promise Quick Start](docs/promise-quick-start.md)
|
||||
- [Promise API](docs/promise-api.md)
|
||||
- [Promise Interoperability](docs/promise-interoperability.md)
|
||||
- [Implementation Notes](docs/implementation-notes.md)
|
||||
- [Upgrade Guide](UPGRADING.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
|
||||
## 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 by the security maintainers listed in the
|
||||
[Security Policy](https://github.com/guzzle/promises/security/policy). Please do
|
||||
not disclose security-related issues publicly until a fix has been announced.
|
||||
|
||||
## License
|
||||
|
||||
Guzzle is made available under the MIT License (MIT). Please see
|
||||
[License File](LICENSE) 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.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
Guzzle Promises Upgrade Guide
|
||||
=============================
|
||||
|
||||
2.x to 3.0
|
||||
----------
|
||||
|
||||
Guzzle Promises 3.0 is a major release that raises the minimum PHP version,
|
||||
updates promise and collection helper signatures, adds generic PHPDoc types for
|
||||
static analyzers, tightens collection helper inputs, improves recursive
|
||||
collection behavior, and clarifies rejection inspection and late rejection
|
||||
callback behavior.
|
||||
|
||||
#### PHP Version and Dependencies
|
||||
|
||||
Guzzle Promises 3.0 requires PHP `^7.4 || ^8.0`. Guzzle Promises 2.x supported
|
||||
PHP `^7.2.5 || ^8.0`.
|
||||
|
||||
If your application still supports PHP 7.2 or 7.3, continue using Guzzle
|
||||
Promises 2.x until your minimum PHP version is raised.
|
||||
|
||||
Guzzle Promises 3.0 has no runtime package dependencies beyond PHP. It removes
|
||||
the 2.x runtime dependency on `symfony/deprecation-contracts`; require that
|
||||
package directly if your application uses it.
|
||||
|
||||
#### Optional Promise Resolution Values
|
||||
|
||||
`PromiseInterface::resolve()` now accepts an optional value. Calling `resolve()`
|
||||
without an argument fulfills the promise with `null`.
|
||||
|
||||
Custom implementations of `PromiseInterface`, and subclasses that override
|
||||
`resolve()` on `Promise`, `FulfilledPromise`, or `RejectedPromise`, must update
|
||||
their method signature from `resolve($value): void` to
|
||||
`resolve($value = null): void`.
|
||||
|
||||
#### Generic PHPDoc Types
|
||||
|
||||
`PromiseInterface`, `PromisorInterface`, and the built-in promise classes now
|
||||
include generic PHPDoc annotations for static analysis tools. The first template
|
||||
type represents the fulfillment value and the second represents the rejection
|
||||
reason. This is a static-analysis-only change and does not alter runtime
|
||||
behavior, but projects with stricter static analysis may see new or different
|
||||
diagnostics:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
|
||||
/** @var PromiseInterface<string, \Throwable> */
|
||||
$promise = $factory->createPromise();
|
||||
|
||||
$value = $promise->wait();
|
||||
```
|
||||
|
||||
Code that uses unparameterized promise types continues to work and is treated as
|
||||
`PromiseInterface<mixed, mixed>`. If your project implements promise interfaces,
|
||||
extends promise classes, or has stricter static analysis, you may need to update
|
||||
your PHPDoc annotations to include the generic value and reason types. The
|
||||
expanded PHPDoc also preserves promise-chain fulfillment and rejection types
|
||||
more precisely through `then()` and `otherwise()`, and documents collection
|
||||
callbacks with value or reason, key, and aggregate-promise arguments so
|
||||
callbacks may declare only the arguments they use.
|
||||
|
||||
#### Collection Helper Inputs
|
||||
|
||||
Promise collection helpers now require iterable inputs. Passing a single promise
|
||||
or scalar value directly now throws a `TypeError`.
|
||||
|
||||
Wrap single promises or values in an array before passing them to
|
||||
`Create::iterFor()`, `Each::of()`, `Each::ofLimit()`, `Each::ofLimitAll()`,
|
||||
`EachPromise`, or the `Utils` collection helpers.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Each;
|
||||
|
||||
// 2.x
|
||||
$promise = Each::ofLimit($singlePromise, 2);
|
||||
|
||||
// 3.0
|
||||
$promise = Each::ofLimit([$singlePromise], 2);
|
||||
```
|
||||
|
||||
`IteratorAggregate` inputs are now iterated via `getIterator()`. In 2.x an
|
||||
aggregate was treated as a single value and produced one result; in 3.0 its
|
||||
entries are consumed individually.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$aggregate = new \ArrayObject([$promiseA, $promiseB]);
|
||||
|
||||
// 2.x: one result — the ArrayObject itself
|
||||
// 3.0: two results — the fulfillment values of $promiseA and $promiseB
|
||||
$promise = Utils::all($aggregate);
|
||||
```
|
||||
|
||||
#### Collection Helper Signatures
|
||||
|
||||
`Utils::all()`, `Utils::settle()`, and `Each::of()` now accept trailing optional
|
||||
arguments. Direct calls using the 2.x argument lists continue to work, and the
|
||||
affected helper classes are final so subclass signatures do not need to change.
|
||||
Code that mirrors or reflects exact helper signatures may need to be updated.
|
||||
|
||||
Pass the recursive flag before the config array when using `Utils::all()` or
|
||||
`Utils::settle()`:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::all($promises, false, ['concurrency' => 5]);
|
||||
$promise = Utils::settle($promises, false, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
Only `concurrency` is honored by these helper config arrays. Callback config
|
||||
keys such as `fulfilled` and `rejected` are ignored; pass callbacks to
|
||||
`Each::of()` directly or use `EachPromise`.
|
||||
|
||||
#### Recursive Collection Helpers
|
||||
|
||||
Existing `Utils::all($promises, true)` calls may return different results in
|
||||
3.0. Recursive mode now detects dynamically-added settled promises and raw
|
||||
values. In 2.x, recursive mode only checked for pending promises.
|
||||
|
||||
If you previously worked around the lack of recursive `Utils::settle()` support,
|
||||
you can replace that workaround with the new `$recursive` argument:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::settle($promises, true);
|
||||
```
|
||||
|
||||
When `$recursive` is true, collection helpers continue taking passes over the
|
||||
collection until no new entries are found and no visible promises remain
|
||||
pending. This is intended for rewindable mutable collections such as
|
||||
`ArrayIterator`. Generators are safe to pass, but they cannot be traversed
|
||||
again once consumed, so recursive mode degrades to a single pass; use a
|
||||
rewindable mutable collection when recursion needs to observe added values.
|
||||
|
||||
#### Promise Inspection
|
||||
|
||||
`Utils::inspect()` and `Utils::inspectAll()` now return the actual rejection
|
||||
reason delivered to rejection callbacks. They no longer unwrap
|
||||
`RejectionException` instances to their inner reason.
|
||||
|
||||
For example, a promise rejected with a `RejectionException` now inspects with
|
||||
that exception as the reason:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\RejectionException;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$reason = new RejectionException('reason');
|
||||
$result = Utils::inspect(new RejectedPromise($reason));
|
||||
|
||||
assert($result['reason'] === $reason);
|
||||
```
|
||||
|
||||
Cancelled promises now inspect with a `CancellationException` reason. If you
|
||||
need the string reason from a `RejectionException` or subclass, call
|
||||
`getReason()` on the exception.
|
||||
|
||||
`Utils::inspect()` still reports wait-function failures as rejection reasons
|
||||
when the wait function does not settle the promise. If the wait function
|
||||
settles the promise and then throws, `inspect()` reports the settled
|
||||
fulfillment or rejection state; direct `Promise::wait()` calls continue to
|
||||
throw that late exception.
|
||||
|
||||
#### Late Rejection Callbacks
|
||||
|
||||
Rejection callbacks registered after a promise was resolved with a rejected
|
||||
promise are now invoked with the nested rejection reason.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->resolve(new RejectedPromise('reason'));
|
||||
|
||||
$promise->then(null, function ($reason): void {
|
||||
assert($reason === 'reason');
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
#### Non-instantiable Helper Classes
|
||||
|
||||
Static helper classes such as `Create`, `Each`, `Is`, and `Utils` now have
|
||||
private constructors. Replace any accidental instantiation with static method
|
||||
calls.
|
||||
|
||||
#### Native PHP Serialization of Runtime Objects
|
||||
|
||||
`Promise`, `TaskQueue`, `EachPromise`, and `Coroutine` no longer support native
|
||||
PHP `serialize()` or `unserialize()`. Persist application values instead of
|
||||
promise runtime state.
|
||||
|
||||
1.x to 2.0
|
||||
----------
|
||||
|
||||
Guzzle Promises 2.0 is a major release that removes deprecated APIs, raises the
|
||||
minimum PHP version, and adds PHP 7 parameter and return types. Applications that
|
||||
only use the object-oriented API should usually need small changes. Applications
|
||||
that call helper functions, implement package interfaces, extend package classes,
|
||||
or pass invalid argument types need closer review.
|
||||
|
||||
#### PHP Version and Dependencies
|
||||
|
||||
Guzzle Promises 2.0 requires PHP `^7.2.5 || ^8.0`. Guzzle Promises 1.x
|
||||
supported PHP `>=5.5`.
|
||||
|
||||
#### PHP 7 Type Hints and Return Types
|
||||
|
||||
Type hints and return types were added wherever possible. Please make sure:
|
||||
|
||||
- You pass values of the documented type when calling methods and functions.
|
||||
- Classes that implement `PromiseInterface`, `PromisorInterface`, or
|
||||
`TaskQueueInterface` update method signatures to remain compatible.
|
||||
- Classes that extend Guzzle Promises classes update any overridden method
|
||||
signatures to remain compatible.
|
||||
- Code that expected package-specific exceptions for invalid argument types may
|
||||
now receive PHP `TypeError` exceptions instead.
|
||||
|
||||
#### Soft-Final Classes
|
||||
|
||||
All previously non-final non-exception classes are now final or annotated with
|
||||
`@final`. If your code extends one of these classes, replace inheritance with
|
||||
composition or implement the relevant interface directly.
|
||||
|
||||
#### Removed Function API
|
||||
|
||||
The static API was introduced in 1.4.0 to mitigate problems with functions
|
||||
conflicting between global and local copies of the package. The function API was
|
||||
removed in 2.0.0, along with the Composer `files` autoload entry that loaded
|
||||
`src/functions_include.php`.
|
||||
|
||||
Replace namespaced function calls with the corresponding static methods in the
|
||||
`GuzzleHttp\Promise` namespace:
|
||||
|
||||
```php
|
||||
// Before:
|
||||
use function GuzzleHttp\Promise\promise_for;
|
||||
|
||||
$promise = promise_for('value');
|
||||
|
||||
// After:
|
||||
use GuzzleHttp\Promise\Create;
|
||||
|
||||
$promise = Create::promiseFor('value');
|
||||
```
|
||||
|
||||
| Original Function | Replacement Method |
|
||||
|-------------------|--------------------|
|
||||
| `queue` | `Utils::queue` |
|
||||
| `task` | `Utils::task` |
|
||||
| `promise_for` | `Create::promiseFor` |
|
||||
| `rejection_for` | `Create::rejectionFor` |
|
||||
| `exception_for` | `Create::exceptionFor` |
|
||||
| `iter_for` | `Create::iterFor` |
|
||||
| `inspect` | `Utils::inspect` |
|
||||
| `inspect_all` | `Utils::inspectAll` |
|
||||
| `unwrap` | `Utils::unwrap` |
|
||||
| `all` | `Utils::all` |
|
||||
| `some` | `Utils::some` |
|
||||
| `any` | `Utils::any` |
|
||||
| `settle` | `Utils::settle` |
|
||||
| `each` | `Each::of` |
|
||||
| `each_limit` | `Each::ofLimit` |
|
||||
| `each_limit_all` | `Each::ofLimitAll` |
|
||||
| `!is_fulfilled` | `Is::pending` |
|
||||
| `is_fulfilled` | `Is::fulfilled` |
|
||||
| `is_rejected` | `Is::rejected` |
|
||||
| `is_settled` | `Is::settled` |
|
||||
| `coroutine` | `Coroutine::of` |
|
||||
|
||||
For the full 2.0 diff, see
|
||||
https://github.com/guzzle/promises/compare/1.5.3...2.0.0.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "guzzlehttp/promises",
|
||||
"description": "Guzzle promises library",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"promise"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
},
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Nyholm",
|
||||
"email": "tobias.nyholm@gmail.com",
|
||||
"homepage": "https://github.com/Nyholm"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Schultze",
|
||||
"email": "webmaster@tubo-world.de",
|
||||
"homepage": "https://github.com/Tobion"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.4 || ^8.0",
|
||||
"symfony/deprecation-contracts": "^2.5 || ^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"phpunit/phpunit": "^9.6.34"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"bamarni/composer-bin-plugin": true
|
||||
},
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# Implementation Notes
|
||||
|
||||
This document describes implementation details that explain observable behavior
|
||||
in `guzzlehttp/promises`, especially queue-based callback execution, iterative
|
||||
resolution, and why `Promise` also acts as the deferred value. Application code
|
||||
usually only needs the [Promise Quick Start](promise-quick-start.md) and
|
||||
[Promise API](promise-api.md).
|
||||
|
||||
## Iterative Resolution and Chaining
|
||||
|
||||
Promises are resolved iteratively by moving pending handlers between promises.
|
||||
This keeps stack size constant even for very long `then()` chains.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$parent = new Promise();
|
||||
$p = $parent;
|
||||
|
||||
for ($i = 0; $i < 1000; $i++) {
|
||||
$p = $p->then(function ($v) {
|
||||
// The stack size remains constant.
|
||||
echo xdebug_get_stack_depth() . ', ';
|
||||
return $v + 1;
|
||||
});
|
||||
}
|
||||
|
||||
$parent->resolve(0);
|
||||
var_dump($p->wait()); // int(1000)
|
||||
|
||||
```
|
||||
|
||||
When a promise is fulfilled or rejected with a non-promise value, the promise
|
||||
takes ownership of each child promise's handlers and delivers values down the
|
||||
chain without recursion.
|
||||
|
||||
When a promise is resolved with another promise, the original promise transfers
|
||||
all of its pending handlers to the new promise. When the new promise is
|
||||
eventually resolved, all pending handlers receive the forwarded
|
||||
value.
|
||||
|
||||
## A Promise Is the Deferred
|
||||
|
||||
Some promise libraries implement promises using a deferred object to represent
|
||||
a computation and a promise object to represent the delivery of the result of
|
||||
the computation. That separation prevents consumers from modifying the value
|
||||
that will eventually be delivered.
|
||||
|
||||
Iterative resolution requires one promise to move handlers from another promise.
|
||||
To do that without making handlers publicly mutable, `Promise` is also the
|
||||
deferred value. Promises of the same class can modify each other's private
|
||||
state, including handler ownership. This means a consumer that receives a
|
||||
`Promise` can also resolve or reject it, but it keeps chaining efficient and
|
||||
stack safe.
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->then(function ($value) { echo $value; });
|
||||
// The promise is the deferred value, so you can deliver a value to it.
|
||||
$promise->resolve('foo');
|
||||
GuzzleHttp\Promise\Utils::queue()->run();
|
||||
// Prints "foo"
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise API](promise-api.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# Promise API
|
||||
|
||||
This reference summarizes the public API provided by `guzzlehttp/promises`.
|
||||
Promise APIs are documented for static analysis as
|
||||
`PromiseInterface<TValue, TReason>`. `TValue` is the fulfillment value type and
|
||||
`TReason` is the rejection reason type. This typing is PHPDoc-only and does not
|
||||
change runtime behavior.
|
||||
|
||||
Callbacks registered with `then()` are queued. They are invoked when the global
|
||||
task queue runs, when a returned promise is waited on, or when the queue is
|
||||
drained by the default shutdown handler.
|
||||
|
||||
## PromiseInterface and Promise
|
||||
|
||||
`PromiseInterface` defines the common promise contract and the states
|
||||
`pending`, `fulfilled`, and `rejected`.
|
||||
|
||||
When creating a `Promise`, you can provide an optional `$waitFn` and
|
||||
`$cancelFn`. `$waitFn` receives a boolean argument and is expected to resolve or
|
||||
reject the promise. `$cancelFn` receives no arguments and is invoked when
|
||||
`cancel()` is called.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(
|
||||
function (bool $recursive) use (&$promise) {
|
||||
$promise->resolve('waited');
|
||||
},
|
||||
function () {
|
||||
// Cancel the underlying operation, such as closing a socket.
|
||||
}
|
||||
);
|
||||
|
||||
assert('waited' === $promise->wait());
|
||||
```
|
||||
|
||||
A promise has the following methods:
|
||||
|
||||
- `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` appends fulfillment and rejection handlers and returns a new promise resolving to the return value of the called handler. If a handler is omitted, the original fulfillment value or rejection reason is forwarded.
|
||||
- `otherwise(callable $onRejected) : PromiseInterface` appends a rejection handler and returns a new promise resolving to the callback result if called, or to the original fulfillment value if the promise is fulfilled.
|
||||
- `wait(bool $unwrap = true) : mixed` synchronously waits on the promise. When `$unwrap` is `true`, fulfilled values are returned and rejected reasons are thrown. When `$unwrap` is `false`, the promise is settled without returning or throwing its result.
|
||||
- `cancel() : void` attempts to cancel the promise and dependent promises.
|
||||
- `getState() : string` returns `pending`, `fulfilled`, or `rejected`.
|
||||
- `resolve($value = null) : void` fulfills the promise with `$value`, or with `null` if no value is given.
|
||||
- `reject($reason) : void` rejects the promise with `$reason`.
|
||||
|
||||
## Settled Promises
|
||||
|
||||
`FulfilledPromise` represents an already fulfilled promise. Fulfillment
|
||||
callbacks are still queued and run when the task queue runs or the returned
|
||||
promise is waited on.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new FulfilledPromise('value');
|
||||
$promise->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
`RejectedPromise` represents an already rejected promise. Rejection callbacks
|
||||
are also queued and run when the queue is drained or the returned promise is
|
||||
waited on.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new RejectedPromise('Error');
|
||||
$promise->then(null, function ($reason) {
|
||||
echo $reason;
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
## Utils
|
||||
|
||||
`GuzzleHttp\Promise\Utils` provides helpers for inspecting, aggregating, and
|
||||
queuing promise work.
|
||||
|
||||
- `Utils::queue(?TaskQueueInterface $assign = null) : TaskQueueInterface` returns the global task queue, or assigns a replacement queue when `$assign` is provided.
|
||||
- `Utils::task(callable $task) : PromiseInterface` adds a task to the global queue and returns a promise that is fulfilled or rejected with the task result.
|
||||
- `Utils::inspect(PromiseInterface $promise) : array` waits for one promise to settle and returns an inspection array with `state` and either `value` or `reason`.
|
||||
- `Utils::inspectAll(iterable $promises) : array` inspects each promise and returns inspection arrays keyed like the input iterable.
|
||||
- `Utils::unwrap(iterable $promises) : array` waits on all promises and returns fulfilled values, throwing if any promise rejects.
|
||||
- `Utils::all(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with all values, or rejected when any input rejects.
|
||||
- `Utils::settle(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with inspection arrays after all inputs settle.
|
||||
- `Utils::some(int $count, iterable $promises) : PromiseInterface` fulfills with the values of the first `$count` promises to fulfill, in the order they appear in the input, or rejects with `AggregateException` if too few fulfill.
|
||||
- `Utils::any(iterable $promises) : PromiseInterface` fulfills with the first fulfilled value, or rejects with `AggregateException` if none fulfill.
|
||||
|
||||
`Utils::all()` and `Utils::settle()` accept `['concurrency' => 5]` or
|
||||
`['concurrency' => callable]` for lazy iterables. This limits how many items are
|
||||
pulled from the iterable at one time; it does not throttle promises that have
|
||||
already been created or started.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::all($promises, false, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
## Create
|
||||
|
||||
`GuzzleHttp\Promise\Create` provides factories used by the promise
|
||||
implementation and by callers that need to normalize values.
|
||||
|
||||
- `Create::promiseFor($value) : PromiseInterface` returns `$value` when it is already a Guzzle promise, wraps foreign thenables in a Guzzle promise, or returns a fulfilled promise for plain values.
|
||||
- `Create::rejectionFor($reason) : PromiseInterface` returns `$reason` when it is already a promise, or returns a rejected promise for plain reasons.
|
||||
- `Create::exceptionFor($reason) : Throwable` returns throwable reasons as-is, or wraps non-throwable reasons in `RejectionException`.
|
||||
- `Create::iterFor(iterable $value) : Iterator` returns an iterator for arrays, iterators, iterator aggregates, and traversables.
|
||||
|
||||
## State
|
||||
|
||||
`GuzzleHttp\Promise\State` provides readable state checks:
|
||||
|
||||
- `State::isPending(PromiseInterface $promise) : bool`
|
||||
- `State::isSettled(PromiseInterface $promise) : bool`
|
||||
- `State::isFulfilled(PromiseInterface $promise) : bool`
|
||||
- `State::isRejected(PromiseInterface $promise) : bool`
|
||||
|
||||
`GuzzleHttp\Promise\Is` is deprecated because PHP 8.6 deprecates `is` as a class
|
||||
name, and will be removed in Guzzle Promises 4.0. Replace `Is::pending()`,
|
||||
`Is::settled()`, `Is::fulfilled()`, and `Is::rejected()` with the matching
|
||||
`State` methods.
|
||||
|
||||
## Each and EachPromise
|
||||
|
||||
`Each::of()` consumes an iterable of promises or values and invokes callbacks as
|
||||
items settle. Fulfillment callbacks receive the fulfilled value, iterable key,
|
||||
and aggregate promise. Rejection callbacks receive the rejection reason,
|
||||
iterable key, and aggregate promise. Callback return values are ignored.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Each;
|
||||
|
||||
$promise = Each::of($promises, $onFulfilled, $onRejected, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
- `Each::of(iterable $iterable, ?callable $onFulfilled = null, ?callable $onRejected = null, array $config = []) : PromiseInterface` consumes the iterable and optionally limits lazy iteration with `concurrency`.
|
||||
- `Each::ofLimit(iterable $iterable, $concurrency, ?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` is a convenience wrapper for `Each::of()` with a concurrency limit.
|
||||
- `Each::ofLimitAll(iterable $iterable, $concurrency, ?callable $onFulfilled = null) : PromiseInterface` is like `ofLimit()`, but rejects the aggregate promise on the first rejection.
|
||||
- `EachPromise` is the configurable class behind `Each`; use it directly when you need `fulfilled`, `rejected`, and `concurrency` keys in one configuration array.
|
||||
|
||||
The concurrency options limit lazy promise creation. For HTTP request
|
||||
concurrency, use `GuzzleHttp\Pool` from `guzzlehttp/guzzle`.
|
||||
|
||||
## Coroutine
|
||||
|
||||
`Coroutine::of(callable $generatorFn) : Coroutine` creates a promise resolved by
|
||||
a generator that yields values or promises. The generator resumes with each
|
||||
fulfilled value, and rejections are thrown into the generator.
|
||||
|
||||
## Task Queue
|
||||
|
||||
`TaskQueueInterface` exposes `isEmpty()`, `add(callable $task)`, and `run()`.
|
||||
`TaskQueue` executes queued tasks in FIFO order. The default queue runs at
|
||||
process shutdown unless disabled, and `wait()` drains the queue while resolving
|
||||
the promise being waited on.
|
||||
|
||||
## Exceptions
|
||||
|
||||
- `RejectionException` is thrown by `wait()` when a rejected promise has a non-throwable reason. The original reason is available through `getReason()`.
|
||||
- `AggregateException` extends `RejectionException` and is used by `Utils::some()` and `Utils::any()` when too few promises fulfill.
|
||||
- `CancellationException` extends `RejectionException` and is used as the rejection reason for cancelled promises.
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
- [Upgrade Guide](../UPGRADING.md)
|
||||
@@ -0,0 +1,78 @@
|
||||
# Promise Interoperability
|
||||
|
||||
This guide explains how Guzzle promises interact with foreign promise
|
||||
implementations. A foreign promise is any object with a `then` method, such as a
|
||||
[React promise](https://github.com/reactphp/promise). When a foreign promise is
|
||||
returned from a `then` callback, Guzzle forwards resolution to that promise.
|
||||
|
||||
## Foreign Promises
|
||||
|
||||
Capture the promise returned from `then()`. That chained promise is the Guzzle
|
||||
promise that follows the foreign promise's eventual result.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$deferred = new React\Promise\Deferred();
|
||||
$reactPromise = $deferred->promise();
|
||||
|
||||
$guzzlePromise = new Promise();
|
||||
$chained = $guzzlePromise->then(function ($value) use ($reactPromise) {
|
||||
// Use the Guzzle value, then continue with the React promise.
|
||||
return $reactPromise;
|
||||
});
|
||||
|
||||
$chained->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$guzzlePromise->resolve('start');
|
||||
Utils::queue()->run();
|
||||
|
||||
$deferred->resolve('done');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
Forwarding a foreign promise does not make Guzzle able to synchronously wait on
|
||||
or cancel the foreign operation. The chained Guzzle promise settles only after
|
||||
the foreign implementation invokes the callbacks registered through `then()`.
|
||||
If the foreign promise has no compatible `wait()` or `cancel()` behavior, Guzzle
|
||||
cannot invent that behavior.
|
||||
|
||||
Use `Create::promiseFor($foreignPromise)` to shadow a foreign thenable as a
|
||||
Guzzle promise. If the foreign object exposes `wait()` or `cancel()` methods,
|
||||
the wrapper uses them. Otherwise, use the foreign implementation's event loop or
|
||||
completion mechanism and drain Guzzle's task queue when callbacks need to run.
|
||||
|
||||
## Event Loop Integration
|
||||
|
||||
Guzzle promises use a task queue to keep stack size constant and to run promise
|
||||
callbacks asynchronously. When waiting on promises synchronously, the task queue
|
||||
is automatically run while resolving the blocking promise and forwarded Guzzle
|
||||
promises.
|
||||
|
||||
When using promises asynchronously in an event loop, run the task queue on loop
|
||||
ticks. If you do not run the task queue, Guzzle promise callbacks may remain
|
||||
queued.
|
||||
|
||||
```php
|
||||
$queue = GuzzleHttp\Promise\Utils::queue();
|
||||
$queue->run();
|
||||
```
|
||||
|
||||
For example, you could use Guzzle promises with React using a short periodic
|
||||
timer. Avoid zero-interval timers because they may keep the loop busy even when
|
||||
there is no promise work to run.
|
||||
|
||||
```php
|
||||
$queue = GuzzleHttp\Promise\Utils::queue();
|
||||
$loop = React\EventLoop\Factory::create();
|
||||
$loop->addPeriodicTimer(0.01, [$queue, 'run']);
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise API](promise-api.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
@@ -0,0 +1,319 @@
|
||||
# Promise Quick Start
|
||||
|
||||
This guide covers the common promise operations needed when using
|
||||
`guzzlehttp/promises` directly: registering callbacks, resolving or rejecting
|
||||
promises, waiting synchronously, composing chains, and using generator-based
|
||||
flows. For the full public surface, see the [Promise API](promise-api.md).
|
||||
|
||||
A *promise* represents the eventual result of an asynchronous operation. The
|
||||
primary way of interacting with a promise is through its `then` method, which
|
||||
registers callbacks to receive either the eventual value or the reason why the
|
||||
promise cannot be fulfilled.
|
||||
|
||||
Guzzle promise callbacks are queued. They run when the task queue is drained,
|
||||
for example by `Utils::queue()->run()`, by waiting on a returned promise, or by
|
||||
the default shutdown handler at the end of the PHP process. Examples that show
|
||||
callback output drain the queue explicitly.
|
||||
|
||||
## Callbacks
|
||||
|
||||
Callbacks are registered with the `then` method by providing an optional
|
||||
`$onFulfilled` followed by an optional `$onRejected` function.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(
|
||||
// $onFulfilled
|
||||
function ($value) {
|
||||
echo 'The promise was fulfilled.';
|
||||
},
|
||||
// $onRejected
|
||||
function ($reason) {
|
||||
echo 'The promise was rejected.';
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
*Resolving* a promise means that you either fulfill a promise with a *value* or
|
||||
reject a promise with a *reason*. Callbacks registered with `then` are invoked
|
||||
only once and in the order in which they were added when the queue is drained.
|
||||
|
||||
## Resolving a Promise
|
||||
|
||||
Promises are fulfilled using the `resolve($value = null)` method. Calling
|
||||
`resolve()` without an argument fulfills the promise with `null`. Resolving a
|
||||
promise with any value other than a `GuzzleHttp\Promise\RejectedPromise` queues
|
||||
the `$onFulfilled` callbacks. Resolving with a rejected promise rejects the
|
||||
promise and queues the `$onRejected` callbacks.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise
|
||||
->then(function ($value) {
|
||||
return 'Hello, ' . $value;
|
||||
})
|
||||
->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$promise->resolve('reader.');
|
||||
Utils::queue()->run();
|
||||
// Outputs "Hello, reader."
|
||||
```
|
||||
|
||||
## Promise Forwarding
|
||||
|
||||
Promises can be chained one after the other. Each `then` call returns a new
|
||||
promise. The return value of a callback is forwarded to the next promise in the
|
||||
chain. Returning a promise from a callback makes the next promise wait for that
|
||||
returned promise to settle.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$nextPromise = new Promise();
|
||||
|
||||
$promise
|
||||
->then(function ($value) use ($nextPromise) {
|
||||
echo $value;
|
||||
|
||||
return $nextPromise;
|
||||
})
|
||||
->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$promise->resolve('A');
|
||||
Utils::queue()->run();
|
||||
// Outputs "A"
|
||||
|
||||
$nextPromise->resolve('B');
|
||||
Utils::queue()->run();
|
||||
// Outputs "B"
|
||||
```
|
||||
|
||||
## Promise Rejection
|
||||
|
||||
When a promise is rejected, the `$onRejected` callbacks are invoked with the
|
||||
rejection reason when the queue is drained.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
echo $reason;
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
// Outputs "Error!"
|
||||
```
|
||||
|
||||
## Rejection Forwarding
|
||||
|
||||
If an exception is thrown in an `$onRejected` callback, subsequent
|
||||
`$onRejected` callbacks receive the thrown exception as the reason.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
throw new Exception($reason);
|
||||
})->then(null, function ($reason) {
|
||||
assert($reason->getMessage() === 'Error!');
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
You can also forward a rejection down the promise chain by returning a
|
||||
`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or
|
||||
`$onRejected` callback.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
return new RejectedPromise($reason);
|
||||
})->then(null, function ($reason) {
|
||||
assert($reason === 'Error!');
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
If an exception is not thrown in an `$onRejected` callback and the callback
|
||||
does not return a rejected promise, downstream `$onFulfilled` callbacks are
|
||||
invoked using the value returned from the `$onRejected` callback.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise
|
||||
->then(null, function ($reason) {
|
||||
return "It's ok";
|
||||
})
|
||||
->then(function ($value) {
|
||||
assert($value === "It's ok");
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
## Synchronous Wait
|
||||
|
||||
You can synchronously force promises to complete using a promise's `wait`
|
||||
method. When creating a promise, you can provide a wait function that is used
|
||||
to synchronously complete the promise. The wait function receives a boolean
|
||||
argument and is expected to resolve or reject the promise. If the wait function
|
||||
does not settle the promise, an exception is thrown.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(function (bool $recursive) use (&$promise) {
|
||||
$promise->resolve('foo');
|
||||
});
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "foo"
|
||||
```
|
||||
|
||||
If a throwable is encountered while invoking the wait function of a promise,
|
||||
the promise is rejected with the throwable and the throwable is thrown.
|
||||
|
||||
```php
|
||||
$promise = new Promise(function (bool $recursive) use (&$promise) {
|
||||
throw new Exception('foo');
|
||||
});
|
||||
|
||||
$promise->wait(); // Throws the exception.
|
||||
```
|
||||
|
||||
Calling `wait` on a promise that has been fulfilled will not trigger the wait
|
||||
function. It will simply return the previously resolved value.
|
||||
|
||||
```php
|
||||
$promise = new Promise(function (bool $recursive) { die('this is not called!'); });
|
||||
$promise->resolve('foo');
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "foo"
|
||||
```
|
||||
|
||||
Calling `wait` on a promise that has been rejected will throw. If the rejection
|
||||
reason is an instance of `\Throwable`, the reason is thrown. Otherwise, a
|
||||
`GuzzleHttp\Promise\RejectionException` is thrown and the reason can be
|
||||
obtained by calling `getReason()` on the exception.
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->reject('foo');
|
||||
$promise->wait();
|
||||
```
|
||||
|
||||
> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with reason: foo'
|
||||
|
||||
## Unwrapping a Promise
|
||||
|
||||
When synchronously waiting on a promise, you are joining the state of the
|
||||
promise into the current execution: the fulfilled value is returned, or the
|
||||
rejection reason is thrown. This is called "unwrapping" the promise. Waiting on
|
||||
a promise unwraps by default.
|
||||
|
||||
You can force a promise to resolve and *not* unwrap its state by passing
|
||||
`false` to `wait()`:
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->reject('foo');
|
||||
|
||||
// This does not throw. It only ensures the promise has been resolved.
|
||||
$promise->wait(false);
|
||||
```
|
||||
|
||||
When unwrapping a promise, the resolved value of the promise will be waited on
|
||||
until the unwrapped value is not a promise. This means that if promise A is
|
||||
resolved with promise B, unwrapping promise A returns the value delivered to
|
||||
promise B.
|
||||
|
||||
When you do not unwrap the promise, no value is returned.
|
||||
|
||||
## Inspecting a Promise
|
||||
|
||||
`Utils::inspect($promise)` waits for a promise to settle and returns an array
|
||||
describing its final state. For rejected promises, the `reason` entry is the
|
||||
actual rejection reason delivered to rejection callbacks.
|
||||
|
||||
This means `RejectionException` and subclasses are not unwrapped by
|
||||
`inspect()`. For example, cancelled promises inspect with a
|
||||
`CancellationException` reason.
|
||||
|
||||
## Generator-Based Async
|
||||
|
||||
`Coroutine::of()` creates a promise from a generator that yields values or
|
||||
promises. The generator resumes each time the yielded value settles, which can
|
||||
make sequential asynchronous flows easier to read.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Coroutine;
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
|
||||
$promise = Coroutine::of(function () {
|
||||
$first = yield new FulfilledPromise('A');
|
||||
$second = yield new FulfilledPromise($first . 'B');
|
||||
|
||||
yield $second . 'C';
|
||||
});
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "ABC"
|
||||
```
|
||||
|
||||
If a yielded promise rejects, the rejection is thrown into the generator. Catch
|
||||
it inside the generator to recover, or let it reject the coroutine promise.
|
||||
|
||||
## Cancellation
|
||||
|
||||
You can cancel a promise that has not yet been fulfilled using `cancel()`. When
|
||||
creating a promise, you can provide an optional cancel function that cancels the
|
||||
underlying operation, such as closing a socket or aborting a query.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(null, function () {
|
||||
// Cancel the underlying operation.
|
||||
});
|
||||
|
||||
$promise->cancel();
|
||||
```
|
||||
|
||||
Cancellation rejects the promise with a `CancellationException` unless the
|
||||
cancel function settles the promise first.
|
||||
|
||||
## Related
|
||||
|
||||
- [Promise API](promise-api.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
- [Upgrade Guide](../UPGRADING.md)
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
* Exception thrown when too many errors occur in the some() or any() methods.
|
||||
*/
|
||||
class AggregateException extends RejectionException
|
||||
{
|
||||
public function __construct(string $msg, array $reasons)
|
||||
{
|
||||
parent::__construct(
|
||||
$reasons,
|
||||
sprintf('%s; %d rejected promises', $msg, count($reasons))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
* Exception that is set as the reason for a promise that has been cancelled.
|
||||
*/
|
||||
class CancellationException extends RejectionException
|
||||
{
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
use Generator;
|
||||
|
||||
/**
|
||||
* Creates a promise that is resolved using a generator that yields values or
|
||||
* promises (somewhat similar to C#'s async keyword).
|
||||
*
|
||||
* When called, the Coroutine::of method will start an instance of the generator
|
||||
* and returns a promise that is fulfilled with its final yielded value.
|
||||
*
|
||||
* Control is returned back to the generator when the yielded promise settles.
|
||||
* This can lead to less verbose code when doing lots of sequential async calls
|
||||
* with minimal processing in between.
|
||||
*
|
||||
* use GuzzleHttp\Promise;
|
||||
*
|
||||
* function createPromise($value) {
|
||||
* return new Promise\FulfilledPromise($value);
|
||||
* }
|
||||
*
|
||||
* $promise = Promise\Coroutine::of(function () {
|
||||
* $value = (yield createPromise('a'));
|
||||
* try {
|
||||
* $value = (yield createPromise($value . 'b'));
|
||||
* } catch (\Throwable $e) {
|
||||
* // The promise was rejected.
|
||||
* }
|
||||
* yield $value . 'c';
|
||||
* });
|
||||
*
|
||||
* // Outputs "abc"
|
||||
* $promise->then(function ($v) { echo $v; });
|
||||
*
|
||||
* @template TValue = mixed
|
||||
* @template TReason = mixed
|
||||
*
|
||||
* @implements PromiseInterface<TValue, TReason>
|
||||
*
|
||||
* @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
|
||||
*/
|
||||
final class Coroutine implements PromiseInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/**
|
||||
* @var PromiseInterface<mixed, mixed>|null
|
||||
*/
|
||||
private ?PromiseInterface $currentPromise = null;
|
||||
|
||||
/**
|
||||
* @var Generator<mixed, mixed, mixed, mixed>
|
||||
*/
|
||||
private Generator $generator;
|
||||
|
||||
/**
|
||||
* @var Promise<TValue, TReason>
|
||||
*/
|
||||
private PromiseInterface $result;
|
||||
|
||||
/**
|
||||
* @param callable(): Generator<mixed, mixed, mixed, mixed> $generatorFn
|
||||
*/
|
||||
public function __construct(callable $generatorFn)
|
||||
{
|
||||
$this->generator = $generatorFn();
|
||||
$this->result = new Promise(function (): void {
|
||||
while (isset($this->currentPromise)) {
|
||||
$this->currentPromise->wait();
|
||||
}
|
||||
}, function (): void {
|
||||
if (isset($this->currentPromise)) {
|
||||
$this->currentPromise->cancel();
|
||||
}
|
||||
});
|
||||
try {
|
||||
$this->nextCoroutine($this->generator->current());
|
||||
} catch (\Throwable $throwable) {
|
||||
$this->result->reject($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new coroutine.
|
||||
*
|
||||
* @param callable(): Generator<mixed, mixed, mixed, mixed> $generatorFn
|
||||
*
|
||||
* @return self<mixed, mixed>
|
||||
*/
|
||||
public static function of(callable $generatorFn): self
|
||||
{
|
||||
return new self($generatorFn);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TFulfilledValue = never
|
||||
* @template TFulfilledReason = never
|
||||
* @template TRejectedValue = never
|
||||
* @template TRejectedReason = never
|
||||
*
|
||||
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
|
||||
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
|
||||
*
|
||||
* @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)>
|
||||
*/
|
||||
public function then(
|
||||
?callable $onFulfilled = null,
|
||||
?callable $onRejected = null
|
||||
): PromiseInterface {
|
||||
return $this->result->then($onFulfilled, $onRejected);
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TRejectedValue = never
|
||||
* @template TRejectedReason = never
|
||||
*
|
||||
* @param callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>) $onRejected Invoked when the promise is rejected.
|
||||
*
|
||||
* @return PromiseInterface<TValue|TRejectedValue, TRejectedReason|\Throwable>
|
||||
*/
|
||||
public function otherwise(callable $onRejected): PromiseInterface
|
||||
{
|
||||
return $this->result->otherwise($onRejected);
|
||||
}
|
||||
|
||||
public function wait(bool $unwrap = true)
|
||||
{
|
||||
return $this->result->wait($unwrap);
|
||||
}
|
||||
|
||||
public function getState(): string
|
||||
{
|
||||
return $this->result->getState();
|
||||
}
|
||||
|
||||
public function resolve($value = null): void
|
||||
{
|
||||
$this->result->resolve($value);
|
||||
}
|
||||
|
||||
public function reject($reason): void
|
||||
{
|
||||
$this->result->reject($reason);
|
||||
}
|
||||
|
||||
public function cancel(): void
|
||||
{
|
||||
if (isset($this->currentPromise)) {
|
||||
$this->currentPromise->cancel();
|
||||
}
|
||||
|
||||
$this->result->cancel();
|
||||
}
|
||||
|
||||
private function nextCoroutine($yielded): void
|
||||
{
|
||||
$this->currentPromise = Create::promiseFor($yielded)
|
||||
->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function _handleSuccess($value): void
|
||||
{
|
||||
$this->currentPromise = null;
|
||||
|
||||
try {
|
||||
$next = $this->generator->send($value);
|
||||
if ($this->generator->valid()) {
|
||||
$this->nextCoroutine($next);
|
||||
} else {
|
||||
$this->result->resolve($value);
|
||||
}
|
||||
} catch (\Throwable $throwable) {
|
||||
$this->result->reject($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function _handleFailure($reason): void
|
||||
{
|
||||
$this->currentPromise = null;
|
||||
|
||||
try {
|
||||
$nextYield = $this->generator->throw(Create::exceptionFor($reason));
|
||||
// The throw was caught, so keep iterating on the coroutine
|
||||
$this->nextCoroutine($nextYield);
|
||||
} catch (\Throwable $throwable) {
|
||||
$this->result->reject($throwable);
|
||||
}
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Create
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `$value` when it is already a Guzzle promise, wraps foreign
|
||||
* thenables in a Guzzle promise, or returns a fulfilled promise for plain
|
||||
* values.
|
||||
*
|
||||
* @template TValue
|
||||
* @template TPromise of PromiseInterface<mixed, mixed> = PromiseInterface<mixed, mixed>
|
||||
*
|
||||
* @param TValue|TPromise $value Promise or value.
|
||||
*
|
||||
* @return ($value is PromiseInterface ? TPromise : FulfilledPromise<TValue, never>)
|
||||
*/
|
||||
public static function promiseFor($value): PromiseInterface
|
||||
{
|
||||
if ($value instanceof PromiseInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// Return a Guzzle promise that shadows the given promise.
|
||||
if (is_object($value) && method_exists($value, 'then')) {
|
||||
$wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
|
||||
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
|
||||
$promise = new Promise($wfn, $cfn);
|
||||
try {
|
||||
$value->then([$promise, 'resolve'], [$promise, 'reject']);
|
||||
} catch (\Throwable $e) {
|
||||
if (State::isPending($promise)) {
|
||||
// The thenable may still hold the callbacks.
|
||||
$promise = new Promise();
|
||||
$promise->reject($e);
|
||||
}
|
||||
}
|
||||
|
||||
return $promise;
|
||||
}
|
||||
|
||||
return new FulfilledPromise($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `$reason` when it is already a promise, or returns a rejected
|
||||
* promise for plain reasons.
|
||||
*
|
||||
* @template TReason
|
||||
* @template TValue = never
|
||||
* @template TPromise of PromiseInterface<mixed, mixed> = PromiseInterface<mixed, mixed>
|
||||
*
|
||||
* @param TReason|TPromise $reason Promise or reason.
|
||||
*
|
||||
* @return ($reason is PromiseInterface ? TPromise : RejectedPromise<TValue, TReason>)
|
||||
*/
|
||||
public static function rejectionFor($reason): PromiseInterface
|
||||
{
|
||||
if ($reason instanceof PromiseInterface) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
return new RejectedPromise($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns throwable reasons as-is, or wraps non-throwable reasons in
|
||||
* `RejectionException`.
|
||||
*
|
||||
* @template TReason
|
||||
*
|
||||
* @param TReason $reason
|
||||
*/
|
||||
public static function exceptionFor($reason): \Throwable
|
||||
{
|
||||
if ($reason instanceof \Throwable) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
return new RejectionException($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for arrays, iterators, iterator aggregates, and
|
||||
* traversables.
|
||||
*
|
||||
* @template TKey of array-key
|
||||
* @template TValue
|
||||
*
|
||||
* @param iterable<TKey, TValue> $value
|
||||
*
|
||||
* @return \Iterator<TKey, TValue>
|
||||
*/
|
||||
public static function iterFor(iterable $value): \Iterator
|
||||
{
|
||||
if ($value instanceof \Iterator) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return new \ArrayIterator($value);
|
||||
}
|
||||
|
||||
if ($value instanceof \IteratorAggregate) {
|
||||
return self::iterFor($value->getIterator());
|
||||
}
|
||||
|
||||
return new \IteratorIterator($value);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Each
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an iterator that yields promises or values, returns a promise that
|
||||
* is fulfilled with a null value when the iterator has been consumed or
|
||||
* the aggregate promise has been fulfilled or rejected.
|
||||
*
|
||||
* $onFulfilled is a function that accepts the fulfilled value, iterable
|
||||
* key, and the aggregate promise. The callback can invoke any necessary
|
||||
* side effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* $onRejected is a function that accepts the rejection reason, iterable
|
||||
* key, and the aggregate promise. The callback can invoke any necessary
|
||||
* side effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* The config array accepts a concurrency option matching {@see ofLimit}.
|
||||
* Other config keys are ignored by this wrapper.
|
||||
*
|
||||
* @template TKey of array-key
|
||||
* @template TValue
|
||||
* @template TReason
|
||||
*
|
||||
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable Iterator or array to iterate over.
|
||||
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
|
||||
* @param (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onRejected
|
||||
* @param array{concurrency?: int|(callable(int): int)} $config Configuration options.
|
||||
*
|
||||
* @return PromiseInterface<mixed, mixed>
|
||||
*/
|
||||
public static function of(
|
||||
iterable $iterable,
|
||||
?callable $onFulfilled = null,
|
||||
?callable $onRejected = null,
|
||||
array $config = []
|
||||
): PromiseInterface {
|
||||
$eachConfig = [];
|
||||
|
||||
if (null !== $onFulfilled) {
|
||||
$eachConfig['fulfilled'] = $onFulfilled;
|
||||
}
|
||||
|
||||
if (null !== $onRejected) {
|
||||
$eachConfig['rejected'] = $onRejected;
|
||||
}
|
||||
|
||||
if (isset($config['concurrency'])) {
|
||||
$eachConfig['concurrency'] = $config['concurrency'];
|
||||
}
|
||||
|
||||
return (new EachPromise($iterable, $eachConfig))->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Like of, but only allows a certain number of outstanding promises at any
|
||||
* given time.
|
||||
*
|
||||
* $concurrency may be an integer or a function that accepts the number of
|
||||
* pending promises and returns a numeric concurrency limit value to allow
|
||||
* for a dynamic concurrency size.
|
||||
*
|
||||
* @template TKey of array-key
|
||||
* @template TValue
|
||||
* @template TReason
|
||||
*
|
||||
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable
|
||||
* @param int|(callable(int): int) $concurrency
|
||||
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
|
||||
* @param (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onRejected
|
||||
*
|
||||
* @return PromiseInterface<mixed, mixed>
|
||||
*/
|
||||
public static function ofLimit(
|
||||
iterable $iterable,
|
||||
$concurrency,
|
||||
?callable $onFulfilled = null,
|
||||
?callable $onRejected = null
|
||||
): PromiseInterface {
|
||||
return self::of($iterable, $onFulfilled, $onRejected, ['concurrency' => $concurrency]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like ofLimit, but rejects the aggregate promise on the first rejection.
|
||||
*
|
||||
* @template TKey of array-key
|
||||
* @template TValue
|
||||
* @template TReason
|
||||
*
|
||||
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable
|
||||
* @param int|(callable(int): int) $concurrency
|
||||
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
|
||||
*
|
||||
* @return PromiseInterface<mixed, mixed>
|
||||
*/
|
||||
public static function ofLimitAll(
|
||||
iterable $iterable,
|
||||
$concurrency,
|
||||
?callable $onFulfilled = null
|
||||
): PromiseInterface {
|
||||
return self::ofLimit(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
$onFulfilled,
|
||||
function ($reason, $idx, PromiseInterface $aggregate): void {
|
||||
$aggregate->reject($reason);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
* Represents a promise that iterates over many promises and invokes
|
||||
* side-effect functions in the process.
|
||||
*
|
||||
* @template TKey of array-key
|
||||
* @template TValue
|
||||
* @template TReason
|
||||
*
|
||||
* @implements PromisorInterface<mixed, mixed>
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class EachPromise implements PromisorInterface
|
||||
{
|
||||
use NonSerializableTrait;
|
||||
|
||||
/** @var array<int, PromiseInterface<mixed, mixed>>|null */
|
||||
private ?array $pending = [];
|
||||
|
||||
private int $nextPendingIndex = 0;
|
||||
|
||||
/** @var \Iterator<TKey, TValue|PromiseInterface<TValue, TReason>>|null */
|
||||
private ?\Iterator $iterable;
|
||||
|
||||
/** @var (callable(int): int)|int|null */
|
||||
private $concurrency;
|
||||
|
||||
/** @var (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null */
|
||||
private $onFulfilled;
|
||||
|
||||
/** @var (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null */
|
||||
private $onRejected;
|
||||
|
||||
/** @var Promise<mixed, mixed>|null */
|
||||
private ?Promise $aggregate = null;
|
||||
|
||||
private ?bool $mutex = null;
|
||||
|
||||
private bool $stepWhileLocked = false;
|
||||
|
||||
/**
|
||||
* Configuration hash can include the following key value pairs:
|
||||
*
|
||||
* - fulfilled: (callable) Invoked when a promise fulfills. The function
|
||||
* is invoked with three arguments: the fulfillment value, the index
|
||||
* position from the iterable list of the promise, and the aggregate
|
||||
* promise that manages all of the promises. The aggregate promise may
|
||||
* be resolved from within the callback to short-circuit the promise.
|
||||
* - rejected: (callable) Invoked when a promise is rejected. The
|
||||
* function is invoked with three arguments: the rejection reason, the
|
||||
* index position from the iterable list of the promise, and the
|
||||
* aggregate promise that manages all of the promises. The aggregate
|
||||
* promise may be resolved from within the callback to short-circuit
|
||||
* the promise.
|
||||
* - concurrency: (integer) Pass this configuration option to limit the
|
||||
* allowed number of outstanding concurrently executing promises,
|
||||
* creating a capped pool of promises. There is no limit by default.
|
||||
*
|
||||
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable Promises or values to iterate.
|
||||
* @param array{
|
||||
* fulfilled?: callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed,
|
||||
* rejected?: callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed,
|
||||
* concurrency?: int|(callable(int): int)
|
||||
* } $config Configuration options
|
||||
*/
|
||||
public function __construct(iterable $iterable, array $config = [])
|
||||
{
|
||||
$this->iterable = Create::iterFor($iterable);
|
||||
|
||||
if (isset($config['concurrency'])) {
|
||||
$this->concurrency = $config['concurrency'];
|
||||
}
|
||||
|
||||
if (isset($config['fulfilled'])) {
|
||||
$this->onFulfilled = $config['fulfilled'];
|
||||
}
|
||||
|
||||
if (isset($config['rejected'])) {
|
||||
$this->onRejected = $config['rejected'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PromiseInterface<mixed, mixed>
|
||||
*/
|
||||
public function promise(): PromiseInterface
|
||||
{
|
||||
if ($this->aggregate) {
|
||||
return $this->aggregate;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->createPromise();
|
||||
$this->iterable->rewind();
|
||||
$this->refillPending();
|
||||
if (!$this->pending) {
|
||||
Utils::queue()->add(function (): void {
|
||||
if (!$this->aggregate || State::isSettled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->checkIfFinished();
|
||||
} catch (\Throwable $e) {
|
||||
$this->aggregate->reject($e);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
$this->aggregate->reject($e);
|
||||
}
|
||||
|
||||
return $this->aggregate;
|
||||
}
|
||||
|
||||
private function createPromise(): void
|
||||
{
|
||||
$this->mutex = false;
|
||||
$this->aggregate = new Promise(function (): void {
|
||||
while (true) {
|
||||
if ($this->checkIfFinished()) {
|
||||
return;
|
||||
}
|
||||
reset($this->pending);
|
||||
// Consume a potentially fluctuating list of promises while
|
||||
// ensuring that indexes are maintained (precluding array_shift).
|
||||
while ($promise = current($this->pending)) {
|
||||
next($this->pending);
|
||||
$promise->wait();
|
||||
if (State::isSettled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Refill and re-sweep; give up only when nothing remains.
|
||||
$this->refillPending();
|
||||
if (State::isSettled($this->aggregate) || !$this->pending) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Clear the references when the promise is resolved.
|
||||
$clearFn = function (): void {
|
||||
$this->iterable = $this->concurrency = $this->pending = null;
|
||||
$this->onFulfilled = $this->onRejected = null;
|
||||
$this->nextPendingIndex = 0;
|
||||
};
|
||||
|
||||
$this->aggregate->then($clearFn, $clearFn);
|
||||
}
|
||||
|
||||
private function refillPending(): void
|
||||
{
|
||||
if (!$this->concurrency) {
|
||||
// Add all pending promises.
|
||||
while ($this->addPending() && $this->advanceIterator()) {
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Add only up to N pending promises.
|
||||
$concurrency = is_callable($this->concurrency)
|
||||
? ($this->concurrency)(count($this->pending))
|
||||
: $this->concurrency;
|
||||
// The callable can settle the aggregate; admit nothing more.
|
||||
if (State::isSettled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
$concurrency = max($concurrency - count($this->pending), 0);
|
||||
// Concurrency may be set to 0 to disallow new promises.
|
||||
if (!$concurrency) {
|
||||
return;
|
||||
}
|
||||
// Add the first pending promise.
|
||||
$this->addPending();
|
||||
// Note this is special handling for concurrency=1 so that we do
|
||||
// not advance the iterator after adding the first promise. This
|
||||
// helps work around issues with generators that might not have the
|
||||
// next value to yield until promise callbacks are called.
|
||||
while (--$concurrency
|
||||
&& $this->advanceIterator()
|
||||
&& $this->addPending()) {
|
||||
}
|
||||
}
|
||||
|
||||
private function addPending(): bool
|
||||
{
|
||||
if (!$this->iterable || !$this->iterable->valid()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$promise = Create::promiseFor($this->iterable->current());
|
||||
$key = $this->iterable->key();
|
||||
|
||||
// Iterable keys may not be unique, so we use a counter to
|
||||
// guarantee uniqueness
|
||||
$idx = $this->nextPendingIndex++;
|
||||
|
||||
$this->pending[$idx] = $promise->then(
|
||||
function ($value) use ($idx, $key): void {
|
||||
if ($this->onFulfilled) {
|
||||
($this->onFulfilled)(
|
||||
$value,
|
||||
$key,
|
||||
$this->aggregate
|
||||
);
|
||||
}
|
||||
$this->step($idx);
|
||||
},
|
||||
function ($reason) use ($idx, $key): void {
|
||||
if ($this->onRejected) {
|
||||
($this->onRejected)(
|
||||
$reason,
|
||||
$key,
|
||||
$this->aggregate
|
||||
);
|
||||
}
|
||||
$this->step($idx);
|
||||
}
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function advanceIterator(): bool
|
||||
{
|
||||
// Place a lock on the iterator so that we ensure to not recurse,
|
||||
// preventing fatal generator errors.
|
||||
if ($this->mutex) {
|
||||
$this->stepWhileLocked = true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->mutex = true;
|
||||
|
||||
try {
|
||||
$this->iterable->next();
|
||||
$this->mutex = false;
|
||||
} catch (\Throwable $e) {
|
||||
$this->aggregate->reject($e);
|
||||
$this->mutex = false;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Run the completion check that locked steps skipped.
|
||||
if ($this->stepWhileLocked) {
|
||||
$this->stepWhileLocked = false;
|
||||
if (!State::isSettled($this->aggregate)) {
|
||||
$this->checkIfFinished();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function step(int $idx): void
|
||||
{
|
||||
// If the promise was already resolved, then ignore this step.
|
||||
if (State::isSettled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unset($this->pending[$idx]);
|
||||
|
||||
// Only refill pending promises if we are not locked, preventing the
|
||||
// EachPromise to recursively invoke the provided iterator, which
|
||||
// cause a fatal error: "Cannot resume an already running generator"
|
||||
if ($this->advanceIterator() && !$this->checkIfFinished()) {
|
||||
// Add more pending promises if possible.
|
||||
$this->refillPending();
|
||||
}
|
||||
}
|
||||
|
||||
/** @phpstan-impure */
|
||||
private function checkIfFinished(): bool
|
||||
{
|
||||
if (!$this->pending && !$this->iterable->valid()) {
|
||||
// Resolve the promise if there's nothing left to do.
|
||||
$this->aggregate->resolve(null);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user