changes for filter and print

This commit is contained in:
2024-09-29 16:59:27 +05:45
parent 497f567cba
commit 684e01bf48
1335 changed files with 38709 additions and 74987 deletions

View File

@@ -2,6 +2,106 @@
Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version.
## 7.9.2 - 2024-07-24
### Fixed
- Adjusted handler selection to use cURL if its version is 7.21.2 or higher, rather than 7.34.0
## 7.9.1 - 2024-07-19
### Fixed
- Fix TLS 1.3 check for HTTP/2 requests
## 7.9.0 - 2024-07-18
### Changed
- Improve protocol version checks to provide feedback around unsupported protocols
- Only select the cURL handler by default if 7.34.0 or higher is linked
- Improved `CurlMultiHandler` to avoid busy wait if possible
- Dropped support for EOL `guzzlehttp/psr7` v1
- Improved URI user info redaction in errors
## 7.8.2 - 2024-07-18
### Added
- Support for PHP 8.4
## 7.8.1 - 2023-12-03
### Changed
- Updated links in docs to their canonical versions
- Replaced `call_user_func*` with native calls
## 7.8.0 - 2023-08-27
### Added
- Support for PHP 8.3
- Added automatic closing of handles on `CurlFactory` object destruction
## 7.7.1 - 2023-08-27
### Changed
- Remove the need for `AllowDynamicProperties` in `CurlMultiHandler`
## 7.7.0 - 2023-05-21
### Added
- Support `guzzlehttp/promises` v2
## 7.6.1 - 2023-05-15
### Fixed
- Fix `SetCookie::fromString` MaxAge deprecation warning and skip invalid MaxAge values
## 7.6.0 - 2023-05-14
### Added
- Support for setting the minimum TLS version in a unified way
- Apply on request the version set in options parameters
## 7.5.2 - 2023-05-14
### Fixed
- Fixed set cookie constructor validation
- Fixed handling of files with `'0'` body
### Changed
- Corrected docs and default connect timeout value to 300 seconds
## 7.5.1 - 2023-04-17
### Fixed
- Fixed `NO_PROXY` settings so that setting the `proxy` option to `no` overrides the env variable
### Changed
- Adjusted `guzzlehttp/psr7` version constraint to `^1.9.1 || ^2.4.5`
## 7.5.0 - 2022-08-28
### Added
@@ -9,20 +109,30 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Support PHP 8.2
- Add request to delay closure params
## 7.4.5 - 2022-06-20
### Fixed
* Fix change in port should be considered a change in origin
* Fix `CURLOPT_HTTPAUTH` option not cleared on change of origin
## 7.4.4 - 2022-06-09
### Fixed
* Fix failure to strip Authorization header on HTTP downgrade
* Fix failure to strip the Cookie header on change in host or HTTP downgrade
## 7.4.3 - 2022-05-25
### Fixed
* Fix cross-domain cookie leakage
## 7.4.2 - 2022-03-20
### Fixed
@@ -31,6 +141,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Reject non-HTTP schemes in StreamHandler
- Set a default ssl.peer_name context in StreamHandler to allow `force_ip_resolve`
## 7.4.1 - 2021-12-06
### Changed
@@ -42,6 +153,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Only close curl handle if it's done [#2950](https://github.com/guzzle/guzzle/pull/2950)
## 7.4.0 - 2021-10-18
### Added
@@ -59,6 +171,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Be more strict with types [#2914](https://github.com/guzzle/guzzle/pull/2914), [#2917](https://github.com/guzzle/guzzle/pull/2917), [#2919](https://github.com/guzzle/guzzle/pull/2919), [#2945](https://github.com/guzzle/guzzle/pull/2945)
## 7.3.0 - 2021-03-23
### Added
@@ -71,6 +184,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Handle exceptions on invalid header consistently between PHP versions and handlers [#2872](https://github.com/guzzle/guzzle/pull/2872)
## 7.2.0 - 2020-10-10
### Added
@@ -93,6 +207,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- Using environment variable GUZZLE_CURL_SELECT_TIMEOUT [#2786](https://github.com/guzzle/guzzle/pull/2786)
## 7.1.1 - 2020-09-30
### Fixed
@@ -104,6 +219,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- We dont connect curl `sink` on HEAD requests.
- Removed some PHP 5 workarounds
## 7.1.0 - 2020-09-22
### Added
@@ -126,14 +242,17 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version
- `Utils::defaultCaBundle()`
- `CurlFactory::LOW_CURL_VERSION_NUMBER`
## 7.0.1 - 2020-06-27
* Fix multiply defined functions fatal error [#2699](https://github.com/guzzle/guzzle/pull/2699)
## 7.0.0 - 2020-06-27
No changes since 7.0.0-rc1.
## 7.0.0-rc1 - 2020-06-15
### Changed
@@ -141,6 +260,7 @@ No changes since 7.0.0-rc1.
* Use error level for logging errors in Middleware [#2629](https://github.com/guzzle/guzzle/pull/2629)
* Disabled IDN support by default and require ext-intl to use it [#2675](https://github.com/guzzle/guzzle/pull/2675)
## 7.0.0-beta2 - 2020-05-25
### Added
@@ -166,6 +286,7 @@ No changes since 7.0.0-rc1.
* Pool option `pool_size` [#2528](https://github.com/guzzle/guzzle/pull/2528)
## 7.0.0-beta1 - 2019-12-30
The diff might look very big but 95% of Guzzle users will be able to upgrade without modification.
@@ -199,15 +320,18 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* `uri_template()` and `UriTemplate` [#2440](https://github.com/guzzle/guzzle/pull/2440)
* Request options `save_to` and `exceptions` [#2464](https://github.com/guzzle/guzzle/pull/2464)
## 6.5.2 - 2019-12-23
* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489)
## 6.5.1 - 2019-12-21
* Better defaults for PHP installations with old ICU lib [#2454](https://github.com/guzzle/guzzle/pull/2454)
* IDN support for redirects [#2424](https://github.com/guzzle/guzzle/pull/2424)
## 6.5.0 - 2019-12-07
* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143)
@@ -217,11 +341,13 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348)
* Deprecated `ClientInterface::VERSION`
## 6.4.1 - 2019-10-23
* No `guzzle.phar` was created in 6.4.0 due expired API token. This release will fix that
* Added `parent::__construct()` to `FileCookieJar` and `SessionCookieJar`
## 6.4.0 - 2019-10-23
* Improvement: Improved error messages when using curl < 7.21.2 [#2108](https://github.com/guzzle/guzzle/pull/2108)
@@ -234,6 +360,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Fix: Prevent concurrent writes to file when saving `CookieJar` [#2335](https://github.com/guzzle/guzzle/pull/2335)
* Improvement: Update `MockHandler` so we can test transfer time [#2362](https://github.com/guzzle/guzzle/pull/2362)
## 6.3.3 - 2018-04-22
* Fix: Default headers when decode_content is specified
@@ -275,13 +402,14 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Bug fix: Fill `CURLOPT_CAPATH` and `CURLOPT_CAINFO` properly [#1684](https://github.com/guzzle/guzzle/pull/1684)
* Improvement: Use `\GuzzleHttp\Promise\rejection_for` function instead of object init [#1827](https://github.com/guzzle/guzzle/pull/1827)
+ Minor code cleanups, documentation fixes and clarifications.
## 6.2.3 - 2017-02-28
* Fix deprecations with guzzle/psr7 version 1.4
## 6.2.2 - 2016-10-08
* Allow to pass nullable Response to delay callable
@@ -289,6 +417,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Fix drain case where content-length is the literal string zero
* Obfuscate in-URL credentials in exceptions
## 6.2.1 - 2016-07-18
* Address HTTP_PROXY security vulnerability, CVE-2016-5385:
@@ -299,6 +428,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
a server does not honor `Connection: close`.
* Ignore URI fragment when sending requests.
## 6.2.0 - 2016-03-21
* Feature: added `GuzzleHttp\json_encode` and `GuzzleHttp\json_decode`.
@@ -318,6 +448,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Bug fix: provide an empty string to `http_build_query` for HHVM workaround.
https://github.com/guzzle/guzzle/pull/1367
## 6.1.1 - 2015-11-22
* Bug fix: Proxy::wrapSync() now correctly proxies to the appropriate handler
@@ -333,6 +464,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Bug fix: fixed regression where MockHandler was not using `sink`.
https://github.com/guzzle/guzzle/pull/1292
## 6.1.0 - 2015-09-08
* Feature: Added the `on_stats` request option to provide access to transfer
@@ -367,6 +499,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Bug fix: Adding a Content-Length to PHP stream wrapper requests if not set.
https://github.com/guzzle/guzzle/pull/1189
## 6.0.2 - 2015-07-04
* Fixed a memory leak in the curl handlers in which references to callbacks
@@ -384,6 +517,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Functions are now conditionally required using an additional level of
indirection to help with global Composer installations.
## 6.0.1 - 2015-05-27
* Fixed a bug with serializing the `query` request option where the `&`
@@ -392,6 +526,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
use `form_params` or `multipart` instead.
* Various doc fixes.
## 6.0.0 - 2015-05-26
* See the UPGRADING.md document for more information.
@@ -416,6 +551,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* `$maxHandles` has been removed from CurlMultiHandler.
* `MultipartPostBody` is now part of the `guzzlehttp/psr7` package.
## 5.3.0 - 2015-05-19
* Mock now supports `save_to`
@@ -426,6 +562,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Marked `GuzzleHttp\Client::getDefaultUserAgent` as deprecated.
* URL scheme is now always lowercased.
## 6.0.0-beta.1
* Requires PHP >= 5.5
@@ -478,6 +615,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* `GuzzleHttp\QueryParser` has been replaced with the
`GuzzleHttp\Psr7\parse_query`.
## 5.2.0 - 2015-01-27
* Added `AppliesHeadersInterface` to make applying headers to a request based
@@ -488,6 +626,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
RingBridge.
* Added a guard in the Pool class to not use recursion for request retries.
## 5.1.0 - 2014-12-19
* Pool class no longer uses recursion when a request is intercepted.
@@ -508,6 +647,7 @@ Please see [the upgrade document](UPGRADING.md) that describes all BC breaking c
* Exceptions thrown in the `end` event are now correctly wrapped with Guzzle
specific exceptions if necessary.
## 5.0.3 - 2014-11-03
This change updates query strings so that they are treated as un-encoded values
@@ -522,6 +662,7 @@ string that should not be parsed or encoded (unless a call to getQuery() is
subsequently made, forcing the query-string to be converted into a Query
object).
## 5.0.2 - 2014-10-30
* Added a trailing `\r\n` to multipart/form-data payloads. See
@@ -541,7 +682,9 @@ object).
* Note: This has been changed in 5.0.3 to now encode query string values by
default unless the `rawString` argument is provided when setting the query
string on a URL: Now allowing many more characters to be present in the
query string without being percent encoded. See https://tools.ietf.org/html/rfc3986#appendix-A
query string without being percent encoded. See
https://datatracker.ietf.org/doc/html/rfc3986#appendix-A
## 5.0.1 - 2014-10-16
@@ -554,6 +697,7 @@ Bugfix release.
* Fixed an issue where transfer statistics were not being populated in the
RingBridge. https://github.com/guzzle/guzzle/issues/866
## 5.0.0 - 2014-10-12
Adding support for non-blocking responses and some minor API cleanup.
@@ -635,6 +779,7 @@ interfaces.
argument. They now accept an associative array of options, including the
"size" key and "metadata" key which can be used to provide custom metadata.
## 4.2.2 - 2014-09-08
* Fixed a memory leak in the CurlAdapter when reusing cURL handles.
@@ -1077,7 +1222,7 @@ interfaces.
## 3.4.0 - 2013-04-11
* Bug fix: URLs are now resolved correctly based on https://tools.ietf.org/html/rfc3986#section-5.2. #289
* Bug fix: URLs are now resolved correctly based on https://datatracker.ietf.org/doc/html/rfc3986#section-5.2. #289
* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289
* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263
* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264.

View File

@@ -3,7 +3,7 @@
# Guzzle, PHP HTTP client
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/github/workflow/status/guzzle/guzzle/CI?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
@@ -60,13 +60,13 @@ composer require guzzlehttp/guzzle
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|----------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | Security fixes | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.2 |
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL (2016-10-31) | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL (2016-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL (2019-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | EOL (2023-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.5 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x

View File

@@ -27,7 +27,7 @@ Please make sure:
- Function `GuzzleHttp\Exception\RequestException::getResponseBodySummary` is removed.
Use `\GuzzleHttp\Psr7\get_message_body_summary` as an alternative.
- Function `GuzzleHttp\Cookie\CookieJar::getCookieValue` is removed.
- Request option `exception` is removed. Please use `http_errors`.
- Request option `exceptions` is removed. Please use `http_errors`.
- Request option `save_to` is removed. Please use `sink`.
- Pool option `pool_size` is removed. Please use `concurrency`.
- We now look for environment variables in the `$_SERVER` super global, due to thread safety issues with `getenv`. We continue to fallback to `getenv` in CLI environments, for maximum compatibility.
@@ -189,11 +189,11 @@ $client = new GuzzleHttp\Client(['handler' => $handler]);
## POST Requests
This version added the [`form_params`](http://guzzle.readthedocs.org/en/latest/request-options.html#form_params)
This version added the [`form_params`](https://docs.guzzlephp.org/en/latest/request-options.html#form_params)
and `multipart` request options. `form_params` is an associative array of
strings or array of strings and is used to serialize an
`application/x-www-form-urlencoded` POST request. The
[`multipart`](http://guzzle.readthedocs.org/en/latest/request-options.html#multipart)
[`multipart`](https://docs.guzzlephp.org/en/latest/request-options.html#multipart)
option is now used to send a multipart/form-data POST request.
`GuzzleHttp\Post\PostFile` has been removed. Use the `multipart` option to add
@@ -209,7 +209,7 @@ The `base_url` option has been renamed to `base_uri`.
## Rewritten Adapter Layer
Guzzle now uses [RingPHP](http://ringphp.readthedocs.org/en/latest) to send
Guzzle now uses [RingPHP](https://ringphp.readthedocs.org/en/latest) to send
HTTP requests. The `adapter` option in a `GuzzleHttp\Client` constructor
is still supported, but it has now been renamed to `handler`. Instead of
passing a `GuzzleHttp\Adapter\AdapterInterface`, you must now pass a PHP
@@ -575,7 +575,7 @@ You can intercept a request and inject a response using the `intercept()` event
of a `GuzzleHttp\Event\BeforeEvent`, `GuzzleHttp\Event\CompleteEvent`, and
`GuzzleHttp\Event\ErrorEvent` event.
See: http://docs.guzzlephp.org/en/latest/events.html
See: https://docs.guzzlephp.org/en/latest/events.html
## Inflection
@@ -668,9 +668,9 @@ in separate repositories:
The service description layer of Guzzle has moved into two separate packages:
- http://github.com/guzzle/command Provides a high level abstraction over web
- https://github.com/guzzle/command Provides a high level abstraction over web
services by representing web service operations using commands.
- http://github.com/guzzle/guzzle-services Provides an implementation of
- https://github.com/guzzle/guzzle-services Provides an implementation of
guzzle/command that provides request serialization and response parsing using
Guzzle service descriptions.
@@ -870,7 +870,7 @@ HeaderInterface (e.g. toArray(), getAll(), etc.).
3.3 to 3.4
----------
Base URLs of a client now follow the rules of https://tools.ietf.org/html/rfc3986#section-5.2.2 when merging URLs.
Base URLs of a client now follow the rules of https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2 when merging URLs.
3.2 to 3.3
----------

View File

@@ -50,11 +50,39 @@
"homepage": "https://github.com/Tobion"
}
],
"repositories": [
{
"type": "package",
"package": {
"name": "guzzle/client-integration-tests",
"version": "v3.0.2",
"dist": {
"url": "https://codeload.github.com/guzzle/client-integration-tests/zip/2c025848417c1135031fdf9c728ee53d0a7ceaee",
"type": "zip"
},
"require": {
"php": "^7.2.5 || ^8.0",
"phpunit/phpunit": "^7.5.20 || ^8.5.8 || ^9.3.11",
"php-http/message": "^1.0 || ^2.0",
"guzzlehttp/psr7": "^1.7 || ^2.0",
"th3n3rd/cartesian-product": "^0.3"
},
"autoload": {
"psr-4": {
"Http\\Client\\Tests\\": "src/"
}
},
"bin": [
"bin/http_test_server"
]
}
}
],
"require": {
"php": "^7.2.5 || ^8.0",
"ext-json": "*",
"guzzlehttp/promises": "^1.5",
"guzzlehttp/psr7": "^1.9 || ^2.4",
"guzzlehttp/promises": "^1.5.3 || ^2.0.3",
"guzzlehttp/psr7": "^2.7.0",
"psr/http-client": "^1.0",
"symfony/deprecation-contracts": "^2.2 || ^3.0"
},
@@ -63,9 +91,10 @@
},
"require-dev": {
"ext-curl": "*",
"bamarni/composer-bin-plugin": "^1.8.1",
"php-http/client-integration-tests": "^3.0",
"phpunit/phpunit": "^8.5.29 || ^9.5.23",
"bamarni/composer-bin-plugin": "^1.8.2",
"guzzle/client-integration-tests": "3.0.2",
"php-http/message-factory": "^1.1",
"phpunit/phpunit": "^8.5.39 || ^9.6.20",
"psr/log": "^1.1 || ^2.0 || ^3.0"
},
"suggest": {
@@ -84,9 +113,6 @@
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "7.5-dev"
}
},
"autoload": {

View File

@@ -11,7 +11,7 @@ final class BodySummarizer implements BodySummarizerInterface
*/
private $truncateAt;
public function __construct(int $truncateAt = null)
public function __construct(?int $truncateAt = null)
{
$this->truncateAt = $truncateAt;
}
@@ -22,7 +22,7 @@ final class BodySummarizer implements BodySummarizerInterface
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? \GuzzleHttp\Psr7\Message::bodySummary($message)
: \GuzzleHttp\Psr7\Message::bodySummary($message, $this->truncateAt);
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
}
}

View File

@@ -52,7 +52,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*
* @param array $config Client configuration settings.
*
* @see \GuzzleHttp\RequestOptions for a list of available request options.
* @see RequestOptions for a list of available request options.
*/
public function __construct(array $config = [])
{
@@ -120,13 +120,14 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
public function send(RequestInterface $request, array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->sendAsync($request, $options)->wait();
}
/**
* The HttpClient PSR (PSR-18) specify this method.
*
* @inheritDoc
* {@inheritDoc}
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
@@ -184,6 +185,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
public function request(string $method, $uri = '', array $options = []): ResponseInterface
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->requestAsync($method, $uri, $options)->wait();
}
@@ -228,11 +230,11 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
{
$defaults = [
'allow_redirects' => RedirectMiddleware::$defaultSettings,
'http_errors' => true,
'decode_content' => true,
'verify' => true,
'cookies' => false,
'idn_conversion' => false,
'http_errors' => true,
'decode_content' => true,
'verify' => true,
'cookies' => false,
'idn_conversion' => false,
];
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
@@ -354,10 +356,10 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (isset($options['form_params'])) {
if (isset($options['multipart'])) {
throw new InvalidArgumentException('You cannot use '
. 'form_params and multipart at the same time. Use the '
. 'form_params option if you want to send application/'
. 'x-www-form-urlencoded requests, and the multipart '
. 'option to send multipart/form-data requests.');
.'form_params and multipart at the same time. Use the '
.'form_params option if you want to send application/'
.'x-www-form-urlencoded requests, and the multipart '
.'option to send multipart/form-data requests.');
}
$options['body'] = \http_build_query($options['form_params'], '', '&');
unset($options['form_params']);
@@ -403,7 +405,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
// Ensure that we don't have the header in different case and set the new value.
$modify['set_headers'] = Psr7\Utils::caselessRemove(['Authorization'], $modify['set_headers']);
$modify['set_headers']['Authorization'] = 'Basic '
. \base64_encode("$value[0]:$value[1]");
.\base64_encode("$value[0]:$value[1]");
break;
case 'digest':
// @todo: Do not rely on curl
@@ -437,13 +439,17 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
}
}
if (isset($options['version'])) {
$modify['version'] = $options['version'];
}
$request = Psr7\Utils::modifyRequest($request, $modify);
if ($request->getBody() instanceof Psr7\MultipartStream) {
// Use a multipart/form-data POST if a Content-Type is not set.
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
. $request->getBody()->getBoundary();
.$request->getBody()->getBoundary();
}
// Merge in conditional headers if they are not present.
@@ -469,9 +475,9 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
private function invalidBody(): InvalidArgumentException
{
return new InvalidArgumentException('Passing in the "body" request '
. 'option as an array to send a request is not supported. '
. 'Please use the "form_params" request option to send a '
. 'application/x-www-form-urlencoded request, or the "multipart" '
. 'request option to send a multipart/form-data request.');
.'option as an array to send a request is not supported. '
.'Please use the "form_params" request option to send a '
.'application/x-www-form-urlencoded request, or the "multipart" '
.'request option to send a multipart/form-data request.');
}
}

View File

@@ -50,10 +50,10 @@ class CookieJar implements CookieJarInterface
$cookieJar = new self();
foreach ($cookies as $name => $value) {
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Discard' => true,
]));
}
@@ -96,9 +96,6 @@ class CookieJar implements CookieJarInterface
return null;
}
/**
* @inheritDoc
*/
public function toArray(): array
{
return \array_map(static function (SetCookie $cookie): array {
@@ -106,13 +103,11 @@ class CookieJar implements CookieJarInterface
}, $this->getIterator()->getArrayCopy());
}
/**
* @inheritDoc
*/
public function clear(?string $domain = null, ?string $path = null, ?string $name = null): void
{
if (!$domain) {
$this->cookies = [];
return;
} elseif (!$path) {
$this->cookies = \array_filter(
@@ -125,25 +120,22 @@ class CookieJar implements CookieJarInterface
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
return !($cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
return !($cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getName() == $name &&
$cookie->matchesPath($path) &&
$cookie->matchesDomain($domain));
return !($cookie->getName() == $name
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
);
}
}
/**
* @inheritDoc
*/
public function clearSessionCookies(): void
{
$this->cookies = \array_filter(
@@ -154,9 +146,6 @@ class CookieJar implements CookieJarInterface
);
}
/**
* @inheritDoc
*/
public function setCookie(SetCookie $cookie): bool
{
// If the name string is empty (but not 0), ignore the set-cookie
@@ -170,9 +159,10 @@ class CookieJar implements CookieJarInterface
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new \RuntimeException('Invalid cookie: ' . $result);
throw new \RuntimeException('Invalid cookie: '.$result);
}
$this->removeCookieIfEmpty($cookie);
return false;
}
@@ -180,9 +170,9 @@ class CookieJar implements CookieJarInterface
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->getName() != $cookie->getName()
if ($c->getPath() != $cookie->getPath()
|| $c->getDomain() != $cookie->getDomain()
|| $c->getName() != $cookie->getName()
) {
continue;
}
@@ -253,7 +243,7 @@ class CookieJar implements CookieJarInterface
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
* @link https://tools.ietf.org/html/rfc6265#section-5.1.4
* @see https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.4
*/
private function getCookiePathFromRequest(RequestInterface $request): string
{
@@ -284,13 +274,13 @@ class CookieJar implements CookieJarInterface
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
if ($cookie->matchesPath($path) &&
$cookie->matchesDomain($host) &&
!$cookie->isExpired() &&
(!$cookie->getSecure() || $scheme === 'https')
if ($cookie->matchesPath($path)
&& $cookie->matchesDomain($host)
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName() . '='
. $cookie->getValue();
$values[] = $cookie->getName().'='
.$cookie->getValue();
}
}

View File

@@ -13,7 +13,8 @@ use Psr\Http\Message\ResponseInterface;
* necessary. Subclasses are also responsible for storing and retrieving
* cookies from a file, database, etc.
*
* @link https://docs.python.org/2/library/cookielib.html Inspiration
* @see https://docs.python.org/2/library/cookielib.html Inspiration
*
* @extends \IteratorAggregate<SetCookie>
*/
interface CookieJarInterface extends \Countable, \IteratorAggregate

View File

@@ -71,7 +71,7 @@ class SessionCookieJar extends CookieJar
$this->setCookie(new SetCookie($cookie));
}
} elseif (\strlen($data)) {
throw new \RuntimeException("Invalid cookie data");
throw new \RuntimeException('Invalid cookie data');
}
}
}

View File

@@ -11,15 +11,15 @@ class SetCookie
* @var array
*/
private static $defaults = [
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false
'Name' => null,
'Value' => null,
'Domain' => null,
'Path' => '/',
'Max-Age' => null,
'Expires' => null,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
];
/**
@@ -58,7 +58,13 @@ class SetCookie
} else {
foreach (\array_keys(self::$defaults) as $search) {
if (!\strcasecmp($search, $key)) {
$data[$search] = $value;
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
}
} else {
$data[$search] = $value;
}
continue 2;
}
}
@@ -74,13 +80,49 @@ class SetCookie
*/
public function __construct(array $data = [])
{
/** @var array|null $replaced will be null in case of replace error */
$replaced = \array_replace(self::$defaults, $data);
if ($replaced === null) {
throw new \InvalidArgumentException('Unable to replace the default values for the Cookie.');
$this->data = self::$defaults;
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];
}
$this->data = $replaced;
// Extract the Expires value and turn it into a UNIX timestamp if needed
if (!$this->getExpires() && $this->getMaxAge()) {
// Calculate the Expires date
@@ -92,13 +134,13 @@ class SetCookie
public function __toString()
{
$str = $this->data['Name'] . '=' . ($this->data['Value'] ?? '') . '; ';
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
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) . '; ';
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
} else {
$str .= ($v === true ? $k : "{$k}={$v}") . '; ';
$str .= ($v === true ? $k : "{$k}={$v}").'; ';
}
}
}
@@ -378,7 +420,7 @@ class SetCookie
}
// Remove the leading '.' as per spec in RFC 6265.
// https://tools.ietf.org/html/rfc6265#section-5.2.3
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = \ltrim(\strtolower($cookieDomain), '.');
$domain = \strtolower($domain);
@@ -389,12 +431,12 @@ class SetCookie
}
// Matching the subdomain according to RFC 6265.
// https://tools.ietf.org/html/rfc6265#section-5.1.3
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.' . \preg_quote($cookieDomain, '/') . '$/', $domain);
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain);
}
/**
@@ -423,8 +465,8 @@ class SetCookie
$name
)) {
return 'Cookie name must not contain invalid characters: ASCII '
. 'Control characters (0-31;127), space, tab and the '
. 'following characters: ()<>@,;:\"/?={}';
.'Control characters (0-31;127), space, tab and the '
.'following characters: ()<>@,;:\"/?={}';
}
// Value must not be null. 0 and empty string are valid. Empty strings

View File

@@ -14,7 +14,7 @@ class BadResponseException extends RequestException
string $message,
RequestInterface $request,
ResponseInterface $response,
\Throwable $previous = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, $request, $response, $previous, $handlerContext);

View File

@@ -25,7 +25,7 @@ class ConnectException extends TransferException implements NetworkExceptionInte
public function __construct(
string $message,
RequestInterface $request,
\Throwable $previous = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
parent::__construct($message, 0, $previous);

View File

@@ -7,7 +7,6 @@ use GuzzleHttp\BodySummarizerInterface;
use Psr\Http\Client\RequestExceptionInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
/**
* HTTP Request exception
@@ -32,8 +31,8 @@ class RequestException extends TransferException implements RequestExceptionInte
public function __construct(
string $message,
RequestInterface $request,
ResponseInterface $response = null,
\Throwable $previous = null,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = []
) {
// Set the code of the exception if the response is set and not future.
@@ -63,10 +62,10 @@ class RequestException extends TransferException implements RequestExceptionInte
*/
public static function create(
RequestInterface $request,
ResponseInterface $response = null,
\Throwable $previous = null,
?ResponseInterface $response = null,
?\Throwable $previous = null,
array $handlerContext = [],
BodySummarizerInterface $bodySummarizer = null
?BodySummarizerInterface $bodySummarizer = null
): self {
if (!$response) {
return new self(
@@ -90,8 +89,7 @@ class RequestException extends TransferException implements RequestExceptionInte
$className = __CLASS__;
}
$uri = $request->getUri();
$uri = static::obfuscateUri($uri);
$uri = \GuzzleHttp\Psr7\Utils::redactUserInfo($request->getUri());
// Client Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
@@ -113,20 +111,6 @@ class RequestException extends TransferException implements RequestExceptionInte
return new $className($message, $request, $response, $previous, $handlerContext);
}
/**
* Obfuscates URI if there is a username and a password present
*/
private static function obfuscateUri(UriInterface $uri): UriInterface
{
$userInfo = $uri->getUserInfo();
if (false !== ($pos = \strpos($userInfo, ':'))) {
return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
}
return $uri;
}
/**
* Get the request that caused the exception
*/

View File

@@ -11,6 +11,7 @@ use GuzzleHttp\Psr7\LazyOpenStream;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
/**
* Creates curl resources from a request
@@ -46,12 +47,22 @@ class CurlFactory implements CurlFactoryInterface
public function create(RequestInterface $request, array $options): EasyHandle
{
$protocolVersion = $request->getProtocolVersion();
if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
if (!self::supportsHttp2()) {
throw new ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
}
} elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
throw new ConnectException(sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
}
if (isset($options['curl']['body_as_string'])) {
$options['_body_as_string'] = $options['curl']['body_as_string'];
unset($options['curl']['body_as_string']);
}
$easy = new EasyHandle;
$easy = new EasyHandle();
$easy->request = $request;
$easy->options = $options;
$conf = $this->getDefaultConf($easy);
@@ -72,6 +83,42 @@ class CurlFactory implements CurlFactoryInterface
return $easy;
}
private static function supportsHttp2(): bool
{
static $supportsHttp2 = null;
if (null === $supportsHttp2) {
$supportsHttp2 = self::supportsTls12()
&& defined('CURL_VERSION_HTTP2')
&& (\CURL_VERSION_HTTP2 & \curl_version()['features']);
}
return $supportsHttp2;
}
private static function supportsTls12(): bool
{
static $supportsTls12 = null;
if (null === $supportsTls12) {
$supportsTls12 = \CURL_SSLVERSION_TLSv1_2 & \curl_version()['features'];
}
return $supportsTls12;
}
private static function supportsTls13(): bool
{
static $supportsTls13 = null;
if (null === $supportsTls13) {
$supportsTls13 = defined('CURL_SSLVERSION_TLSv1_3')
&& (\CURL_SSLVERSION_TLSv1_3 & \curl_version()['features']);
}
return $supportsTls13;
}
public function release(EasyHandle $easy): void
{
$resource = $easy->handle;
@@ -147,7 +194,7 @@ class CurlFactory implements CurlFactoryInterface
'error' => \curl_error($easy->handle),
'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME),
] + \curl_getinfo($easy->handle);
$ctx[self::CURL_VERSION_STR] = \curl_version()['version'];
$ctx[self::CURL_VERSION_STR] = self::getCurlVersion();
$factory->release($easy);
// Retry when nothing is present or when curl failed to rewind.
@@ -158,14 +205,25 @@ class CurlFactory implements CurlFactoryInterface
return self::createRejection($easy, $ctx);
}
private static function getCurlVersion(): string
{
static $curlVersion = null;
if (null === $curlVersion) {
$curlVersion = \curl_version()['version'];
}
return $curlVersion;
}
private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface
{
static $connectionErrors = [
\CURLE_OPERATION_TIMEOUTED => true,
\CURLE_OPERATION_TIMEOUTED => true,
\CURLE_COULDNT_RESOLVE_HOST => true,
\CURLE_COULDNT_CONNECT => true,
\CURLE_SSL_CONNECT_ERROR => true,
\CURLE_GOT_NOTHING => true,
\CURLE_COULDNT_CONNECT => true,
\CURLE_SSL_CONNECT_ERROR => true,
\CURLE_GOT_NOTHING => true,
];
if ($easy->createResponseException) {
@@ -194,15 +252,22 @@ class CurlFactory implements CurlFactoryInterface
);
}
$uri = $easy->request->getUri();
$sanitizedError = self::sanitizeCurlError($ctx['error'] ?? '', $uri);
$message = \sprintf(
'cURL error %s: %s (%s)',
$ctx['errno'],
$ctx['error'],
$sanitizedError,
'see https://curl.haxx.se/libcurl/c/libcurl-errors.html'
);
$uriString = (string) $easy->request->getUri();
if ($uriString !== '' && false === \strpos($ctx['error'], $uriString)) {
$message .= \sprintf(' for %s', $uriString);
if ('' !== $sanitizedError) {
$redactedUriString = \GuzzleHttp\Psr7\Utils::redactUserInfo($uri)->__toString();
if ($redactedUriString !== '' && false === \strpos($sanitizedError, $redactedUriString)) {
$message .= \sprintf(' for %s', $redactedUriString);
}
}
// Create a connection exception if it was a specific error code.
@@ -213,18 +278,36 @@ class CurlFactory implements CurlFactoryInterface
return P\Create::rejectionFor($error);
}
private static function sanitizeCurlError(string $error, UriInterface $uri): string
{
if ('' === $error) {
return $error;
}
$baseUri = $uri->withQuery('')->withFragment('');
$baseUriString = $baseUri->__toString();
if ('' === $baseUriString) {
return $error;
}
$redactedUriString = \GuzzleHttp\Psr7\Utils::redactUserInfo($baseUri)->__toString();
return str_replace($baseUriString, $redactedUriString, $error);
}
/**
* @return array<int|string, mixed>
*/
private function getDefaultConf(EasyHandle $easy): array
{
$conf = [
'_headers' => $easy->request->getHeaders(),
\CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
\CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''),
'_headers' => $easy->request->getHeaders(),
\CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
\CURLOPT_URL => (string) $easy->request->getUri()->withFragment(''),
\CURLOPT_RETURNTRANSFER => false,
\CURLOPT_HEADER => false,
\CURLOPT_CONNECTTIMEOUT => 150,
\CURLOPT_HEADER => false,
\CURLOPT_CONNECTTIMEOUT => 300,
];
if (\defined('CURLOPT_PROTOCOLS')) {
@@ -232,10 +315,11 @@ class CurlFactory implements CurlFactoryInterface
}
$version = $easy->request->getProtocolVersion();
if ($version == 1.1) {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
} elseif ($version == 2.0) {
if ('2' === $version || '2.0' === $version) {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
} elseif ('1.1' === $version) {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
} else {
$conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
}
@@ -250,12 +334,13 @@ class CurlFactory implements CurlFactoryInterface
if ($size === null || $size > 0) {
$this->applyBody($easy->request, $easy->options, $conf);
return;
}
$method = $easy->request->getMethod();
if ($method === 'PUT' || $method === 'POST') {
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
if (!$easy->request->hasHeader('Content-Length')) {
$conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
}
@@ -341,6 +426,7 @@ class CurlFactory implements CurlFactoryInterface
foreach (\array_keys($options['_headers']) as $key) {
if (!\strcasecmp($key, $name)) {
unset($options['_headers'][$key]);
return;
}
}
@@ -365,11 +451,11 @@ class CurlFactory implements CurlFactoryInterface
// If it's a directory or a link to a directory use CURLOPT_CAPATH.
// If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
if (
\is_dir($options['verify']) ||
(
\is_link($options['verify']) === true &&
($verifyLink = \readlink($options['verify'])) !== false &&
\is_dir($verifyLink)
\is_dir($options['verify'])
|| (
\is_link($options['verify']) === true
&& ($verifyLink = \readlink($options['verify'])) !== false
&& \is_dir($verifyLink)
)
) {
$conf[\CURLOPT_CAPATH] = $options['verify'];
@@ -388,8 +474,10 @@ class CurlFactory implements CurlFactoryInterface
// The empty string enables all available decoders and implicitly
// sets a matching 'Accept-Encoding' header.
$conf[\CURLOPT_ENCODING] = '';
// But as the user did not specify any acceptable encodings we need
// to overwrite this implicit header with an empty one.
// But as the user did not specify any encoding preference,
// let's leave it up to server by preventing curl from sending
// the header, which will be interpreted as 'Accept-Encoding: *'.
// https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
$conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
}
}
@@ -443,13 +531,53 @@ class CurlFactory implements CurlFactoryInterface
$scheme = $easy->request->getUri()->getScheme();
if (isset($options['proxy'][$scheme])) {
$host = $easy->request->getUri()->getHost();
if (!isset($options['proxy']['no']) || !Utils::isHostInNoProxy($host, $options['proxy']['no'])) {
if (isset($options['proxy']['no']) && Utils::isHostInNoProxy($host, $options['proxy']['no'])) {
unset($conf[\CURLOPT_PROXY]);
} else {
$conf[\CURLOPT_PROXY] = $options['proxy'][$scheme];
}
}
}
}
if (isset($options['crypto_method'])) {
$protocolVersion = $easy->request->getProtocolVersion();
// If HTTP/2, upgrade TLS 1.0 and 1.1 to 1.2
if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
if (
\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']
|| \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']
|| \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']
) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
} elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
if (!self::supportsTls13()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
} else {
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT === $options['crypto_method']) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_0;
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT === $options['crypto_method']) {
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_1;
} elseif (\STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT === $options['crypto_method']) {
if (!self::supportsTls12()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_2;
} elseif (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT === $options['crypto_method']) {
if (!self::supportsTls13()) {
throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
}
$conf[\CURLOPT_SSLVERSION] = \CURL_SSLVERSION_TLSv1_3;
} else {
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
}
if (isset($options['cert'])) {
$cert = $options['cert'];
if (\is_array($cert)) {
@@ -459,8 +587,8 @@ class CurlFactory implements CurlFactoryInterface
if (!\file_exists($cert)) {
throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
}
# OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
# see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
// OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
// see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
$ext = pathinfo($cert, \PATHINFO_EXTENSION);
if (preg_match('#^(der|p12)$#i', $ext)) {
$conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext);
@@ -523,9 +651,10 @@ class CurlFactory implements CurlFactoryInterface
}
} catch (\RuntimeException $e) {
$ctx['error'] = 'The connection unexpectedly failed without '
. 'providing an error. The request would have been retried, '
. 'but attempting to rewind the request body failed. '
. 'Exception: ' . $e;
.'providing an error. The request would have been retried, '
.'but attempting to rewind the request body failed. '
.'Exception: '.$e;
return self::createRejection($easy, $ctx);
}
@@ -534,14 +663,15 @@ class CurlFactory implements CurlFactoryInterface
$easy->options['_curl_retries'] = 1;
} elseif ($easy->options['_curl_retries'] == 2) {
$ctx['error'] = 'The cURL request was retried 3 times '
. 'and did not succeed. The most likely reason for the failure '
. 'is that cURL was unable to rewind the body of the request '
. 'and subsequent retries resulted in the same error. Turn on '
. 'the debug option to see what went wrong. See '
. 'https://bugs.php.net/bug.php?id=47204 for more information.';
.'and did not succeed. The most likely reason for the failure '
.'is that cURL was unable to rewind the body of the request '
.'and subsequent retries resulted in the same error. Turn on '
.'the debug option to see what went wrong. See '
.'https://bugs.php.net/bug.php?id=47204 for more information.';
return self::createRejection($easy, $ctx);
} else {
$easy->options['_curl_retries']++;
++$easy->options['_curl_retries'];
}
return $handler($easy->request, $easy->options);
@@ -571,6 +701,7 @@ class CurlFactory implements CurlFactoryInterface
$easy->createResponse();
} catch (\Exception $e) {
$easy->createResponseException = $e;
return -1;
}
if ($onHeaders !== null) {
@@ -580,6 +711,7 @@ class CurlFactory implements CurlFactoryInterface
// Associate the exception with the handle and trigger
// a curl header write error by returning 0.
$easy->onHeadersException = $e;
return -1;
}
}
@@ -589,7 +721,16 @@ class CurlFactory implements CurlFactoryInterface
} else {
$easy->headers[] = $value;
}
return \strlen($h);
};
}
public function __destruct()
{
foreach ($this->handles as $id => $handle) {
\curl_close($handle);
unset($this->handles[$id]);
}
}
}

View File

@@ -2,6 +2,7 @@
namespace GuzzleHttp\Handler;
use Closure;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\PromiseInterface;
@@ -15,11 +16,8 @@ use Psr\Http\Message\RequestInterface;
* associative array of curl option constants mapping to values in the
* **curl** key of the provided request options.
*
* @property resource|\CurlMultiHandle $_mh Internal use only. Lazy loaded multi-handle.
*
* @final
*/
#[\AllowDynamicProperties]
class CurlMultiHandler
{
/**
@@ -56,6 +54,9 @@ class CurlMultiHandler
*/
private $options = [];
/** @var resource|\CurlMultiHandle */
private $_mh;
/**
* This handler accepts the following options:
*
@@ -79,6 +80,10 @@ class CurlMultiHandler
}
$this->options = $options['options'] ?? [];
// unsetting the property forces the first access to go through
// __get().
unset($this->_mh);
}
/**
@@ -155,6 +160,9 @@ class CurlMultiHandler
}
}
// Run curl_multi_exec in the queue to enable other async tasks to run
P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
// Step through the task queue which may add additional requests.
P\Utils::queue()->run();
@@ -164,11 +172,25 @@ class CurlMultiHandler
\usleep(250);
}
while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM);
while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
// Prevent busy looping for slow HTTP requests.
\curl_multi_select($this->_mh, $this->selectTimeout);
}
$this->processMessages();
}
/**
* Runs \curl_multi_exec() inside the event loop, to prevent busy looping
*/
private function tickInQueue(): void
{
if (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
\curl_multi_select($this->_mh, 0);
P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
}
}
/**
* Runs until all outstanding connections have completed.
*/

View File

@@ -106,7 +106,7 @@ final class EasyHandle
*/
public function __get($name)
{
$msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: ' . $name;
$msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name;
throw new \BadMethodCallException($msg);
}
}

View File

@@ -14,9 +14,9 @@ final class HeaderProcessor
*
* @param string[] $headers
*
* @throws \RuntimeException
*
* @return array{0:string, 1:int, 2:?string, 3:array}
*
* @throws \RuntimeException
*/
public static function parseHeaders(array $headers): array
{

View File

@@ -52,21 +52,21 @@ class MockHandler implements \Countable
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public static function createWithMiddleware(array $queue = null, callable $onFulfilled = null, callable $onRejected = null): HandlerStack
public static function createWithMiddleware(?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 \Psr\Http\Message\ResponseInterface} objects, Exceptions,
* {@see ResponseInterface} objects, Exceptions,
* callables, or Promises.
*
* @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
*/
public function __construct(array $queue = null, callable $onFulfilled = null, callable $onRejected = null)
public function __construct(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null)
{
$this->onFulfilled = $onFulfilled;
$this->onRejected = $onRejected;
@@ -138,6 +138,7 @@ class MockHandler implements \Countable
if ($this->onRejected) {
($this->onRejected)($reason);
}
return P\Create::rejectionFor($reason);
}
);
@@ -159,7 +160,7 @@ class MockHandler implements \Countable
) {
$this->queue[] = $value;
} else {
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found ' . Utils::describeType($value));
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value));
}
}
}
@@ -199,7 +200,7 @@ class MockHandler implements \Countable
private function invokeStats(
RequestInterface $request,
array $options,
ResponseInterface $response = null,
?ResponseInterface $response = null,
$reason = null
): void {
if (isset($options['on_stats'])) {

View File

@@ -40,6 +40,12 @@ class StreamHandler
\usleep($options['delay'] * 1000);
}
$protocolVersion = $request->getProtocolVersion();
if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
throw new ConnectException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request);
}
$startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
try {
@@ -67,7 +73,7 @@ class StreamHandler
if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed
|| false !== \strpos($message, 'Connection refused')
|| false !== \strpos($message, "couldn't connect to host") // error on HHVM
|| false !== \strpos($message, "connection attempt failed")
|| false !== \strpos($message, 'connection attempt failed')
) {
$e = new ConnectException($e->getMessage(), $request, $e);
} else {
@@ -83,8 +89,8 @@ class StreamHandler
array $options,
RequestInterface $request,
?float $startTime,
ResponseInterface $response = null,
\Throwable $error = null
?ResponseInterface $response = null,
?\Throwable $error = null
): void {
if (isset($options['on_stats'])) {
$stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []);
@@ -231,9 +237,10 @@ class StreamHandler
\set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool {
$errors[] = [
'message' => $msg,
'file' => $file,
'line' => $line
'file' => $file,
'line' => $line,
];
return true;
});
@@ -247,7 +254,7 @@ class StreamHandler
$message = 'Error creating resource: ';
foreach ($errors as $err) {
foreach ($err as $key => $value) {
$message .= "[$key] $value" . \PHP_EOL;
$message .= "[$key] $value".\PHP_EOL;
}
}
throw new \RuntimeException(\trim($message));
@@ -272,7 +279,7 @@ class StreamHandler
// HTTP/1.1 streams using the PHP stream wrapper require a
// Connection: close header
if ($request->getProtocolVersion() == '1.1'
if ($request->getProtocolVersion() === '1.1'
&& !$request->hasHeader('Connection')
) {
$request = $request->withHeader('Connection', 'close');
@@ -350,6 +357,7 @@ class StreamHandler
if (false === $records || !isset($records[0]['ip'])) {
throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
}
return $uri->withHost($records[0]['ip']);
}
if ('v6' === $options['force_ip_resolve']) {
@@ -357,7 +365,8 @@ class StreamHandler
if (false === $records || !isset($records[0]['ipv6'])) {
throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
}
return $uri->withHost('[' . $records[0]['ipv6'] . ']');
return $uri->withHost('['.$records[0]['ipv6'].']');
}
}
@@ -375,11 +384,11 @@ class StreamHandler
$context = [
'http' => [
'method' => $request->getMethod(),
'header' => $headers,
'method' => $request->getMethod(),
'header' => $headers,
'protocol_version' => $request->getProtocolVersion(),
'ignore_errors' => true,
'follow_location' => 0,
'ignore_errors' => true,
'follow_location' => 0,
],
'ssl' => [
'peer_name' => $request->getUri()->getHost(),
@@ -388,7 +397,7 @@ class StreamHandler
$body = (string) $request->getBody();
if (!empty($body)) {
if ('' !== $body) {
$context['http']['content'] = $body;
// Prevent the HTTP handler from adding a Content-Type header.
if (!$request->hasHeader('Content-Type')) {
@@ -472,6 +481,25 @@ class StreamHandler
}
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
{
if (
$value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
|| $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
|| $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
|| (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
) {
$options['http']['crypto_method'] = $value;
return;
}
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
/**
* @param mixed $value as passed via Request transfer options.
*/
@@ -542,27 +570,27 @@ class StreamHandler
}
static $map = [
\STREAM_NOTIFY_CONNECT => 'CONNECT',
\STREAM_NOTIFY_CONNECT => 'CONNECT',
\STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
\STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
\STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
\STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
\STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
\STREAM_NOTIFY_PROGRESS => 'PROGRESS',
\STREAM_NOTIFY_FAILURE => 'FAILURE',
\STREAM_NOTIFY_COMPLETED => 'COMPLETED',
\STREAM_NOTIFY_RESOLVE => 'RESOLVE',
\STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
\STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
\STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
\STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
\STREAM_NOTIFY_PROGRESS => 'PROGRESS',
\STREAM_NOTIFY_FAILURE => 'FAILURE',
\STREAM_NOTIFY_COMPLETED => 'COMPLETED',
\STREAM_NOTIFY_RESOLVE => 'RESOLVE',
];
static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
$value = Utils::debugResource($value);
$ident = $request->getMethod() . ' ' . $request->getUri()->withFragment('');
$ident = $request->getMethod().' '.$request->getUri()->withFragment('');
self::addNotification(
$params,
static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
\fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
foreach (\array_filter($passed) as $i => $v) {
\fwrite($value, $args[$i] . ': "' . $v . '" ');
\fwrite($value, $args[$i].': "'.$v.'" ');
}
\fwrite($value, "\n");
}
@@ -577,7 +605,7 @@ class StreamHandler
} else {
$params['notification'] = self::callArray([
$params['notification'],
$notify
$notify,
]);
}
}

View File

@@ -58,7 +58,7 @@ class HandlerStack
/**
* @param (callable(RequestInterface, array): PromiseInterface)|null $handler Underlying HTTP handler.
*/
public function __construct(callable $handler = null)
public function __construct(?callable $handler = null)
{
$this->handler = $handler;
}
@@ -86,14 +86,14 @@ class HandlerStack
$stack = [];
if ($this->handler !== null) {
$stack[] = "0) Handler: " . $this->debugCallable($this->handler);
$stack[] = '0) Handler: '.$this->debugCallable($this->handler);
}
$result = '';
foreach (\array_reverse($this->stack) as $tuple) {
$depth++;
++$depth;
$str = "{$depth}) Name: '{$tuple[1]}', ";
$str .= "Function: " . $this->debugCallable($tuple[0]);
$str .= 'Function: '.$this->debugCallable($tuple[0]);
$result = "> {$str}\n{$result}";
$stack[] = $str;
}
@@ -122,7 +122,7 @@ class HandlerStack
*/
public function hasHandler(): bool
{
return $this->handler !== null ;
return $this->handler !== null;
}
/**
@@ -266,10 +266,10 @@ class HandlerStack
if (\is_array($fn)) {
return \is_string($fn[0])
? "callable({$fn[0]}::{$fn[1]})"
: "callable(['" . \get_class($fn[0]) . "', '{$fn[1]}'])";
: "callable(['".\get_class($fn[0])."', '{$fn[1]}'])";
}
/** @var object $fn */
return 'callable(' . \spl_object_hash($fn) . ')';
return 'callable('.\spl_object_hash($fn).')';
}
}

View File

@@ -40,11 +40,11 @@ class MessageFormatter implements MessageFormatterInterface
/**
* Apache Common Log Format.
*
* @link https://httpd.apache.org/docs/2.4/logs.html#common
* @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 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}';
@@ -90,9 +90,9 @@ class MessageFormatter implements MessageFormatterInterface
break;
case 'req_headers':
$result = \trim($request->getMethod()
. ' ' . $request->getRequestTarget())
. ' HTTP/' . $request->getProtocolVersion() . "\r\n"
. $this->headers($request);
.' '.$request->getRequestTarget())
.' HTTP/'.$request->getProtocolVersion()."\r\n"
.$this->headers($request);
break;
case 'res_headers':
$result = $response ?
@@ -101,7 +101,7 @@ class MessageFormatter implements MessageFormatterInterface
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
) . "\r\n" . $this->headers($response)
)."\r\n".$this->headers($response)
: 'NULL';
break;
case 'req_body':
@@ -177,6 +177,7 @@ class MessageFormatter implements MessageFormatterInterface
}
$cache[$matches[1]] = $result;
return $result;
},
$this->template
@@ -190,7 +191,7 @@ class MessageFormatter implements MessageFormatterInterface
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
$result .= $name . ': ' . \implode(', ', $values) . "\r\n";
$result .= $name.': '.\implode(', ', $values)."\r\n";
}
return \trim($result);

View File

@@ -34,10 +34,12 @@ final class Middleware
}
$cookieJar = $options['cookies'];
$request = $cookieJar->withCookieHeader($request);
return $handler($request, $options)
->then(
static function (ResponseInterface $response) use ($cookieJar, $request): ResponseInterface {
$cookieJar->extractCookies($request, $response);
return $response;
}
);
@@ -53,13 +55,14 @@ final class Middleware
*
* @return callable(callable): callable Returns a function that accepts the next handler.
*/
public static function httpErrors(BodySummarizerInterface $bodySummarizer = null): callable
public static function httpErrors(?BodySummarizerInterface $bodySummarizer = null): callable
{
return static function (callable $handler) use ($bodySummarizer): callable {
return static function ($request, array $options) use ($handler, $bodySummarizer) {
if (empty($options['http_errors'])) {
return $handler($request, $options);
}
return $handler($request, $options)->then(
static function (ResponseInterface $response) use ($request, $bodySummarizer) {
$code = $response->getStatusCode();
@@ -93,20 +96,22 @@ final class Middleware
return $handler($request, $options)->then(
static function ($value) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'request' => $request,
'response' => $value,
'error' => null,
'options' => $options
'error' => null,
'options' => $options,
];
return $value;
},
static function ($reason) use ($request, &$container, $options) {
$container[] = [
'request' => $request,
'request' => $request,
'response' => null,
'error' => $reason,
'options' => $options
'error' => $reason,
'options' => $options,
];
return P\Create::rejectionFor($reason);
}
);
@@ -127,7 +132,7 @@ final class Middleware
*
* @return callable Returns a function that accepts the next handler.
*/
public static function tap(callable $before = null, callable $after = null): callable
public static function tap(?callable $before = null, ?callable $after = null): callable
{
return static function (callable $handler) use ($before, $after): callable {
return static function (RequestInterface $request, array $options) use ($handler, $before, $after) {
@@ -138,6 +143,7 @@ final class Middleware
if ($after) {
$after($request, $options, $response);
}
return $response;
};
};
@@ -170,7 +176,7 @@ final class Middleware
*
* @return callable Returns a function that accepts the next handler.
*/
public static function retry(callable $decider, callable $delay = null): callable
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);
@@ -202,12 +208,14 @@ final class Middleware
static function ($response) use ($logger, $request, $formatter, $logLevel): ResponseInterface {
$message = $formatter->format($request, $response);
$logger->log($logLevel, $message);
return $response;
},
static function ($reason) use ($logger, $request, $formatter): PromiseInterface {
$response = $reason instanceof RequestException ? $reason->getResponse() : null;
$message = $formatter->format($request, $response, P\Create::exceptionFor($reason));
$logger->error($message);
return P\Create::rejectionFor($reason);
}
);

View File

@@ -76,14 +76,15 @@ class PrepareBodyMiddleware
$expect = $options['expect'] ?? null;
// Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
if ($expect === false || $request->getProtocolVersion() < 1.1) {
// Return if disabled or using HTTP/1.0
if ($expect === false || $request->getProtocolVersion() === '1.0') {
return;
}
// The expect header is unconditionally enabled
if ($expect === true) {
$modify['set_headers']['Expect'] = '100-Continue';
return;
}

View File

@@ -27,10 +27,10 @@ class RedirectMiddleware
* @var array
*/
public static $defaultSettings = [
'max' => 5,
'protocols' => ['http', 'https'],
'strict' => false,
'referer' => false,
'max' => 5,
'protocols' => ['http', 'https'],
'strict' => false,
'referer' => false,
'track_redirects' => false,
];
@@ -166,8 +166,8 @@ class RedirectMiddleware
// not forcing RFC compliance, but rather emulating what all browsers
// would do.
$statusCode = $response->getStatusCode();
if ($statusCode == 303 ||
($statusCode <= 302 && !$options['allow_redirects']['strict'])
if ($statusCode == 303
|| ($statusCode <= 302 && !$options['allow_redirects']['strict'])
) {
$safeMethods = ['GET', 'HEAD', 'OPTIONS'];
$requestMethod = $request->getMethod();

View File

@@ -5,9 +5,7 @@ namespace GuzzleHttp;
/**
* This class contains a list of built-in Guzzle request options.
*
* More documentation for each option can be found at http://guzzlephp.org/.
*
* @link http://docs.guzzlephp.org/en/v6/request-options.html
* @see https://docs.guzzlephp.org/en/latest/request-options.html
*/
final class RequestOptions
{
@@ -63,17 +61,29 @@ final class RequestOptions
* 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 \GuzzleHttp\Cookie\CookieJarInterface}.
* an instance of {@see Cookie\CookieJarInterface}.
*/
public const COOKIES = 'cookies';
/**
* connect_timeout: (float, default=0) Float describing the number of
* seconds to wait while trying to connect to a server. Use 0 to wait
* indefinitely (the default behavior).
* 300 seconds (the default behavior).
*/
public const CONNECT_TIMEOUT = 'connect_timeout';
/**
* crypto_method: (int) A value describing the minimum TLS protocol
* version to use.
*
* This setting must be set to one of the
* ``STREAM_CRYPTO_METHOD_TLS*_CLIENT`` constants. PHP 7.4 or higher is
* required in order to use TLS 1.3, and cURL 7.34.0 or higher is required
* in order to specify a crypto method, with cURL 7.52.0 or higher being
* required to use TLS 1.3.
*/
public const CRYPTO_METHOD = 'crypto_method';
/**
* debug: (bool|resource) Set to true or set to a PHP stream returned by
* fopen() enable debug output with the HTTP handler used to send a

View File

@@ -40,11 +40,11 @@ class RetryMiddleware
* and returns the number of
* milliseconds to delay.
*/
public function __construct(callable $decider, callable $nextHandler, callable $delay = null)
public function __construct(callable $decider, callable $nextHandler, ?callable $delay = null)
{
$this->decider = $decider;
$this->nextHandler = $nextHandler;
$this->delay = $delay ?: __CLASS__ . '::exponentialDelay';
$this->delay = $delay ?: __CLASS__.'::exponentialDelay';
}
/**
@@ -54,7 +54,7 @@ class RetryMiddleware
*/
public static function exponentialDelay(int $retries): int
{
return (int) \pow(2, $retries - 1) * 1000;
return (int) 2 ** ($retries - 1) * 1000;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
@@ -64,6 +64,7 @@ class RetryMiddleware
}
$fn = $this->nextHandler;
return $fn($request, $options)
->then(
$this->onFulfilled($request, $options),
@@ -85,6 +86,7 @@ class RetryMiddleware
)) {
return $value;
}
return $this->doRetry($request, $options, $value);
};
}
@@ -103,11 +105,12 @@ class RetryMiddleware
)) {
return P\Create::rejectionFor($reason);
}
return $this->doRetry($req, $options);
};
}
private function doRetry(RequestInterface $request, array $options, ResponseInterface $response = null): PromiseInterface
private function doRetry(RequestInterface $request, array $options, ?ResponseInterface $response = null): PromiseInterface
{
$options['delay'] = ($this->delay)(++$options['retries'], $response, $request);

View File

@@ -23,9 +23,9 @@ final class Utils
{
switch (\gettype($input)) {
case 'object':
return 'object(' . \get_class($input) . ')';
return 'object('.\get_class($input).')';
case 'array':
return 'array(' . \count($input) . ')';
return 'array('.\count($input).')';
default:
\ob_start();
\var_dump($input);
@@ -71,7 +71,7 @@ final class Utils
return \STDOUT;
}
return \GuzzleHttp\Psr7\Utils::tryFopen('php://output', 'w');
return Psr7\Utils::tryFopen('php://output', 'w');
}
/**
@@ -79,15 +79,15 @@ final class Utils
*
* The returned handler is not wrapped by any default middlewares.
*
* @throws \RuntimeException if no viable Handler is available.
*
* @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*/
public static function chooseHandler(): callable
{
$handler = null;
if (\defined('CURLOPT_CUSTOMREQUEST')) {
if (\defined('CURLOPT_CUSTOMREQUEST') && \function_exists('curl_version') && version_compare(curl_version()['version'], '7.21.2') >= 0) {
if (\function_exists('curl_multi_exec') && \function_exists('curl_exec')) {
$handler = Proxy::wrapSync(new CurlMultiHandler(), new CurlHandler());
} elseif (\function_exists('curl_exec')) {
@@ -176,14 +176,13 @@ No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
supply the path on disk to a certificate bundle to the 'verify' request
option: http://docs.guzzlephp.org/en/latest/clients.html#verify. If you do not
need a specific certificate bundle, then Mozilla provides a commonly used CA
bundle which can be downloaded here (provided by the maintainer of cURL):
https://curl.haxx.se/ca/cacert.pem. Once
you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP
ini setting to point to the path to the file, allowing you to omit the 'verify'
request option. See https://curl.haxx.se/docs/sslcerts.html for more
information.
option: https://docs.guzzlephp.org/en/latest/request-options.html#verify. If
you do not need a specific certificate bundle, then Mozilla provides a commonly
used CA bundle which can be downloaded here (provided by the maintainer of
cURL): https://curl.haxx.se/ca/cacert.pem. Once you have a CA bundle available
on disk, you can set the 'openssl.cafile' PHP ini setting to point to the path
to the file, allowing you to omit the 'verify' request option. See
https://curl.haxx.se/docs/sslcerts.html for more information.
EOT
);
}
@@ -247,8 +246,8 @@ EOT
}
// Special match if the area when prefixed with ".". Remove any
// existing leading "." and add a new leading ".".
$area = '.' . \ltrim($area, '.');
if (\substr($host, -(\strlen($area))) === $area) {
$area = '.'.\ltrim($area, '.');
if (\substr($host, -\strlen($area)) === $area) {
return true;
}
}
@@ -269,13 +268,13 @@ EOT
*
* @throws InvalidArgumentException if the JSON cannot be decoded.
*
* @link https://www.php.net/manual/en/function.json-decode.php
* @see https://www.php.net/manual/en/function.json-decode.php
*/
public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: ' . \json_last_error_msg());
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
return $data;
@@ -290,13 +289,13 @@ EOT
*
* @throws InvalidArgumentException if the JSON cannot be encoded.
*
* @link https://www.php.net/manual/en/function.json-encode.php
* @see https://www.php.net/manual/en/function.json-encode.php
*/
public static function jsonEncode($value, int $options = 0, int $depth = 512): string
{
$json = \json_encode($value, $options, $depth);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: ' . \json_last_error_msg());
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var string */
@@ -341,7 +340,7 @@ EOT
$errorMessage = 'IDN conversion failed';
if ($errors) {
$errorMessage .= ' (errors: ' . implode(', ', $errors) . ')';
$errorMessage .= ' (errors: '.implode(', ', $errors).')';
}
throw new InvalidArgumentException($errorMessage);

View File

@@ -50,10 +50,10 @@ function debug_resource($value = null)
*
* The returned handler is not wrapped by any default middlewares.
*
* @throws \RuntimeException if no viable Handler is available.
*
* @return callable(\Psr\Http\Message\RequestInterface, array): \GuzzleHttp\Promise\PromiseInterface Returns the best handler for the given system.
*
* @throws \RuntimeException if no viable Handler is available.
*
* @deprecated choose_handler will be removed in guzzlehttp/guzzle:8.0. Use Utils::chooseHandler instead.
*/
function choose_handler(): callable
@@ -141,7 +141,7 @@ function is_host_in_noproxy(string $host, array $noProxyArray): bool
*
* @throws Exception\InvalidArgumentException if the JSON cannot be decoded.
*
* @link https://www.php.net/manual/en/function.json-decode.php
* @see https://www.php.net/manual/en/function.json-decode.php
* @deprecated json_decode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonDecode instead.
*/
function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
@@ -158,7 +158,7 @@ function json_decode(string $json, bool $assoc = false, int $depth = 512, int $o
*
* @throws Exception\InvalidArgumentException if the JSON cannot be encoded.
*
* @link https://www.php.net/manual/en/function.json-encode.php
* @see https://www.php.net/manual/en/function.json-encode.php
* @deprecated json_encode will be removed in guzzlehttp/guzzle:8.0. Use Utils::jsonEncode instead.
*/
function json_encode($value, int $options = 0, int $depth = 512): string

View File

@@ -2,5 +2,5 @@
// Don't redefine the functions if included multiple times.
if (!\function_exists('GuzzleHttp\describe_type')) {
require __DIR__ . '/functions.php';
require __DIR__.'/functions.php';
}

View File

@@ -1,11 +1,57 @@
# CHANGELOG
## 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
@@ -13,6 +59,7 @@
- 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
@@ -24,12 +71,14 @@
- 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

View File

@@ -29,6 +29,21 @@ for a general introduction to promises.
`GuzzleHttp\Promise\Coroutine::of()`.
## Installation
```shell
composer require guzzlehttp/promises
```
## Version Guidance
| Version | Status | PHP Version |
|---------|---------------------|--------------|
| 1.x | Security fixes only | >=5.5,<8.3 |
| 2.x | Latest | >=7.2.5,<8.5 |
## Quick Start
A *promise* represents the eventual result of an asynchronous operation. The
@@ -430,8 +445,6 @@ $loop = React\EventLoop\Factory::create();
$loop->addPeriodicTimer(0, [$queue, 'run']);
```
*TODO*: Perhaps adding a `futureTick()` on each tick would be faster?
## Implementation Notes
@@ -501,8 +514,8 @@ $promise->resolve('foo');
A static API was first introduced in 1.4.0, in order to mitigate problems with
functions conflicting between global and local copies of the package. The
function API will be removed in 2.0.0. A migration table has been provided here
for your convenience:
function API was removed in 2.0.0. A migration table has been provided here for
your convenience:
| Original Function | Replacement Method |
|----------------|----------------|

View File

@@ -26,32 +26,32 @@
}
],
"require": {
"php": ">=5.5"
"php": "^7.2.5 || ^8.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^4.4 || ^5.1"
"bamarni/composer-bin-plugin": "^1.8.2",
"phpunit/phpunit": "^8.5.39 || ^9.6.20"
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
},
"files": ["src/functions_include.php"]
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Promise\\Tests\\": "tests/"
}
},
"scripts": {
"test": "vendor/bin/simple-phpunit",
"test-ci": "vendor/bin/simple-phpunit --coverage-text"
},
"extra": {
"branch-alias": {
"dev-master": "1.5-dev"
"bamarni-bin": {
"bin-links": true,
"forward-command": false
}
},
"config": {
"allow-plugins": {
"bamarni/composer-bin-plugin": true
},
"preferred-install": "dist",
"sort-packages": true
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -7,7 +9,7 @@ namespace GuzzleHttp\Promise;
*/
class AggregateException extends RejectionException
{
public function __construct($msg, array $reasons)
public function __construct(string $msg, array $reasons)
{
parent::__construct(
$reasons,

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**

View File

@@ -1,8 +1,9 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
use Exception;
use Generator;
use Throwable;
@@ -27,7 +28,7 @@ use Throwable;
* $value = (yield createPromise('a'));
* try {
* $value = (yield createPromise($value . 'b'));
* } catch (\Exception $e) {
* } catch (\Throwable $e) {
* // The promise was rejected.
* }
* yield $value . 'c';
@@ -40,7 +41,7 @@ use Throwable;
*
* @return Promise
*
* @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
* @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
*/
final class Coroutine implements PromiseInterface
{
@@ -62,15 +63,13 @@ final class Coroutine implements PromiseInterface
public function __construct(callable $generatorFn)
{
$this->generator = $generatorFn();
$this->result = new Promise(function () {
$this->result = new Promise(function (): void {
while (isset($this->currentPromise)) {
$this->currentPromise->wait();
}
});
try {
$this->nextCoroutine($this->generator->current());
} catch (\Exception $exception) {
$this->result->reject($exception);
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}
@@ -78,53 +77,51 @@ final class Coroutine implements PromiseInterface
/**
* Create a new coroutine.
*
* @return self
*/
public static function of(callable $generatorFn)
public static function of(callable $generatorFn): self
{
return new self($generatorFn);
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return $this->result->then($onFulfilled, $onRejected);
}
public function otherwise(callable $onRejected)
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->result->otherwise($onRejected);
}
public function wait($unwrap = true)
public function wait(bool $unwrap = true)
{
return $this->result->wait($unwrap);
}
public function getState()
public function getState(): string
{
return $this->result->getState();
}
public function resolve($value)
public function resolve($value): void
{
$this->result->resolve($value);
}
public function reject($reason)
public function reject($reason): void
{
$this->result->reject($reason);
}
public function cancel()
public function cancel(): void
{
$this->currentPromise->cancel();
$this->result->cancel();
}
private function nextCoroutine($yielded)
private function nextCoroutine($yielded): void
{
$this->currentPromise = Create::promiseFor($yielded)
->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
@@ -133,7 +130,7 @@ final class Coroutine implements PromiseInterface
/**
* @internal
*/
public function _handleSuccess($value)
public function _handleSuccess($value): void
{
unset($this->currentPromise);
try {
@@ -143,8 +140,6 @@ final class Coroutine implements PromiseInterface
} else {
$this->result->resolve($value);
}
} catch (Exception $exception) {
$this->result->reject($exception);
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}
@@ -153,15 +148,13 @@ final class Coroutine implements PromiseInterface
/**
* @internal
*/
public function _handleFailure($reason)
public function _handleFailure($reason): void
{
unset($this->currentPromise);
try {
$nextYield = $this->generator->throw(Create::exceptionFor($reason));
// The throw was caught, so keep iterating on the coroutine
$this->nextCoroutine($nextYield);
} catch (Exception $exception) {
$this->result->reject($exception);
} catch (Throwable $throwable) {
$this->result->reject($throwable);
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Create
@@ -8,10 +10,8 @@ final class Create
* Creates a promise for a value if the value is not a promise.
*
* @param mixed $value Promise or value.
*
* @return PromiseInterface
*/
public static function promiseFor($value)
public static function promiseFor($value): PromiseInterface
{
if ($value instanceof PromiseInterface) {
return $value;
@@ -23,6 +23,7 @@ final class Create
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
$promise = new Promise($wfn, $cfn);
$value->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise;
}
@@ -34,10 +35,8 @@ final class Create
* If the provided reason is a promise, then it is returned as-is.
*
* @param mixed $reason Promise or reason.
*
* @return PromiseInterface
*/
public static function rejectionFor($reason)
public static function rejectionFor($reason): PromiseInterface
{
if ($reason instanceof PromiseInterface) {
return $reason;
@@ -50,12 +49,10 @@ final class Create
* Create an exception for a rejected promise value.
*
* @param mixed $reason
*
* @return \Exception|\Throwable
*/
public static function exceptionFor($reason)
public static function exceptionFor($reason): \Throwable
{
if ($reason instanceof \Exception || $reason instanceof \Throwable) {
if ($reason instanceof \Throwable) {
return $reason;
}
@@ -66,10 +63,8 @@ final class Create
* Returns an iterator for the given value.
*
* @param mixed $value
*
* @return \Iterator
*/
public static function iterFor($value)
public static function iterFor($value): \Iterator
{
if ($value instanceof \Iterator) {
return $value;

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Each
@@ -17,20 +19,16 @@ final class Each
* index, and the aggregate promise. The callback can invoke any necessary
* side effects and choose to resolve or reject the aggregate if needed.
*
* @param mixed $iterable Iterator or array to iterate over.
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
* @param mixed $iterable Iterator or array to iterate over.
*/
public static function of(
$iterable,
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return (new EachPromise($iterable, [
'fulfilled' => $onFulfilled,
'rejected' => $onRejected
'rejected' => $onRejected,
]))->promise();
}
@@ -44,21 +42,17 @@ final class Each
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
*/
public static function ofLimit(
$iterable,
$concurrency,
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return (new EachPromise($iterable, [
'fulfilled' => $onFulfilled,
'rejected' => $onRejected,
'concurrency' => $concurrency
'fulfilled' => $onFulfilled,
'rejected' => $onRejected,
'concurrency' => $concurrency,
]))->promise();
}
@@ -69,20 +63,17 @@ final class Each
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
*
* @return PromiseInterface
*/
public static function ofLimitAll(
$iterable,
$concurrency,
callable $onFulfilled = null
) {
return each_limit(
?callable $onFulfilled = null
): PromiseInterface {
return self::ofLimit(
$iterable,
$concurrency,
$onFulfilled,
function ($reason, $idx, PromiseInterface $aggregate) {
function ($reason, $idx, PromiseInterface $aggregate): void {
$aggregate->reject($reason);
}
);

View File

@@ -1,10 +1,14 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Represents a promise that iterates over many promises and invokes
* side-effect functions in the process.
*
* @final
*/
class EachPromise implements PromisorInterface
{
@@ -69,7 +73,7 @@ class EachPromise implements PromisorInterface
}
/** @psalm-suppress InvalidNullableReturnType */
public function promise()
public function promise(): PromiseInterface
{
if ($this->aggregate) {
return $this->aggregate;
@@ -82,21 +86,18 @@ class EachPromise implements PromisorInterface
$this->refillPending();
} catch (\Throwable $e) {
$this->aggregate->reject($e);
} catch (\Exception $e) {
$this->aggregate->reject($e);
}
/**
* @psalm-suppress NullableReturnStatement
* @phpstan-ignore-next-line
*/
return $this->aggregate;
}
private function createPromise()
private function createPromise(): void
{
$this->mutex = false;
$this->aggregate = new Promise(function () {
$this->aggregate = new Promise(function (): void {
if ($this->checkIfFinished()) {
return;
}
@@ -113,7 +114,7 @@ class EachPromise implements PromisorInterface
});
// Clear the references when the promise is resolved.
$clearFn = function () {
$clearFn = function (): void {
$this->iterable = $this->concurrency = $this->pending = null;
$this->onFulfilled = $this->onRejected = null;
$this->nextPendingIndex = 0;
@@ -122,17 +123,19 @@ class EachPromise implements PromisorInterface
$this->aggregate->then($clearFn, $clearFn);
}
private function refillPending()
private function refillPending(): void
{
if (!$this->concurrency) {
// Add all pending promises.
while ($this->addPending() && $this->advanceIterator());
while ($this->addPending() && $this->advanceIterator()) {
}
return;
}
// Add only up to N pending promises.
$concurrency = is_callable($this->concurrency)
? call_user_func($this->concurrency, count($this->pending))
? ($this->concurrency)(count($this->pending))
: $this->concurrency;
$concurrency = max($concurrency - count($this->pending), 0);
// Concurrency may be set to 0 to disallow new promises.
@@ -147,10 +150,11 @@ class EachPromise implements PromisorInterface
// next value to yield until promise callbacks are called.
while (--$concurrency
&& $this->advanceIterator()
&& $this->addPending());
&& $this->addPending()) {
}
}
private function addPending()
private function addPending(): bool
{
if (!$this->iterable || !$this->iterable->valid()) {
return false;
@@ -164,10 +168,9 @@ class EachPromise implements PromisorInterface
$idx = $this->nextPendingIndex++;
$this->pending[$idx] = $promise->then(
function ($value) use ($idx, $key) {
function ($value) use ($idx, $key): void {
if ($this->onFulfilled) {
call_user_func(
$this->onFulfilled,
($this->onFulfilled)(
$value,
$key,
$this->aggregate
@@ -175,10 +178,9 @@ class EachPromise implements PromisorInterface
}
$this->step($idx);
},
function ($reason) use ($idx, $key) {
function ($reason) use ($idx, $key): void {
if ($this->onRejected) {
call_user_func(
$this->onRejected,
($this->onRejected)(
$reason,
$key,
$this->aggregate
@@ -191,7 +193,7 @@ class EachPromise implements PromisorInterface
return true;
}
private function advanceIterator()
private function advanceIterator(): bool
{
// Place a lock on the iterator so that we ensure to not recurse,
// preventing fatal generator errors.
@@ -204,19 +206,17 @@ class EachPromise implements PromisorInterface
try {
$this->iterable->next();
$this->mutex = false;
return true;
} catch (\Throwable $e) {
$this->aggregate->reject($e);
$this->mutex = false;
return false;
} catch (\Exception $e) {
$this->aggregate->reject($e);
$this->mutex = false;
return false;
}
}
private function step($idx)
private function step(int $idx): void
{
// If the promise was already resolved, then ignore this step.
if (Is::settled($this->aggregate)) {
@@ -234,11 +234,12 @@ class EachPromise implements PromisorInterface
}
}
private function checkIfFinished()
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;
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -7,11 +9,16 @@ namespace GuzzleHttp\Promise;
*
* Thenning off of this promise will invoke the onFulfilled callback
* immediately and ignore other callbacks.
*
* @final
*/
class FulfilledPromise implements PromiseInterface
{
private $value;
/**
* @param mixed $value
*/
public function __construct($value)
{
if (is_object($value) && method_exists($value, 'then')) {
@@ -24,9 +31,9 @@ class FulfilledPromise implements PromiseInterface
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
// Return itself if there is no onFulfilled function.
if (!$onFulfilled) {
return $this;
@@ -35,14 +42,12 @@ class FulfilledPromise implements PromiseInterface
$queue = Utils::queue();
$p = new Promise([$queue, 'run']);
$value = $this->value;
$queue->add(static function () use ($p, $value, $onFulfilled) {
$queue->add(static function () use ($p, $value, $onFulfilled): void {
if (Is::pending($p)) {
try {
$p->resolve($onFulfilled($value));
} catch (\Throwable $e) {
$p->reject($e);
} catch (\Exception $e) {
$p->reject($e);
}
}
});
@@ -50,34 +55,34 @@ class FulfilledPromise implements PromiseInterface
return $p;
}
public function otherwise(callable $onRejected)
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait($unwrap = true, $defaultDelivery = null)
public function wait(bool $unwrap = true)
{
return $unwrap ? $this->value : null;
}
public function getState()
public function getState(): string
{
return self::FULFILLED;
}
public function resolve($value)
public function resolve($value): void
{
if ($value !== $this->value) {
throw new \LogicException("Cannot resolve a fulfilled promise");
throw new \LogicException('Cannot resolve a fulfilled promise');
}
}
public function reject($reason)
public function reject($reason): void
{
throw new \LogicException("Cannot reject a fulfilled promise");
throw new \LogicException('Cannot reject a fulfilled promise');
}
public function cancel()
public function cancel(): void
{
// pass
}

View File

@@ -1,45 +1,39 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Is
{
/**
* Returns true if a promise is pending.
*
* @return bool
*/
public static function pending(PromiseInterface $promise)
public static function pending(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled or rejected.
*
* @return bool
*/
public static function settled(PromiseInterface $promise)
public static function settled(PromiseInterface $promise): bool
{
return $promise->getState() !== PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled.
*
* @return bool
*/
public static function fulfilled(PromiseInterface $promise)
public static function fulfilled(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::FULFILLED;
}
/**
* Returns true if a promise is rejected.
*
* @return bool
*/
public static function rejected(PromiseInterface $promise)
public static function rejected(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::REJECTED;
}

View File

@@ -1,11 +1,15 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Promises/A+ implementation that avoids recursion when possible.
*
* @link https://promisesaplus.com/
* @see https://promisesaplus.com/
*
* @final
*/
class Promise implements PromiseInterface
{
@@ -21,43 +25,46 @@ class Promise implements PromiseInterface
* @param callable $cancelFn Fn that when invoked cancels the promise.
*/
public function __construct(
callable $waitFn = null,
callable $cancelFn = null
?callable $waitFn = null,
?callable $cancelFn = null
) {
$this->waitFn = $waitFn;
$this->cancelFn = $cancelFn;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
if ($this->state === self::PENDING) {
$p = new Promise(null, [$this, 'cancel']);
$this->handlers[] = [$p, $onFulfilled, $onRejected];
$p->waitList = $this->waitList;
$p->waitList[] = $this;
return $p;
}
// Return a fulfilled promise and immediately invoke any callbacks.
if ($this->state === self::FULFILLED) {
$promise = Create::promiseFor($this->result);
return $onFulfilled ? $promise->then($onFulfilled) : $promise;
}
// It's either cancelled or rejected, so return a rejected promise
// and immediately invoke any callbacks.
$rejection = Create::rejectionFor($this->result);
return $onRejected ? $rejection->then(null, $onRejected) : $rejection;
}
public function otherwise(callable $onRejected)
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait($unwrap = true)
public function wait(bool $unwrap = true)
{
$this->waitIfPending();
@@ -73,12 +80,12 @@ class Promise implements PromiseInterface
}
}
public function getState()
public function getState(): string
{
return $this->state;
}
public function cancel()
public function cancel(): void
{
if ($this->state !== self::PENDING) {
return;
@@ -93,8 +100,6 @@ class Promise implements PromiseInterface
$fn();
} catch (\Throwable $e) {
$this->reject($e);
} catch (\Exception $e) {
$this->reject($e);
}
}
@@ -105,17 +110,17 @@ class Promise implements PromiseInterface
}
}
public function resolve($value)
public function resolve($value): void
{
$this->settle(self::FULFILLED, $value);
}
public function reject($reason)
public function reject($reason): void
{
$this->settle(self::REJECTED, $reason);
}
private function settle($state, $value)
private function settle(string $state, $value): void
{
if ($this->state !== self::PENDING) {
// Ignore calls with the same resolution.
@@ -148,7 +153,7 @@ class Promise implements PromiseInterface
if (!is_object($value) || !method_exists($value, 'then')) {
$id = $state === self::FULFILLED ? 1 : 2;
// It's a success, so resolve the handlers in the queue.
Utils::queue()->add(static function () use ($id, $value, $handlers) {
Utils::queue()->add(static function () use ($id, $value, $handlers): void {
foreach ($handlers as $handler) {
self::callHandler($id, $value, $handler);
}
@@ -159,12 +164,12 @@ class Promise implements PromiseInterface
} else {
// Resolve the handlers when the forwarded promise is resolved.
$value->then(
static function ($value) use ($handlers) {
static function ($value) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(1, $value, $handler);
}
},
static function ($reason) use ($handlers) {
static function ($reason) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(2, $reason, $handler);
}
@@ -180,7 +185,7 @@ class Promise implements PromiseInterface
* @param mixed $value Value to pass to the callback.
* @param array $handler Array of handler data (promise and callbacks).
*/
private static function callHandler($index, $value, array $handler)
private static function callHandler(int $index, $value, array $handler): void
{
/** @var PromiseInterface $promise */
$promise = $handler[0];
@@ -211,12 +216,10 @@ class Promise implements PromiseInterface
}
} catch (\Throwable $reason) {
$promise->reject($reason);
} catch (\Exception $reason) {
$promise->reject($reason);
}
}
private function waitIfPending()
private function waitIfPending(): void
{
if ($this->state !== self::PENDING) {
return;
@@ -227,9 +230,9 @@ class Promise implements PromiseInterface
} else {
// If there's no wait function, then reject the promise.
$this->reject('Cannot wait on a promise that has '
. 'no internal wait function. You must provide a wait '
. 'function when constructing the promise to be able to '
. 'wait on a promise.');
.'no internal wait function. You must provide a wait '
.'function when constructing the promise to be able to '
.'wait on a promise.');
}
Utils::queue()->run();
@@ -240,13 +243,13 @@ class Promise implements PromiseInterface
}
}
private function invokeWaitFn()
private function invokeWaitFn(): void
{
try {
$wfn = $this->waitFn;
$this->waitFn = null;
$wfn(true);
} catch (\Exception $reason) {
} catch (\Throwable $reason) {
if ($this->state === self::PENDING) {
// The promise has not been resolved yet, so reject the promise
// with the exception.
@@ -259,7 +262,7 @@ class Promise implements PromiseInterface
}
}
private function invokeWaitList()
private function invokeWaitList(): void
{
$waitList = $this->waitList;
$this->waitList = null;

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -9,13 +11,13 @@ namespace GuzzleHttp\Promise;
* which registers callbacks to receive either a promises eventual value or
* the reason why the promise cannot be fulfilled.
*
* @link https://promisesaplus.com/
* @see https://promisesaplus.com/
*/
interface PromiseInterface
{
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
public const PENDING = 'pending';
public const FULFILLED = 'fulfilled';
public const REJECTED = 'rejected';
/**
* Appends fulfillment and rejection handlers to the promise, and returns
@@ -23,13 +25,11 @@ interface PromiseInterface
*
* @param callable $onFulfilled Invoked when the promise fulfills.
* @param callable $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface
*/
public function then(
callable $onFulfilled = null,
callable $onRejected = null
);
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface;
/**
* Appends a rejection handler callback to the promise, and returns a new
@@ -38,20 +38,16 @@ interface PromiseInterface
* fulfilled.
*
* @param callable $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface
*/
public function otherwise(callable $onRejected);
public function otherwise(callable $onRejected): PromiseInterface;
/**
* Get the state of the promise ("pending", "rejected", or "fulfilled").
*
* The three states can be checked against the constants defined on
* PromiseInterface: PENDING, FULFILLED, and REJECTED.
*
* @return string
*/
public function getState();
public function getState(): string;
/**
* Resolve the promise with the given value.
@@ -60,7 +56,7 @@ interface PromiseInterface
*
* @throws \RuntimeException if the promise is already resolved.
*/
public function resolve($value);
public function resolve($value): void;
/**
* Reject the promise with the given reason.
@@ -69,14 +65,14 @@ interface PromiseInterface
*
* @throws \RuntimeException if the promise is already resolved.
*/
public function reject($reason);
public function reject($reason): void;
/**
* Cancels the promise if possible.
*
* @link https://github.com/promises-aplus/cancellation-spec/issues/7
* @see https://github.com/promises-aplus/cancellation-spec/issues/7
*/
public function cancel();
public function cancel(): void;
/**
* Waits until the promise completes if possible.
@@ -86,12 +82,10 @@ interface PromiseInterface
*
* If the promise cannot be waited on, then the promise will be rejected.
*
* @param bool $unwrap
*
* @return mixed
*
* @throws \LogicException if the promise has no wait function or if the
* promise does not settle after waiting.
*/
public function wait($unwrap = true);
public function wait(bool $unwrap = true);
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -9,8 +11,6 @@ interface PromisorInterface
{
/**
* Returns a promise.
*
* @return PromiseInterface
*/
public function promise();
public function promise(): PromiseInterface;
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -7,11 +9,16 @@ namespace GuzzleHttp\Promise;
*
* Thenning off of this promise will invoke the onRejected callback
* immediately and ignore other callbacks.
*
* @final
*/
class RejectedPromise implements PromiseInterface
{
private $reason;
/**
* @param mixed $reason
*/
public function __construct($reason)
{
if (is_object($reason) && method_exists($reason, 'then')) {
@@ -24,9 +31,9 @@ class RejectedPromise implements PromiseInterface
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
) {
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
// If there's no onRejected callback then just return self.
if (!$onRejected) {
return $this;
@@ -35,7 +42,7 @@ class RejectedPromise implements PromiseInterface
$queue = Utils::queue();
$reason = $this->reason;
$p = new Promise([$queue, 'run']);
$queue->add(static function () use ($p, $reason, $onRejected) {
$queue->add(static function () use ($p, $reason, $onRejected): void {
if (Is::pending($p)) {
try {
// Return a resolved promise if onRejected does not throw.
@@ -43,9 +50,6 @@ class RejectedPromise implements PromiseInterface
} catch (\Throwable $e) {
// onRejected threw, so return a rejected promise.
$p->reject($e);
} catch (\Exception $e) {
// onRejected threw, so return a rejected promise.
$p->reject($e);
}
}
});
@@ -53,12 +57,12 @@ class RejectedPromise implements PromiseInterface
return $p;
}
public function otherwise(callable $onRejected)
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait($unwrap = true, $defaultDelivery = null)
public function wait(bool $unwrap = true)
{
if ($unwrap) {
throw Create::exceptionFor($this->reason);
@@ -67,24 +71,24 @@ class RejectedPromise implements PromiseInterface
return null;
}
public function getState()
public function getState(): string
{
return self::REJECTED;
}
public function resolve($value)
public function resolve($value): void
{
throw new \LogicException("Cannot resolve a rejected promise");
throw new \LogicException('Cannot resolve a rejected promise');
}
public function reject($reason)
public function reject($reason): void
{
if ($reason !== $this->reason) {
throw new \LogicException("Cannot reject a rejected promise");
throw new \LogicException('Cannot reject a rejected promise');
}
}
public function cancel()
public function cancel(): void
{
// pass
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -13,24 +15,23 @@ class RejectionException extends \RuntimeException
private $reason;
/**
* @param mixed $reason Rejection reason.
* @param string $description Optional description
* @param mixed $reason Rejection reason.
* @param string|null $description Optional description.
*/
public function __construct($reason, $description = null)
public function __construct($reason, ?string $description = null)
{
$this->reason = $reason;
$message = 'The promise was rejected';
if ($description) {
$message .= ' with reason: ' . $description;
$message .= ' with reason: '.$description;
} elseif (is_string($reason)
|| (is_object($reason) && method_exists($reason, '__toString'))
) {
$message .= ' with reason: ' . $this->reason;
$message .= ' with reason: '.$this->reason;
} elseif ($reason instanceof \JsonSerializable) {
$message .= ' with reason: '
. json_encode($this->reason, JSON_PRETTY_PRINT);
$message .= ' with reason: '.json_encode($this->reason, JSON_PRETTY_PRINT);
}
parent::__construct($message);

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
@@ -10,16 +12,18 @@ namespace GuzzleHttp\Promise;
* by calling the `run()` function of the global task queue in an event loop.
*
* GuzzleHttp\Promise\Utils::queue()->run();
*
* @final
*/
class TaskQueue implements TaskQueueInterface
{
private $enableShutdown = true;
private $queue = [];
public function __construct($withShutdown = true)
public function __construct(bool $withShutdown = true)
{
if ($withShutdown) {
register_shutdown_function(function () {
register_shutdown_function(function (): void {
if ($this->enableShutdown) {
// Only run the tasks if an E_ERROR didn't occur.
$err = error_get_last();
@@ -31,17 +35,17 @@ class TaskQueue implements TaskQueueInterface
}
}
public function isEmpty()
public function isEmpty(): bool
{
return !$this->queue;
}
public function add(callable $task)
public function add(callable $task): void
{
$this->queue[] = $task;
}
public function run()
public function run(): void
{
while ($task = array_shift($this->queue)) {
/** @var callable $task */
@@ -60,7 +64,7 @@ class TaskQueue implements TaskQueueInterface
*
* Note: This shutdown will occur before any destructors are triggered.
*/
public function disableShutdown()
public function disableShutdown(): void
{
$this->enableShutdown = false;
}

View File

@@ -1,24 +1,24 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
interface TaskQueueInterface
{
/**
* Returns true if the queue is empty.
*
* @return bool
*/
public function isEmpty();
public function isEmpty(): bool;
/**
* Adds a task to the queue that will be executed the next time run is
* called.
*/
public function add(callable $task);
public function add(callable $task): void;
/**
* Execute all of the pending task in the queue.
*/
public function run();
public function run(): void;
}

View File

@@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Utils
@@ -17,11 +19,9 @@ final class Utils
* }
* </code>
*
* @param TaskQueueInterface $assign Optionally specify a new queue instance.
*
* @return TaskQueueInterface
* @param TaskQueueInterface|null $assign Optionally specify a new queue instance.
*/
public static function queue(TaskQueueInterface $assign = null)
public static function queue(?TaskQueueInterface $assign = null): TaskQueueInterface
{
static $queue;
@@ -39,22 +39,18 @@ final class Utils
* returns a promise that is fulfilled or rejected with the result.
*
* @param callable $task Task function to run.
*
* @return PromiseInterface
*/
public static function task(callable $task)
public static function task(callable $task): PromiseInterface
{
$queue = self::queue();
$promise = new Promise([$queue, 'run']);
$queue->add(function () use ($task, $promise) {
$queue->add(function () use ($task, $promise): void {
try {
if (Is::pending($promise)) {
$promise->resolve($task());
}
} catch (\Throwable $e) {
$promise->reject($e);
} catch (\Exception $e) {
$promise->reject($e);
}
});
@@ -72,22 +68,18 @@ final class Utils
* key mapping to the rejection reason of the promise.
*
* @param PromiseInterface $promise Promise or value.
*
* @return array
*/
public static function inspect(PromiseInterface $promise)
public static function inspect(PromiseInterface $promise): array
{
try {
return [
'state' => PromiseInterface::FULFILLED,
'value' => $promise->wait()
'value' => $promise->wait(),
];
} catch (RejectionException $e) {
return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()];
} catch (\Throwable $e) {
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
} catch (\Exception $e) {
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
}
}
@@ -100,14 +92,12 @@ final class Utils
* @see inspect for the inspection state array format.
*
* @param PromiseInterface[] $promises Traversable of promises to wait upon.
*
* @return array
*/
public static function inspectAll($promises)
public static function inspectAll($promises): array
{
$results = [];
foreach ($promises as $key => $promise) {
$results[$key] = inspect($promise);
$results[$key] = self::inspect($promise);
}
return $results;
@@ -122,12 +112,9 @@ final class Utils
*
* @param iterable<PromiseInterface> $promises Iterable of PromiseInterface objects to wait on.
*
* @return array
*
* @throws \Exception on error
* @throws \Throwable on error in PHP >=7
* @throws \Throwable on error
*/
public static function unwrap($promises)
public static function unwrap($promises): array
{
$results = [];
foreach ($promises as $key => $promise) {
@@ -147,22 +134,21 @@ final class Utils
*
* @param mixed $promises Promises or values.
* @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
*
* @return PromiseInterface
*/
public static function all($promises, $recursive = false)
public static function all($promises, bool $recursive = false): PromiseInterface
{
$results = [];
$promise = Each::of(
$promises,
function ($value, $idx) use (&$results) {
function ($value, $idx) use (&$results): void {
$results[$idx] = $value;
},
function ($reason, $idx, Promise $aggregate) {
function ($reason, $idx, Promise $aggregate): void {
$aggregate->reject($reason);
}
)->then(function () use (&$results) {
ksort($results);
return $results;
});
@@ -173,6 +159,7 @@ final class Utils
return self::all($promises, $recursive);
}
}
return $results;
});
}
@@ -193,17 +180,15 @@ final class Utils
*
* @param int $count Total number of promises.
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*/
public static function some($count, $promises)
public static function some(int $count, $promises): PromiseInterface
{
$results = [];
$rejections = [];
return Each::of(
$promises,
function ($value, $idx, PromiseInterface $p) use (&$results, $count) {
function ($value, $idx, PromiseInterface $p) use (&$results, $count): void {
if (Is::settled($p)) {
return;
}
@@ -212,7 +197,7 @@ final class Utils
$p->resolve(null);
}
},
function ($reason) use (&$rejections) {
function ($reason) use (&$rejections): void {
$rejections[] = $reason;
}
)->then(
@@ -224,6 +209,7 @@ final class Utils
);
}
ksort($results);
return array_values($results);
}
);
@@ -234,10 +220,8 @@ final class Utils
* fulfillment value is not an array of 1 but the value directly.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*/
public static function any($promises)
public static function any($promises): PromiseInterface
{
return self::some(1, $promises)->then(function ($values) {
return $values[0];
@@ -253,23 +237,22 @@ final class Utils
* @see inspect for the inspection state array format.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*/
public static function settle($promises)
public static function settle($promises): PromiseInterface
{
$results = [];
return Each::of(
$promises,
function ($value, $idx) use (&$results) {
function ($value, $idx) use (&$results): void {
$results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
},
function ($reason, $idx) use (&$results) {
function ($reason, $idx) use (&$results): void {
$results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
}
)->then(function () use (&$results) {
ksort($results);
return $results;
});
}

View File

@@ -1,363 +0,0 @@
<?php
namespace GuzzleHttp\Promise;
/**
* Get the global task queue used for promise resolution.
*
* This task queue MUST be run in an event loop in order for promises to be
* settled asynchronously. It will be automatically run when synchronously
* waiting on a promise.
*
* <code>
* while ($eventLoop->isRunning()) {
* GuzzleHttp\Promise\queue()->run();
* }
* </code>
*
* @param TaskQueueInterface $assign Optionally specify a new queue instance.
*
* @return TaskQueueInterface
*
* @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead.
*/
function queue(TaskQueueInterface $assign = null)
{
return Utils::queue($assign);
}
/**
* Adds a function to run in the task queue when it is next `run()` and returns
* a promise that is fulfilled or rejected with the result.
*
* @param callable $task Task function to run.
*
* @return PromiseInterface
*
* @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead.
*/
function task(callable $task)
{
return Utils::task($task);
}
/**
* Creates a promise for a value if the value is not a promise.
*
* @param mixed $value Promise or value.
*
* @return PromiseInterface
*
* @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead.
*/
function promise_for($value)
{
return Create::promiseFor($value);
}
/**
* Creates a rejected promise for a reason if the reason is not a promise. If
* the provided reason is a promise, then it is returned as-is.
*
* @param mixed $reason Promise or reason.
*
* @return PromiseInterface
*
* @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead.
*/
function rejection_for($reason)
{
return Create::rejectionFor($reason);
}
/**
* Create an exception for a rejected promise value.
*
* @param mixed $reason
*
* @return \Exception|\Throwable
*
* @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead.
*/
function exception_for($reason)
{
return Create::exceptionFor($reason);
}
/**
* Returns an iterator for the given value.
*
* @param mixed $value
*
* @return \Iterator
*
* @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead.
*/
function iter_for($value)
{
return Create::iterFor($value);
}
/**
* Synchronously waits on a promise to resolve and returns an inspection state
* array.
*
* Returns a state associative array containing a "state" key mapping to a
* valid promise state. If the state of the promise is "fulfilled", the array
* will contain a "value" key mapping to the fulfilled value of the promise. If
* the promise is rejected, the array will contain a "reason" key mapping to
* the rejection reason of the promise.
*
* @param PromiseInterface $promise Promise or value.
*
* @return array
*
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead.
*/
function inspect(PromiseInterface $promise)
{
return Utils::inspect($promise);
}
/**
* Waits on all of the provided promises, but does not unwrap rejected promises
* as thrown exception.
*
* Returns an array of inspection state arrays.
*
* @see inspect for the inspection state array format.
*
* @param PromiseInterface[] $promises Traversable of promises to wait upon.
*
* @return array
*
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead.
*/
function inspect_all($promises)
{
return Utils::inspectAll($promises);
}
/**
* Waits on all of the provided promises and returns the fulfilled values.
*
* Returns an array that contains the value of each promise (in the same order
* the promises were provided). An exception is thrown if any of the promises
* are rejected.
*
* @param iterable<PromiseInterface> $promises Iterable of PromiseInterface objects to wait on.
*
* @return array
*
* @throws \Exception on error
* @throws \Throwable on error in PHP >=7
*
* @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead.
*/
function unwrap($promises)
{
return Utils::unwrap($promises);
}
/**
* Given an array of promises, return a promise that is fulfilled when all the
* items in the array are fulfilled.
*
* The promise's fulfillment value is an array with fulfillment values at
* respective positions to the original array. If any promise in the array
* rejects, the returned promise is rejected with the rejection reason.
*
* @param mixed $promises Promises or values.
* @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
*
* @return PromiseInterface
*
* @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead.
*/
function all($promises, $recursive = false)
{
return Utils::all($promises, $recursive);
}
/**
* Initiate a competitive race between multiple promises or values (values will
* become immediately fulfilled promises).
*
* When count amount of promises have been fulfilled, the returned promise is
* fulfilled with an array that contains the fulfillment values of the winners
* in order of resolution.
*
* This promise is rejected with a {@see AggregateException} if the number of
* fulfilled promises is less than the desired $count.
*
* @param int $count Total number of promises.
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead.
*/
function some($count, $promises)
{
return Utils::some($count, $promises);
}
/**
* Like some(), with 1 as count. However, if the promise fulfills, the
* fulfillment value is not an array of 1 but the value directly.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead.
*/
function any($promises)
{
return Utils::any($promises);
}
/**
* Returns a promise that is fulfilled when all of the provided promises have
* been fulfilled or rejected.
*
* The returned promise is fulfilled with an array of inspection state arrays.
*
* @see inspect for the inspection state array format.
*
* @param mixed $promises Promises or values.
*
* @return PromiseInterface
*
* @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead.
*/
function settle($promises)
{
return Utils::settle($promises);
}
/**
* 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, iterator index,
* 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, iterator index,
* and the aggregate promise. The callback can invoke any necessary side
* effects and choose to resolve or reject the aggregate if needed.
*
* @param mixed $iterable Iterator or array to iterate over.
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
*
* @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead.
*/
function each(
$iterable,
callable $onFulfilled = null,
callable $onRejected = null
) {
return Each::of($iterable, $onFulfilled, $onRejected);
}
/**
* Like each, 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
* dynamic a concurrency size.
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
* @param callable $onRejected
*
* @return PromiseInterface
*
* @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead.
*/
function each_limit(
$iterable,
$concurrency,
callable $onFulfilled = null,
callable $onRejected = null
) {
return Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected);
}
/**
* Like each_limit, but ensures that no promise in the given $iterable argument
* is rejected. If any promise is rejected, then the aggregate promise is
* rejected with the encountered rejection.
*
* @param mixed $iterable
* @param int|callable $concurrency
* @param callable $onFulfilled
*
* @return PromiseInterface
*
* @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead.
*/
function each_limit_all(
$iterable,
$concurrency,
callable $onFulfilled = null
) {
return Each::ofLimitAll($iterable, $concurrency, $onFulfilled);
}
/**
* Returns true if a promise is fulfilled.
*
* @return bool
*
* @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead.
*/
function is_fulfilled(PromiseInterface $promise)
{
return Is::fulfilled($promise);
}
/**
* Returns true if a promise is rejected.
*
* @return bool
*
* @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead.
*/
function is_rejected(PromiseInterface $promise)
{
return Is::rejected($promise);
}
/**
* Returns true if a promise is fulfilled or rejected.
*
* @return bool
*
* @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead.
*/
function is_settled(PromiseInterface $promise)
{
return Is::settled($promise);
}
/**
* Create a new coroutine.
*
* @see Coroutine
*
* @return PromiseInterface
*
* @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead.
*/
function coroutine(callable $generatorFn)
{
return Coroutine::of($generatorFn);
}

View File

@@ -1,6 +0,0 @@
<?php
// Don't redefine the functions if included multiple times.
if (!function_exists('GuzzleHttp\Promise\promise_for')) {
require __DIR__ . '/functions.php';
}

View File

@@ -5,7 +5,76 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## Unreleased
## 2.7.0 - 2024-07-18
### Added
- Add `Utils::redactUserInfo()` method
- Add ability to encode bools as ints in `Query::build`
## 2.6.3 - 2024-07-18
### Fixed
- Make `StreamWrapper::stream_stat()` return `false` if inner stream's size is `null`
### Changed
- PHP 8.4 support
## 2.6.2 - 2023-12-03
### Fixed
- Fixed another issue with the fact that PHP transforms numeric strings in array keys to ints
### Changed
- Updated links in docs to their canonical versions
- Replaced `call_user_func*` with native calls
## 2.6.1 - 2023-08-27
### Fixed
- Properly handle the fact that PHP transforms numeric strings in array keys to ints
## 2.6.0 - 2023-08-03
### Changed
- Updated the mime type map to add some new entries, fix a couple of invalid entries, and remove an invalid entry
- Fallback to `application/octet-stream` if we are unable to guess the content type for a multipart file upload
## 2.5.1 - 2023-08-03
### Fixed
- Corrected mime type for `.acc` files to `audio/aac`
### Changed
- PHP 8.3 support
## 2.5.0 - 2023-04-17
### Changed
- Adjusted `psr/http-message` version constraint to `^1.1 || ^2.0`
## 2.4.5 - 2023-04-17
### Fixed
- Prevent possible warnings on unset variables in `ServerRequest::normalizeNestedFileSpec`
- Fixed `Message::bodySummary` when `preg_match` fails
- Fixed header validation issue
## 2.4.4 - 2023-03-09
### Changed
- Removed the need for `AllowDynamicProperties` in `LazyOpenStream`
## 2.4.3 - 2022-10-26

View File

@@ -8,12 +8,26 @@ functionality like query string parsing.
![Static analysis](https://github.com/guzzle/psr7/workflows/Static%20analysis/badge.svg)
# Stream implementation
## Features
This package comes with a number of stream implementations and stream
decorators.
## Installation
```shell
composer require guzzlehttp/psr7
```
## Version Guidance
| Version | Status | PHP Version |
|---------|---------------------|--------------|
| 1.x | EOL (2024-06-30) | >=5.4,<8.2 |
| 2.x | Latest | >=7.2.5,<8.5 |
## AppendStream
`GuzzleHttp\Psr7\AppendStream`
@@ -245,6 +259,8 @@ class EofCallbackStream implements StreamInterface
private $callback;
private $stream;
public function __construct(StreamInterface $stream, callable $cb)
{
$this->stream = $stream;
@@ -257,7 +273,7 @@ class EofCallbackStream implements StreamInterface
// Invoke the callback when EOF is hit.
if ($this->eof()) {
call_user_func($this->callback);
($this->callback)();
}
return $result;
@@ -420,7 +436,7 @@ will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
## `GuzzleHttp\Psr7\Query::build`
`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string`
`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string`
Build a query string from an array of key value pairs.
@@ -482,11 +498,18 @@ a message.
## `GuzzleHttp\Psr7\Utils::readLine`
`public static function readLine(StreamInterface $stream, int $maxLength = null): string`
`public static function readLine(StreamInterface $stream, ?int $maxLength = null): string`
Read a line from the stream up to the maximum allowed buffer length.
## `GuzzleHttp\Psr7\Utils::redactUserInfo`
`public static function redactUserInfo(UriInterface $uri): UriInterface`
Redact the password in the user info part of a URI.
## `GuzzleHttp\Psr7\Utils::streamFor`
`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
@@ -621,7 +644,7 @@ this library also provides additional functionality when working with URIs as st
An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference.
An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI,
the base URI. Relative references can be divided into several forms according to
[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2):
[RFC 3986 Section 4.2](https://datatracker.ietf.org/doc/html/rfc3986#section-4.2):
- network-path references, e.g. `//example.com/path`
- absolute-path references, e.g. `/path`
@@ -658,7 +681,7 @@ termed a relative-path reference.
### `GuzzleHttp\Psr7\Uri::isSameDocumentReference`
`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool`
`public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool`
Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its
fragment component, identical to the base URI. When no base URI is given, only an empty URI reference
@@ -680,8 +703,8 @@ or the standard port. This method can be used independently of the implementatio
`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string`
Composes a URI reference string from its various components according to
[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called
manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
[RFC 3986 Section 5.3](https://datatracker.ietf.org/doc/html/rfc3986#section-5.3). Usually this method does not need
to be called manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`.
### `GuzzleHttp\Psr7\Uri::fromParts`
@@ -725,8 +748,8 @@ Determines if a modified URL should be considered cross-origin with respect to a
## Reference Resolution
`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according
to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers
do when resolving a link in a website based on the current request URI.
to [RFC 3986 Section 5](https://datatracker.ietf.org/doc/html/rfc3986#section-5). This is for example also what web
browsers do when resolving a link in a website based on the current request URI.
### `GuzzleHttp\Psr7\UriResolver::resolve`
@@ -739,7 +762,7 @@ Converts the relative URI into a new URI that is resolved against the base URI.
`public static function removeDotSegments(string $path): string`
Removes dot segments from a path and returns the new path according to
[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4).
[RFC 3986 Section 5.2.4](https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4).
### `GuzzleHttp\Psr7\UriResolver::relativize`
@@ -765,7 +788,7 @@ echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // pr
## Normalization and Comparison
`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to
[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6).
[RFC 3986 Section 6](https://datatracker.ietf.org/doc/html/rfc3986#section-6).
### `GuzzleHttp\Psr7\UriNormalizer::normalize`
@@ -847,14 +870,6 @@ This of course assumes they will be resolved against the same base URI. If this
equivalence or difference of relative references does not mean anything.
## Version Guidance
| Version | Status | PHP Version |
|---------|----------------|------------------|
| 1.x | Security fixes | >=5.4,<8.1 |
| 2.x | Latest | ^7.2.5 \|\| ^8.0 |
## Security
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information.

View File

@@ -52,7 +52,7 @@
"require": {
"php": "^7.2.5 || ^8.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0",
"psr/http-message": "^1.1 || ^2.0",
"ralouphie/getallheaders": "^3.0"
},
"provide": {
@@ -60,9 +60,9 @@
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"bamarni/composer-bin-plugin": "^1.8.1",
"http-interop/http-factory-tests": "^0.9",
"phpunit/phpunit": "^8.5.29 || ^9.5.23"
"bamarni/composer-bin-plugin": "^1.8.2",
"http-interop/http-factory-tests": "0.9.0",
"phpunit/phpunit": "^8.5.39 || ^9.6.20"
},
"suggest": {
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
@@ -81,9 +81,6 @@
"bamarni-bin": {
"bin-links": true,
"forward-command": false
},
"branch-alias": {
"dev-master": "2.4-dev"
}
},
"config": {

View File

@@ -40,12 +40,14 @@ final class AppendStream implements StreamInterface
{
try {
$this->rewind();
return $this->getContents();
} catch (\Throwable $e) {
if (\PHP_VERSION_ID >= 70400) {
throw $e;
}
trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
return '';
}
}
@@ -138,9 +140,9 @@ final class AppendStream implements StreamInterface
public function eof(): bool
{
return !$this->streams ||
($this->current >= count($this->streams) - 1 &&
$this->streams[$this->current]->eof());
return !$this->streams
|| ($this->current >= count($this->streams) - 1
&& $this->streams[$this->current]->eof());
}
public function rewind(): void
@@ -167,7 +169,7 @@ final class AppendStream implements StreamInterface
$stream->rewind();
} catch (\Exception $e) {
throw new \RuntimeException('Unable to seek stream '
. $i . ' of the AppendStream', 0, $e);
.$i.' of the AppendStream', 0, $e);
}
}
@@ -197,7 +199,7 @@ final class AppendStream implements StreamInterface
if ($this->current === $total) {
break;
}
$this->current++;
++$this->current;
}
$result = $this->streams[$this->current]->read($remaining);
@@ -237,8 +239,6 @@ final class AppendStream implements StreamInterface
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)

View File

@@ -134,8 +134,6 @@ final class BufferStream implements StreamInterface
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)

View File

@@ -33,7 +33,7 @@ final class CachingStream implements StreamInterface
*/
public function __construct(
StreamInterface $stream,
StreamInterface $target = null
?StreamInterface $target = null
) {
$this->remoteStream = $stream;
$this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+'));

View File

@@ -18,7 +18,7 @@ final class FnStream implements StreamInterface
private const SLOTS = [
'__toString', 'close', 'detach', 'rewind',
'getSize', 'tell', 'eof', 'isSeekable', 'seek', 'isWritable', 'write',
'isReadable', 'read', 'getContents', 'getMetadata'
'isReadable', 'read', 'getContents', 'getMetadata',
];
/** @var array<string, callable> */
@@ -33,7 +33,7 @@ final class FnStream implements StreamInterface
// Create the functions on the class
foreach ($methods as $name => $fn) {
$this->{'_fn_' . $name} = $fn;
$this->{'_fn_'.$name} = $fn;
}
}
@@ -45,7 +45,7 @@ final class FnStream implements StreamInterface
public function __get(string $name): void
{
throw new \BadMethodCallException(str_replace('_fn_', '', $name)
. '() is not implemented in the FnStream');
.'() is not implemented in the FnStream');
}
/**
@@ -54,7 +54,7 @@ final class FnStream implements StreamInterface
public function __destruct()
{
if (isset($this->_fn_close)) {
call_user_func($this->_fn_close);
($this->_fn_close)();
}
}
@@ -93,88 +93,88 @@ final class FnStream implements StreamInterface
public function __toString(): string
{
try {
return call_user_func($this->_fn___toString);
/** @var string */
return ($this->_fn___toString)();
} catch (\Throwable $e) {
if (\PHP_VERSION_ID >= 70400) {
throw $e;
}
trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
return '';
}
}
public function close(): void
{
call_user_func($this->_fn_close);
($this->_fn_close)();
}
public function detach()
{
return call_user_func($this->_fn_detach);
return ($this->_fn_detach)();
}
public function getSize(): ?int
{
return call_user_func($this->_fn_getSize);
return ($this->_fn_getSize)();
}
public function tell(): int
{
return call_user_func($this->_fn_tell);
return ($this->_fn_tell)();
}
public function eof(): bool
{
return call_user_func($this->_fn_eof);
return ($this->_fn_eof)();
}
public function isSeekable(): bool
{
return call_user_func($this->_fn_isSeekable);
return ($this->_fn_isSeekable)();
}
public function rewind(): void
{
call_user_func($this->_fn_rewind);
($this->_fn_rewind)();
}
public function seek($offset, $whence = SEEK_SET): void
{
call_user_func($this->_fn_seek, $offset, $whence);
($this->_fn_seek)($offset, $whence);
}
public function isWritable(): bool
{
return call_user_func($this->_fn_isWritable);
return ($this->_fn_isWritable)();
}
public function write($string): int
{
return call_user_func($this->_fn_write, $string);
return ($this->_fn_write)($string);
}
public function isReadable(): bool
{
return call_user_func($this->_fn_isReadable);
return ($this->_fn_isReadable)();
}
public function read($length): string
{
return call_user_func($this->_fn_read, $length);
return ($this->_fn_read)($length);
}
public function getContents(): string
{
return call_user_func($this->_fn_getContents);
return ($this->_fn_getContents)();
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)
{
return call_user_func($this->_fn_getMetadata, $key);
return ($this->_fn_getMetadata)($key);
}
}

View File

@@ -22,7 +22,7 @@ final class Header
foreach ((array) $header as $value) {
foreach (self::splitList($value) as $val) {
$part = [];
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) ?: [] as $kvp) {
if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
$m = $matches[0];
if (isset($m[1])) {
@@ -89,7 +89,7 @@ final class Header
$v = '';
$isQuoted = false;
$isEscaped = false;
for ($i = 0, $max = \strlen($value); $i < $max; $i++) {
for ($i = 0, $max = \strlen($value); $i < $max; ++$i) {
if ($isEscaped) {
$v .= $value[$i];
$isEscaped = false;

View File

@@ -23,20 +23,14 @@ use Psr\Http\Message\UriInterface;
* Note: in consuming code it is recommended to require the implemented interfaces
* and inject the instance of this class multiple times.
*/
final class HttpFactory implements
RequestFactoryInterface,
ResponseFactoryInterface,
ServerRequestFactoryInterface,
StreamFactoryInterface,
UploadedFileFactoryInterface,
UriFactoryInterface
final class HttpFactory implements RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
{
public function createUploadedFile(
StreamInterface $stream,
int $size = null,
?int $size = null,
int $error = \UPLOAD_ERR_OK,
string $clientFilename = null,
string $clientMediaType = null
?string $clientFilename = null,
?string $clientMediaType = null
): UploadedFileInterface {
if ($size === null) {
$size = $stream->getSize();

View File

@@ -13,9 +13,9 @@ use Psr\Http\Message\StreamInterface;
* then appends the zlib.inflate filter. The stream is then converted back
* to a Guzzle stream resource to be used as a Guzzle stream.
*
* @link http://tools.ietf.org/html/rfc1950
* @link http://tools.ietf.org/html/rfc1952
* @link http://php.net/manual/en/filters.compression.php
* @see https://datatracker.ietf.org/doc/html/rfc1950
* @see https://datatracker.ietf.org/doc/html/rfc1952
* @see https://www.php.net/manual/en/filters.compression.php
*/
final class InflateStream implements StreamInterface
{
@@ -28,7 +28,7 @@ final class InflateStream implements StreamInterface
{
$resource = StreamWrapper::getResource($stream);
// Specify window=15+32, so zlib will use header detection to both gzip (with header) and zlib data
// See http://www.zlib.net/manual.html#Advanced definition of inflateInit2
// See https://www.zlib.net/manual.html#Advanced definition of inflateInit2
// "Add 32 to windowBits to enable zlib and gzip decoding with automatic header detection"
// Default window size is 15.
stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15 + 32]);

View File

@@ -10,7 +10,6 @@ use Psr\Http\Message\StreamInterface;
* Lazily reads or writes to a file that is opened only after an IO operation
* take place on the stream.
*/
#[\AllowDynamicProperties]
final class LazyOpenStream implements StreamInterface
{
use StreamDecoratorTrait;
@@ -21,6 +20,11 @@ final class LazyOpenStream implements StreamInterface
/** @var string */
private $mode;
/**
* @var StreamInterface
*/
private $stream;
/**
* @param string $filename File to lazily open
* @param string $mode fopen mode to use when opening the stream
@@ -29,6 +33,10 @@ final class LazyOpenStream implements StreamInterface
{
$this->filename = $filename;
$this->mode = $mode;
// unsetting the property forces the first access to go through
// __get().
unset($this->stream);
}
/**

View File

@@ -18,31 +18,31 @@ final class Message
public static function toString(MessageInterface $message): string
{
if ($message instanceof RequestInterface) {
$msg = trim($message->getMethod() . ' '
. $message->getRequestTarget())
. ' HTTP/' . $message->getProtocolVersion();
$msg = trim($message->getMethod().' '
.$message->getRequestTarget())
.' HTTP/'.$message->getProtocolVersion();
if (!$message->hasHeader('host')) {
$msg .= "\r\nHost: " . $message->getUri()->getHost();
$msg .= "\r\nHost: ".$message->getUri()->getHost();
}
} elseif ($message instanceof ResponseInterface) {
$msg = 'HTTP/' . $message->getProtocolVersion() . ' '
. $message->getStatusCode() . ' '
. $message->getReasonPhrase();
$msg = 'HTTP/'.$message->getProtocolVersion().' '
.$message->getStatusCode().' '
.$message->getReasonPhrase();
} else {
throw new \InvalidArgumentException('Unknown message type');
}
foreach ($message->getHeaders() as $name => $values) {
if (strtolower($name) === 'set-cookie') {
if (is_string($name) && strtolower($name) === 'set-cookie') {
foreach ($values as $value) {
$msg .= "\r\n{$name}: " . $value;
$msg .= "\r\n{$name}: ".$value;
}
} else {
$msg .= "\r\n{$name}: " . implode(', ', $values);
$msg .= "\r\n{$name}: ".implode(', ', $values);
}
}
return "{$msg}\r\n\r\n" . $message->getBody();
return "{$msg}\r\n\r\n".$message->getBody();
}
/**
@@ -77,7 +77,7 @@ final class Message
// Matches any printable character, including unicode characters:
// letters, marks, numbers, punctuation, spacing, and separators.
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) {
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary) !== 0) {
return null;
}
@@ -146,7 +146,7 @@ final class Message
// If these aren't the same, then one line didn't match and there's an invalid header.
if ($count !== substr_count($rawHeaders, "\n")) {
// Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
// Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
}
@@ -190,7 +190,7 @@ final class Message
$host = $headers[reset($hostKey)][0];
$scheme = substr($host, -4) === ':443' ? 'https' : 'http';
return $scheme . '://' . $host . '/' . ltrim($path, '/');
return $scheme.'://'.$host.'/'.ltrim($path, '/');
}
/**
@@ -227,11 +227,11 @@ final class Message
public static function parseResponse(string $message): ResponseInterface
{
$data = self::parseMessage($message);
// According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
// between status-code and reason-phrase is required. But browsers accept
// responses without space and reason as well.
// According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2
// the space between status-code and reason-phrase is required. But
// browsers accept responses without space and reason as well.
if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
throw new \InvalidArgumentException('Invalid response string: '.$data['start-line']);
}
$parts = explode(' ', $data['start-line'], 3);

View File

@@ -12,11 +12,11 @@ use Psr\Http\Message\StreamInterface;
*/
trait MessageTrait
{
/** @var array<string, string[]> Map of all registered headers, as original name => array of values */
/** @var string[][] Map of all registered headers, as original name => array of values */
private $headers = [];
/** @var array<string, string> Map of lowercase header name => original name at registration */
private $headerNames = [];
/** @var string[] Map of lowercase header name => original name at registration */
private $headerNames = [];
/** @var string */
private $protocol = '1.1';
@@ -37,6 +37,7 @@ trait MessageTrait
$new = clone $this;
$new->protocol = $version;
return $new;
}
@@ -135,11 +136,12 @@ trait MessageTrait
$new = clone $this;
$new->stream = $body;
return $new;
}
/**
* @param array<string|int, string|string[]> $headers
* @param (string|string[])[] $headers
*/
private function setHeaders(array $headers): void
{
@@ -191,7 +193,7 @@ trait MessageTrait
*
* @return string[] Trimmed header values
*
* @see https://tools.ietf.org/html/rfc7230#section-3.2.4
* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
*/
private function trimAndValidateHeaderValues(array $values): array
{
@@ -211,7 +213,7 @@ trait MessageTrait
}
/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2
* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
*
* @param mixed $header
*/
@@ -224,18 +226,15 @@ trait MessageTrait
));
}
if (! preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/', $header)) {
if (!preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) {
throw new \InvalidArgumentException(
sprintf(
'"%s" is not valid header name',
$header
)
sprintf('"%s" is not valid header name.', $header)
);
}
}
/**
* @see https://tools.ietf.org/html/rfc7230#section-3.2
* @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
*
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
@@ -257,8 +256,10 @@ trait MessageTrait
// Clients must not send a request with line folding and a server sending folded headers is
// likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting
// folding is not likely to break any legitimate use case.
if (! preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/', $value)) {
throw new \InvalidArgumentException(sprintf('"%s" is not valid header value', $value));
if (!preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) {
throw new \InvalidArgumentException(
sprintf('"%s" is not valid header value.', $value)
);
}
}
}

View File

@@ -18,7 +18,7 @@ final class MimeType
'7zip' => 'application/x-7z-compressed',
'123' => 'application/vnd.lotus-1-2-3',
'aab' => 'application/x-authorware-bin',
'aac' => 'audio/x-acc',
'aac' => 'audio/aac',
'aam' => 'application/x-authorware-map',
'aas' => 'application/x-authorware-seg',
'abw' => 'application/x-abiword',
@@ -29,6 +29,7 @@ final class MimeType
'acu' => 'application/vnd.acucobol',
'acutc' => 'application/vnd.acucorp',
'adp' => 'audio/adpcm',
'adts' => 'audio/aac',
'aep' => 'application/vnd.audiograph',
'afm' => 'application/x-font-type1',
'afp' => 'application/vnd.ibm.modcap',
@@ -41,11 +42,16 @@ final class MimeType
'air' => 'application/vnd.adobe.air-application-installer-package+zip',
'ait' => 'application/vnd.dvb.ait',
'ami' => 'application/vnd.amiga.ami',
'aml' => 'application/automationml-aml+xml',
'amlx' => 'application/automationml-amlx+zip',
'amr' => 'audio/amr',
'apk' => 'application/vnd.android.package-archive',
'apng' => 'image/apng',
'appcache' => 'text/cache-manifest',
'appinstaller' => 'application/appinstaller',
'application' => 'application/x-ms-application',
'appx' => 'application/appx',
'appxbundle' => 'application/appxbundle',
'apr' => 'application/vnd.lotus-approach',
'arc' => 'application/x-freearc',
'arj' => 'application/x-arj',
@@ -90,6 +96,7 @@ final class MimeType
'bpk' => 'application/octet-stream',
'bpmn' => 'application/octet-stream',
'bsp' => 'model/vnd.valve.source.compiled-map',
'btf' => 'image/prs.btif',
'btif' => 'image/prs.btif',
'buffer' => 'application/octet-stream',
'bz' => 'application/x-bzip',
@@ -141,6 +148,7 @@ final class MimeType
'cjs' => 'application/node',
'cla' => 'application/vnd.claymore',
'class' => 'application/octet-stream',
'cld' => 'model/vnd.cld',
'clkk' => 'application/vnd.crick.clicker.keyboard',
'clkp' => 'application/vnd.crick.clicker.palette',
'clkt' => 'application/vnd.crick.clicker.template',
@@ -175,6 +183,7 @@ final class MimeType
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'curl' => 'text/vnd.curl',
'cwl' => 'application/cwl',
'cww' => 'application/prs.cww',
'cxt' => 'application/x-director',
'cxx' => 'text/x-c',
@@ -197,6 +206,7 @@ final class MimeType
'der' => 'application/x-x509-ca-cert',
'dfac' => 'application/vnd.dreamfactory',
'dgc' => 'application/x-dgc-compressed',
'dib' => 'image/bmp',
'dic' => 'text/x-c',
'dir' => 'application/x-director',
'dis' => 'application/vnd.mobius.dis',
@@ -219,6 +229,7 @@ final class MimeType
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'dp' => 'application/vnd.osgi.dp',
'dpg' => 'application/vnd.dpgraph',
'dpx' => 'image/dpx',
'dra' => 'audio/vnd.dra',
'drle' => 'image/dicom-rle',
'dsc' => 'text/prs.lines.tag',
@@ -255,7 +266,6 @@ final class MimeType
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'es' => 'application/ecmascript',
'es3' => 'application/vnd.eszigno3+xml',
'esa' => 'application/vnd.osgi.subsystem',
'esf' => 'application/vnd.epson.esf',
@@ -448,6 +458,7 @@ final class MimeType
'jsonld' => 'application/ld+json',
'jsonml' => 'application/jsonml+json',
'jsx' => 'text/jsx',
'jt' => 'model/jt',
'jxr' => 'image/jxr',
'jxra' => 'image/jxra',
'jxrs' => 'image/jxrs',
@@ -552,7 +563,7 @@ final class MimeType
'mime' => 'message/rfc822',
'mj2' => 'video/mj2',
'mjp2' => 'video/mj2',
'mjs' => 'application/javascript',
'mjs' => 'text/javascript',
'mk3d' => 'video/x-matroska',
'mka' => 'audio/x-matroska',
'mkd' => 'text/x-markdown',
@@ -602,6 +613,8 @@ final class MimeType
'msg' => 'application/vnd.ms-outlook',
'msh' => 'model/mesh',
'msi' => 'application/x-msdownload',
'msix' => 'application/msix',
'msixbundle' => 'application/msixbundle',
'msl' => 'application/vnd.mobius.msl',
'msm' => 'application/octet-stream',
'msp' => 'application/octet-stream',
@@ -775,6 +788,8 @@ final class MimeType
'pvb' => 'application/vnd.3gpp.pic-bw-var',
'pwn' => 'application/vnd.3m.post-it-notes',
'pya' => 'audio/vnd.ms-playready.media.pya',
'pyo' => 'model/vnd.pytha.pyox',
'pyox' => 'model/vnd.pytha.pyox',
'pyv' => 'video/vnd.ms-playready.media.pyv',
'qam' => 'application/vnd.epson.quickanime',
'qbo' => 'application/vnd.intu.qbo',
@@ -923,10 +938,12 @@ final class MimeType
'st' => 'application/vnd.sailingtracker.track',
'stc' => 'application/vnd.sun.xml.calc.template',
'std' => 'application/vnd.sun.xml.draw.template',
'step' => 'application/STEP',
'stf' => 'application/vnd.wt.stf',
'sti' => 'application/vnd.sun.xml.impress.template',
'stk' => 'application/hyperstudio',
'stl' => 'model/stl',
'stp' => 'application/STEP',
'stpx' => 'model/step+xml',
'stpxz' => 'model/step-xml+zip',
'stpz' => 'model/step+zip',
@@ -1013,10 +1030,12 @@ final class MimeType
'ulx' => 'application/x-glulx',
'umj' => 'application/vnd.umajin',
'unityweb' => 'application/vnd.unity',
'uo' => 'application/vnd.uoml+xml',
'uoml' => 'application/vnd.uoml+xml',
'uri' => 'text/uri-list',
'uris' => 'text/uri-list',
'urls' => 'text/uri-list',
'usda' => 'model/vnd.usda',
'usdz' => 'model/vnd.usdz+zip',
'ustar' => 'application/x-ustar',
'utz' => 'application/vnd.uiq.theme',
@@ -1096,6 +1115,7 @@ final class MimeType
'webmanifest' => 'application/manifest+json',
'webp' => 'image/webp',
'wg' => 'application/vnd.pmi.widget',
'wgsl' => 'text/wgsl',
'wgt' => 'application/widget',
'wif' => 'application/watcherinfo+xml',
'wks' => 'application/vnd.ms-works',
@@ -1150,9 +1170,10 @@ final class MimeType
'xel' => 'application/xcap-el+xml',
'xenc' => 'application/xenc+xml',
'xer' => 'application/patch-ops-error+xml',
'xfdf' => 'application/vnd.adobe.xfdf',
'xfdf' => 'application/xfdf',
'xfdl' => 'application/vnd.xfdl',
'xht' => 'application/xhtml+xml',
'xhtm' => 'application/vnd.pwg-xhtml-print+xml',
'xhtml' => 'application/xhtml+xml',
'xhvml' => 'application/xv+xml',
'xif' => 'image/vnd.xiff',
@@ -1183,6 +1204,7 @@ final class MimeType
'xpw' => 'application/vnd.intercon.formnet',
'xpx' => 'application/vnd.intercon.formnet',
'xsd' => 'application/xml',
'xsf' => 'application/prs.xsf+xml',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xsm' => 'application/vnd.syncml+xml',
@@ -1218,7 +1240,7 @@ final class MimeType
/**
* Determines the mimetype of a file by looking at its extension.
*
* @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json
* @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json
*/
public static function fromFilename(string $filename): ?string
{
@@ -1228,7 +1250,7 @@ final class MimeType
/**
* Maps a file extensions to a mimetype.
*
* @link https://raw.githubusercontent.com/jshttp/mime-db/master/db.json
* @see https://raw.githubusercontent.com/jshttp/mime-db/master/db.json
*/
public static function fromExtension(string $extension): ?string
{

View File

@@ -32,7 +32,7 @@ final class MultipartStream implements StreamInterface
*
* @throws \InvalidArgumentException
*/
public function __construct(array $elements = [], string $boundary = null)
public function __construct(array $elements = [], ?string $boundary = null)
{
$this->boundary = $boundary ?: bin2hex(random_bytes(20));
$this->stream = $this->createStream($elements);
@@ -51,7 +51,7 @@ final class MultipartStream implements StreamInterface
/**
* Get the headers needed before transferring the content of a POST file
*
* @param array<string, string> $headers
* @param string[] $headers
*/
private function getHeaders(array $headers): string
{
@@ -60,7 +60,7 @@ final class MultipartStream implements StreamInterface
$str .= "{$key}: {$value}\r\n";
}
return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n";
return "--{$this->boundary}\r\n".trim($str)."\r\n\r\n";
}
/**
@@ -72,7 +72,7 @@ final class MultipartStream implements StreamInterface
foreach ($elements as $element) {
if (!is_array($element)) {
throw new \UnexpectedValueException("An array is expected");
throw new \UnexpectedValueException('An array is expected');
}
$this->addElement($stream, $element);
}
@@ -112,10 +112,15 @@ final class MultipartStream implements StreamInterface
$stream->addStream(Utils::streamFor("\r\n"));
}
/**
* @param string[] $headers
*
* @return array{0: StreamInterface, 1: string[]}
*/
private function createElement(string $name, StreamInterface $stream, ?string $filename, array $headers): array
{
// Set a default content-disposition header if one was no provided
$disposition = $this->getHeader($headers, 'content-disposition');
$disposition = self::getHeader($headers, 'content-disposition');
if (!$disposition) {
$headers['Content-Disposition'] = ($filename === '0' || $filename)
? sprintf(
@@ -127,7 +132,7 @@ final class MultipartStream implements StreamInterface
}
// Set a default content-length header if one was no provided
$length = $this->getHeader($headers, 'content-length');
$length = self::getHeader($headers, 'content-length');
if (!$length) {
if ($length = $stream->getSize()) {
$headers['Content-Length'] = (string) $length;
@@ -135,21 +140,22 @@ final class MultipartStream implements StreamInterface
}
// Set a default Content-Type if one was not supplied
$type = $this->getHeader($headers, 'content-type');
$type = self::getHeader($headers, 'content-type');
if (!$type && ($filename === '0' || $filename)) {
if ($type = MimeType::fromFilename($filename)) {
$headers['Content-Type'] = $type;
}
$headers['Content-Type'] = MimeType::fromFilename($filename) ?? 'application/octet-stream';
}
return [$stream, $headers];
}
private function getHeader(array $headers, string $key)
/**
* @param string[] $headers
*/
private static function getHeader(array $headers, string $key): ?string
{
$lowercaseHeader = strtolower($key);
foreach ($headers as $k => $v) {
if (strtolower($k) === $lowercaseHeader) {
if (strtolower((string) $k) === $lowercaseHeader) {
return $v;
}
}

View File

@@ -18,7 +18,7 @@ use Psr\Http\Message\StreamInterface;
*/
final class PumpStream implements StreamInterface
{
/** @var callable|null */
/** @var callable(int): (string|false|null)|null */
private $source;
/** @var int|null */
@@ -34,7 +34,7 @@ final class PumpStream implements StreamInterface
private $buffer;
/**
* @param callable(int): (string|null|false) $source Source of the stream data. The callable MAY
* @param callable(int): (string|false|null) $source Source of the stream data. The callable MAY
* accept an integer argument used to control the
* amount of data to return. The callable MUST
* return a string when called, or false|null on error
@@ -60,6 +60,7 @@ final class PumpStream implements StreamInterface
throw $e;
}
trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
return '';
}
}
@@ -149,8 +150,6 @@ final class PumpStream implements StreamInterface
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)
@@ -164,11 +163,12 @@ final class PumpStream implements StreamInterface
private function pump(int $length): void
{
if ($this->source) {
if ($this->source !== null) {
do {
$data = call_user_func($this->source, $length);
$data = ($this->source)($length);
if ($data === false || $data === null) {
$this->source = null;
return;
}
$this->buffer->write($data);

View File

@@ -63,12 +63,15 @@ final class Query
* string. This function does not modify the provided keys when an array is
* encountered (like `http_build_query()` would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode,
* PHP_QUERY_RFC3986 to encode using
* RFC3986, or PHP_QUERY_RFC1738 to
* encode using RFC1738.
* @param bool $treatBoolsAsInts Set to true to encode as 0/1, and
* false as false/true.
*/
public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string
public static function build(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string
{
if (!$params) {
return '';
@@ -86,22 +89,24 @@ final class Query
throw new \InvalidArgumentException('Invalid type');
}
$castBool = $treatBoolsAsInts ? static function ($v) { return (int) $v; } : static function ($v) { return $v ? 'true' : 'false'; };
$qs = '';
foreach ($params as $k => $v) {
$k = $encoder((string) $k);
if (!is_array($v)) {
$qs .= $k;
$v = is_bool($v) ? (int) $v : $v;
$v = is_bool($v) ? $castBool($v) : $v;
if ($v !== null) {
$qs .= '=' . $encoder((string) $v);
$qs .= '='.$encoder((string) $v);
}
$qs .= '&';
} else {
foreach ($v as $vv) {
$qs .= $k;
$vv = is_bool($vv) ? (int) $vv : $vv;
$vv = is_bool($vv) ? $castBool($vv) : $vv;
if ($vv !== null) {
$qs .= '=' . $encoder((string) $vv);
$qs .= '='.$encoder((string) $vv);
}
$qs .= '&';
}

View File

@@ -28,7 +28,7 @@ class Request implements RequestInterface
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array<string, string|string[]> $headers Request headers
* @param (string|string[])[] $headers Request headers
* @param string|resource|StreamInterface|null $body Request body
* @param string $version Protocol version
*/
@@ -69,7 +69,7 @@ class Request implements RequestInterface
$target = '/';
}
if ($this->uri->getQuery() != '') {
$target .= '?' . $this->uri->getQuery();
$target .= '?'.$this->uri->getQuery();
}
return $target;
@@ -85,6 +85,7 @@ class Request implements RequestInterface
$new = clone $this;
$new->requestTarget = $requestTarget;
return $new;
}
@@ -98,6 +99,7 @@ class Request implements RequestInterface
$this->assertMethod($method);
$new = clone $this;
$new->method = strtoupper($method);
return $new;
}
@@ -131,7 +133,7 @@ class Request implements RequestInterface
}
if (($port = $this->uri->getPort()) !== null) {
$host .= ':' . $port;
$host .= ':'.$port;
}
if (isset($this->headerNames['host'])) {
@@ -141,7 +143,7 @@ class Request implements RequestInterface
$this->headerNames['host'] = 'Host';
}
// Ensure Host is the first header.
// See: http://tools.ietf.org/html/rfc7230#section-5.4
// See: https://datatracker.ietf.org/doc/html/rfc7230#section-5.4
$this->headers = [$header => [$host]] + $this->headers;
}

View File

@@ -86,7 +86,7 @@ class Response implements ResponseInterface
/**
* @param int $status Status code
* @param array<string, string|string[]> $headers Response headers
* @param (string|string[])[] $headers Response headers
* @param string|resource|StreamInterface|null $body Response body
* @param string $version Protocol version
* @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
@@ -96,7 +96,7 @@ class Response implements ResponseInterface
array $headers = [],
$body = null,
string $version = '1.1',
string $reason = null
?string $reason = null
) {
$this->assertStatusCodeRange($status);
@@ -138,6 +138,7 @@ class Response implements ResponseInterface
$reasonPhrase = self::PHRASES[$new->statusCode];
}
$new->reasonPhrase = (string) $reasonPhrase;
return $new;
}

View File

@@ -14,7 +14,7 @@ final class Rfc7230
*
* Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
*
* @link https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
* @see https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
*
* @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
*/

View File

@@ -59,7 +59,7 @@ class ServerRequest extends Request implements ServerRequestInterface
/**
* @param string $method HTTP method
* @param string|UriInterface $uri URI
* @param array<string, string|string[]> $headers Request headers
* @param (string|string[])[] $headers Request headers
* @param string|resource|StreamInterface|null $body Request body
* @param string $version Protocol version
* @param array $serverParams Typically the $_SERVER superglobal
@@ -144,10 +144,10 @@ class ServerRequest extends Request implements ServerRequestInterface
foreach (array_keys($files['tmp_name']) as $key) {
$spec = [
'tmp_name' => $files['tmp_name'][$key],
'size' => $files['size'][$key],
'error' => $files['error'][$key],
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'size' => $files['size'][$key] ?? null,
'error' => $files['error'][$key] ?? null,
'name' => $files['name'][$key] ?? null,
'type' => $files['type'][$key] ?? null,
];
$normalizedFiles[$key] = self::createUploadedFileFromSpec($spec);
}
@@ -182,7 +182,7 @@ class ServerRequest extends Request implements ServerRequestInterface
private static function extractHostAndPortFromAuthority(string $authority): array
{
$uri = 'http://' . $authority;
$uri = 'http://'.$authority;
$parts = parse_url($uri);
if (false === $parts) {
return [null, null];
@@ -286,8 +286,6 @@ class ServerRequest extends Request implements ServerRequestInterface
}
/**
* {@inheritdoc}
*
* @return array|object|null
*/
public function getParsedBody()
@@ -309,8 +307,6 @@ class ServerRequest extends Request implements ServerRequestInterface
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getAttribute($attribute, $default = null)

View File

@@ -12,8 +12,8 @@ use Psr\Http\Message\StreamInterface;
class Stream implements StreamInterface
{
/**
* @see http://php.net/manual/function.fopen.php
* @see http://php.net/manual/en/function.gzopen.php
* @see https://www.php.net/manual/en/function.fopen.php
* @see https://www.php.net/manual/en/function.gzopen.php
*/
private const READABLE_MODES = '/r|a\+|ab\+|w\+|wb\+|x\+|xb\+|c\+|cb\+/';
private const WRITABLE_MODES = '/a|w|r\+|rb\+|rw|x|c/';
@@ -61,8 +61,8 @@ class Stream implements StreamInterface
$this->stream = $stream;
$meta = stream_get_meta_data($this->stream);
$this->seekable = $meta['seekable'];
$this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']);
$this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']);
$this->readable = (bool) preg_match(self::READABLE_MODES, $meta['mode']);
$this->writable = (bool) preg_match(self::WRITABLE_MODES, $meta['mode']);
$this->uri = $this->getMetadata('uri');
}
@@ -80,12 +80,14 @@ class Stream implements StreamInterface
if ($this->isSeekable()) {
$this->seek(0);
}
return $this->getContents();
} catch (\Throwable $e) {
if (\PHP_VERSION_ID >= 70400) {
throw $e;
}
trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
return '';
}
}
@@ -145,6 +147,7 @@ class Stream implements StreamInterface
$stats = fstat($this->stream);
if (is_array($stats) && isset($stats['size'])) {
$this->size = $stats['size'];
return $this->size;
}
@@ -207,7 +210,7 @@ class Stream implements StreamInterface
}
if (fseek($this->stream, $offset, $whence) === -1) {
throw new \RuntimeException('Unable to seek to stream position '
. $offset . ' with whence ' . var_export($whence, true));
.$offset.' with whence '.var_export($whence, true));
}
}
@@ -261,8 +264,6 @@ class Stream implements StreamInterface
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)

View File

@@ -31,6 +31,7 @@ trait StreamDecoratorTrait
{
if ($name === 'stream') {
$this->stream = $this->createStream();
return $this->stream;
}
@@ -43,12 +44,14 @@ trait StreamDecoratorTrait
if ($this->isSeekable()) {
$this->seek(0);
}
return $this->getContents();
} catch (\Throwable $e) {
if (\PHP_VERSION_ID >= 70400) {
throw $e;
}
trigger_error(sprintf('%s::__toString exception: %s', self::class, (string) $e), E_USER_ERROR);
return '';
}
}
@@ -67,7 +70,7 @@ trait StreamDecoratorTrait
{
/** @var callable $callable */
$callable = [$this->stream, $method];
$result = call_user_func_array($callable, $args);
$result = ($callable)(...$args);
// Always return the wrapped object if the result is a return $this
return $result === $this->stream ? $this : $result;
@@ -79,8 +82,6 @@ trait StreamDecoratorTrait
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function getMetadata($key = null)

View File

@@ -41,7 +41,7 @@ final class StreamWrapper
$mode = 'w';
} else {
throw new \InvalidArgumentException('The stream must be readable, '
. 'writable, or both.');
.'writable, or both.');
}
return fopen('guzzle://stream', $mode, false, self::createStreamContext($stream));
@@ -55,7 +55,7 @@ final class StreamWrapper
public static function createStreamContext(StreamInterface $stream)
{
return stream_context_create([
'guzzle' => ['stream' => $stream]
'guzzle' => ['stream' => $stream],
]);
}
@@ -69,7 +69,7 @@ final class StreamWrapper
}
}
public function stream_open(string $path, string $mode, int $options, string &$opened_path = null): bool
public function stream_open(string $path, string $mode, int $options, ?string &$opened_path = null): bool
{
$options = stream_context_get_options($this->context);
@@ -115,61 +115,93 @@ final class StreamWrapper
*/
public function stream_cast(int $cast_as)
{
$stream = clone($this->stream);
$stream = clone $this->stream;
$resource = $stream->detach();
return $resource ?? false;
}
/**
* @return array<int|string, int>
* @return array{
* dev: int,
* ino: int,
* mode: int,
* nlink: int,
* uid: int,
* gid: int,
* rdev: int,
* size: int,
* atime: int,
* mtime: int,
* ctime: int,
* blksize: int,
* blocks: int
* }|false
*/
public function stream_stat(): array
public function stream_stat()
{
if ($this->stream->getSize() === null) {
return false;
}
static $modeMap = [
'r' => 33060,
'r' => 33060,
'rb' => 33060,
'r+' => 33206,
'w' => 33188,
'wb' => 33188
'w' => 33188,
'wb' => 33188,
];
return [
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
'blocks' => 0,
];
}
/**
* @return array<int|string, int>
* @return array{
* dev: int,
* ino: int,
* mode: int,
* nlink: int,
* uid: int,
* gid: int,
* rdev: int,
* size: int,
* atime: int,
* mtime: int,
* ctime: int,
* blksize: int,
* blocks: int
* }
*/
public function url_stat(string $path, int $flags): array
{
return [
'dev' => 0,
'ino' => 0,
'mode' => 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'dev' => 0,
'ino' => 0,
'mode' => 0,
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
'blocks' => 0,
];
}
}

View File

@@ -64,8 +64,8 @@ class UploadedFile implements UploadedFileInterface
$streamOrFile,
?int $size,
int $errorStatus,
string $clientFilename = null,
string $clientMediaType = null
?string $clientFilename = null,
?string $clientMediaType = null
) {
$this->setError($errorStatus);
$this->size = $size;
@@ -113,7 +113,7 @@ class UploadedFile implements UploadedFileInterface
$this->error = $error;
}
private function isStringNotEmpty($param): bool
private static function isStringNotEmpty($param): bool
{
return is_string($param) && false === empty($param);
}
@@ -163,7 +163,7 @@ class UploadedFile implements UploadedFileInterface
{
$this->validateActive();
if (false === $this->isStringNotEmpty($targetPath)) {
if (false === self::isStringNotEmpty($targetPath)) {
throw new InvalidArgumentException(
'Invalid path provided for move operation; must be a non-empty string'
);

View File

@@ -25,7 +25,7 @@ class Uri implements UriInterface, \JsonSerializable
private const HTTP_DEFAULT_HOST = 'localhost';
private const DEFAULT_PORTS = [
'http' => 80,
'http' => 80,
'https' => 443,
'ftp' => 21,
'gopher' => 70,
@@ -41,14 +41,14 @@ class Uri implements UriInterface, \JsonSerializable
/**
* Unreserved characters for use in a regex.
*
* @link https://tools.ietf.org/html/rfc3986#section-2.3
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.3
*/
private const CHAR_UNRESERVED = 'a-zA-Z0-9_\-\.~';
/**
* Sub-delims for use in a regex.
*
* @link https://tools.ietf.org/html/rfc3986#section-2.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-2.2
*/
private const CHAR_SUB_DELIMS = '!\$&\'\(\)\*\+,;=';
private const QUERY_SEPARATORS_REPLACEMENT = ['=' => '%3D', '&' => '%26'];
@@ -87,6 +87,7 @@ class Uri implements UriInterface, \JsonSerializable
$this->applyParts($parts);
}
}
/**
* UTF-8 aware \parse_url() replacement.
*
@@ -121,7 +122,7 @@ class Uri implements UriInterface, \JsonSerializable
$url
);
$result = parse_url($prefix . $encodedUrl);
$result = parse_url($prefix.$encodedUrl);
if ($result === false) {
return false;
@@ -161,7 +162,7 @@ class Uri implements UriInterface, \JsonSerializable
* `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to
* that format).
*
* @link https://tools.ietf.org/html/rfc3986#section-5.3
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
*/
public static function composeComponents(?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment): string
{
@@ -169,25 +170,25 @@ class Uri implements UriInterface, \JsonSerializable
// weak type checks to also accept null until we can add scalar type hints
if ($scheme != '') {
$uri .= $scheme . ':';
$uri .= $scheme.':';
}
if ($authority != '' || $scheme === 'file') {
$uri .= '//' . $authority;
$uri .= '//'.$authority;
}
if ($authority != '' && $path != '' && $path[0] != '/') {
$path = '/' . $path;
$path = '/'.$path;
}
$uri .= $path;
if ($query != '') {
$uri .= '?' . $query;
$uri .= '?'.$query;
}
if ($fragment != '') {
$uri .= '#' . $fragment;
$uri .= '#'.$fragment;
}
return $uri;
@@ -218,7 +219,7 @@ class Uri implements UriInterface, \JsonSerializable
* @see Uri::isNetworkPathReference
* @see Uri::isAbsolutePathReference
* @see Uri::isRelativePathReference
* @link https://tools.ietf.org/html/rfc3986#section-4
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-4
*/
public static function isAbsolute(UriInterface $uri): bool
{
@@ -230,7 +231,7 @@ class Uri implements UriInterface, \JsonSerializable
*
* A relative reference that begins with two slash characters is termed an network-path reference.
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
*/
public static function isNetworkPathReference(UriInterface $uri): bool
{
@@ -242,7 +243,7 @@ class Uri implements UriInterface, \JsonSerializable
*
* A relative reference that begins with a single slash character is termed an absolute-path reference.
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
*/
public static function isAbsolutePathReference(UriInterface $uri): bool
{
@@ -257,7 +258,7 @@ class Uri implements UriInterface, \JsonSerializable
*
* A relative reference that does not begin with a slash character is termed a relative-path reference.
*
* @link https://tools.ietf.org/html/rfc3986#section-4.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
*/
public static function isRelativePathReference(UriInterface $uri): bool
{
@@ -276,9 +277,9 @@ class Uri implements UriInterface, \JsonSerializable
* @param UriInterface $uri The URI to check
* @param UriInterface|null $base An optional base URI to compare against
*
* @link https://tools.ietf.org/html/rfc3986#section-4.4
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-4.4
*/
public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool
public static function isSameDocumentReference(UriInterface $uri, ?UriInterface $base = null): bool
{
if ($base !== null) {
$uri = UriResolver::resolve($base, $uri);
@@ -335,8 +336,8 @@ class Uri implements UriInterface, \JsonSerializable
*
* It has the same behavior as withQueryValue() but for an associative array of key => value.
*
* @param UriInterface $uri URI to use as a base.
* @param array<string, string|null> $keyValueArray Associative array of key and values
* @param UriInterface $uri URI to use as a base.
* @param (string|null)[] $keyValueArray Associative array of key and values
*/
public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface
{
@@ -352,7 +353,7 @@ class Uri implements UriInterface, \JsonSerializable
/**
* Creates a URI from a hash of `parse_url` components.
*
* @link http://php.net/manual/en/function.parse-url.php
* @see https://www.php.net/manual/en/function.parse-url.php
*
* @throws MalformedUriException If the components do not form a valid URI.
*/
@@ -374,11 +375,11 @@ class Uri implements UriInterface, \JsonSerializable
{
$authority = $this->host;
if ($this->userInfo !== '') {
$authority = $this->userInfo . '@' . $authority;
$authority = $this->userInfo.'@'.$authority;
}
if ($this->port !== null) {
$authority .= ':' . $this->port;
$authority .= ':'.$this->port;
}
return $authority;
@@ -435,7 +436,7 @@ class Uri implements UriInterface, \JsonSerializable
{
$info = $this->filterUserInfoComponent($user);
if ($password !== null) {
$info .= ':' . $this->filterUserInfoComponent($password);
$info .= ':'.$this->filterUserInfoComponent($password);
}
if ($this->userInfo === $info) {
@@ -563,7 +564,7 @@ class Uri implements UriInterface, \JsonSerializable
? $this->filterQueryAndFragment($parts['fragment'])
: '';
if (isset($parts['pass'])) {
$this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']);
$this->userInfo .= ':'.$this->filterUserInfoComponent($parts['pass']);
}
$this->removeDefaultPort();
@@ -595,7 +596,7 @@ class Uri implements UriInterface, \JsonSerializable
}
return preg_replace_callback(
'/(?:[^%' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . ']+|%(?![A-Fa-f0-9]{2}))/',
'/(?:[^%'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.']+|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$component
);
@@ -627,7 +628,7 @@ class Uri implements UriInterface, \JsonSerializable
}
$port = (int) $port;
if (0 > $port || 0xffff < $port) {
if (0 > $port || 0xFFFF < $port) {
throw new \InvalidArgumentException(
sprintf('Invalid port: %d. Must be between 0 and 65535', $port)
);
@@ -637,7 +638,7 @@ class Uri implements UriInterface, \JsonSerializable
}
/**
* @param string[] $keys
* @param (string|int)[] $keys
*
* @return string[]
*/
@@ -649,7 +650,9 @@ class Uri implements UriInterface, \JsonSerializable
return [];
}
$decodedKeys = array_map('rawurldecode', $keys);
$decodedKeys = array_map(function ($k): string {
return rawurldecode((string) $k);
}, $keys);
return array_filter(explode('&', $current), function ($part) use ($decodedKeys) {
return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true);
@@ -664,7 +667,7 @@ class Uri implements UriInterface, \JsonSerializable
$queryString = strtr($key, self::QUERY_SEPARATORS_REPLACEMENT);
if ($value !== null) {
$queryString .= '=' . strtr($value, self::QUERY_SEPARATORS_REPLACEMENT);
$queryString .= '='.strtr($value, self::QUERY_SEPARATORS_REPLACEMENT);
}
return $queryString;
@@ -691,7 +694,7 @@ class Uri implements UriInterface, \JsonSerializable
}
return preg_replace_callback(
'/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
'/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/]++|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$path
);
@@ -711,7 +714,7 @@ class Uri implements UriInterface, \JsonSerializable
}
return preg_replace_callback(
'/(?:[^' . self::CHAR_UNRESERVED . self::CHAR_SUB_DELIMS . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
'/(?:[^'.self::CHAR_UNRESERVED.self::CHAR_SUB_DELIMS.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/',
[$this, 'rawurlencodeMatchZero'],
$str
);

View File

@@ -11,7 +11,7 @@ use Psr\Http\Message\UriInterface;
*
* @author Tobias Schultze
*
* @link https://tools.ietf.org/html/rfc3986#section-6
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-6
*/
final class UriNormalizer
{
@@ -119,7 +119,7 @@ final class UriNormalizer
* @param UriInterface $uri The URI to normalize
* @param int $flags A bitmask of normalizations to apply, see constants
*
* @link https://tools.ietf.org/html/rfc3986#section-6.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-6.2
*/
public static function normalize(UriInterface $uri, int $flags = self::PRESERVING_NORMALIZATIONS): UriInterface
{
@@ -131,8 +131,8 @@ final class UriNormalizer
$uri = self::decodeUnreservedCharacters($uri);
}
if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === '' &&
($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
if ($flags & self::CONVERT_EMPTY_PATH && $uri->getPath() === ''
&& ($uri->getScheme() === 'http' || $uri->getScheme() === 'https')
) {
$uri = $uri->withPath('/');
}
@@ -174,7 +174,7 @@ final class UriNormalizer
* @param UriInterface $uri2 An URI to compare
* @param int $normalizations A bitmask of normalizations to apply, see constants
*
* @link https://tools.ietf.org/html/rfc3986#section-6.1
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-6.1
*/
public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, int $normalizations = self::PRESERVING_NORMALIZATIONS): bool
{
@@ -185,7 +185,7 @@ final class UriNormalizer
{
$regex = '/(?:%[A-Fa-f0-9]{2})++/';
$callback = function (array $match) {
$callback = function (array $match): string {
return strtoupper($match[0]);
};
@@ -201,7 +201,7 @@ final class UriNormalizer
{
$regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i';
$callback = function (array $match) {
$callback = function (array $match): string {
return rawurldecode($match[0]);
};

View File

@@ -11,14 +11,14 @@ use Psr\Http\Message\UriInterface;
*
* @author Tobias Schultze
*
* @link https://tools.ietf.org/html/rfc3986#section-5
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5
*/
final class UriResolver
{
/**
* Removes dot segments from a path and returns the new path.
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2.4
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
*/
public static function removeDotSegments(string $path): string
{
@@ -40,7 +40,7 @@ final class UriResolver
if ($path[0] === '/' && (!isset($newPath[0]) || $newPath[0] !== '/')) {
// Re-add the leading slash if necessary for cases like "/.."
$newPath = '/' . $newPath;
$newPath = '/'.$newPath;
} elseif ($newPath !== '' && ($segment === '.' || $segment === '..')) {
// Add the trailing slash if necessary
// If newPath is not empty, then $segment must be set and is the last segment from the foreach
@@ -53,7 +53,7 @@ final class UriResolver
/**
* Converts the relative URI into a new URI that is resolved against the base URI.
*
* @link http://tools.ietf.org/html/rfc3986#section-5.2
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2
*/
public static function resolve(UriInterface $base, UriInterface $rel): UriInterface
{
@@ -80,13 +80,13 @@ final class UriResolver
$targetPath = $rel->getPath();
} else {
if ($targetAuthority != '' && $base->getPath() === '') {
$targetPath = '/' . $rel->getPath();
$targetPath = '/'.$rel->getPath();
} else {
$lastSlashPos = strrpos($base->getPath(), '/');
if ($lastSlashPos === false) {
$targetPath = $rel->getPath();
} else {
$targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath();
$targetPath = substr($base->getPath(), 0, $lastSlashPos + 1).$rel->getPath();
}
}
}
@@ -127,8 +127,8 @@ final class UriResolver
*/
public static function relativize(UriInterface $base, UriInterface $target): UriInterface
{
if ($target->getScheme() !== '' &&
($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
if ($target->getScheme() !== ''
&& ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '')
) {
return $target;
}
@@ -185,7 +185,7 @@ final class UriResolver
}
}
$targetSegments[] = $targetLastSegment;
$relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments);
$relativePath = str_repeat('../', count($sourceSegments)).implode('/', $targetSegments);
// A reference to am empty last segment or an empty first sub-segment must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used

View File

@@ -14,18 +14,18 @@ final class Utils
/**
* Remove the items given by the keys, case insensitively from the data.
*
* @param string[] $keys
* @param (string|int)[] $keys
*/
public static function caselessRemove(array $keys, array $data): array
{
$result = [];
foreach ($keys as &$key) {
$key = strtolower($key);
$key = strtolower((string) $key);
}
foreach ($data as $k => $v) {
if (!is_string($k) || !in_array(strtolower($k), $keys)) {
if (!in_array(strtolower((string) $k), $keys)) {
$result[$k] = $v;
}
}
@@ -90,6 +90,7 @@ final class Utils
}
$buffer .= $buf;
}
return $buffer;
}
@@ -174,7 +175,7 @@ final class Utils
$standardPorts = ['http' => 80, 'https' => 443];
$scheme = $changes['uri']->getScheme();
if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
$changes['set_headers']['Host'] .= ':' . $port;
$changes['set_headers']['Host'] .= ':'.$port;
}
}
}
@@ -249,6 +250,20 @@ final class Utils
return $buffer;
}
/**
* Redact the password in the user info part of a URI.
*/
public static function redactUserInfo(UriInterface $uri): UriInterface
{
$userInfo = $uri->getUserInfo();
if (false !== ($pos = \strpos($userInfo, ':'))) {
return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
}
return $uri;
}
/**
* Create a new stream based on the input type.
*
@@ -291,6 +306,7 @@ final class Utils
fwrite($stream, (string) $resource);
fseek($stream, 0);
}
return new Stream($stream, $options);
}
@@ -308,6 +324,7 @@ final class Utils
fseek($stream, 0);
$resource = $stream;
}
return new Stream($resource, $options);
case 'object':
/** @var object $resource */
@@ -320,6 +337,7 @@ final class Utils
}
$result = $resource->current();
$resource->next();
return $result;
}, $options);
} elseif (method_exists($resource, '__toString')) {
@@ -334,7 +352,7 @@ final class Utils
return new PumpStream($resource, $options);
}
throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource));
}
/**