diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 22a0f10c0..e474586d4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ permissions: contents: read env: - COMPOSER_ROOT_VERSION: 8.3.x-dev + COMPOSER_ROOT_VERSION: 8.5.x-dev jobs: build-lowest-version: diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 4bb4ee7e7..be2234387 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -9,7 +9,7 @@ permissions: contents: read env: - COMPOSER_ROOT_VERSION: 8.3.x-dev + COMPOSER_ROOT_VERSION: 8.5.x-dev jobs: phpstan: diff --git a/AGENTS.md b/AGENTS.md index 9be25beb8..4117b77b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,6 +91,9 @@ sections of the README and `UPGRADING.md` describe the fork; the rest of - Keep fork changes minimal and in upstream's style so upstream updates merge cleanly. +- Fix confirmed upstream bugs that warrant correction in the fork. Add a concise + code comment explaining why the fix differs from upstream. Do not open an + upstream pull request unless the owner asks. - Track the latest stable upstream release. Sync when a new stable release is available, merging all changes through its release commit and preserving the fork's intentional differences. Do not routinely sync unreleased branch @@ -130,9 +133,9 @@ sections of the README and `UPGRADING.md` describe the fork; the rest of never a rebase. Review the full upstream diff since the previous sync and the resulting fork diff; keep the fork's intentional behavior when resolving conflicts. - When upstream merges a pull request the fork already carries, reconcile the - fork's copy with upstream's final version, keep the fork's own changes on top - of it, and remove only the code it supersedes. + When upstream merges a fix the fork already carries, reconcile the fork's copy + with upstream's final version, keep the fork's own changes on top of it, and + remove only the code it supersedes. - Run the fork's static checks and relevant unit tests using the existing local environment, then push the pull request branch. Use the `gh` CLI to monitor CI and inspect failure logs. CI runs the full suite, including integration diff --git a/CHANGELOG.md b/CHANGELOG.md index da7968db7..2c605a47e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,47 @@ and the README's [Hypervel Fork](README.md#hypervel-fork) section. Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. +## 8.5.0 - 2026-11-13 + +### Added + +- Add `Utils::setDefaultHandlerFactory()` to replace the default handler + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.4` + +### Deprecated + +- Deprecated `Utils::defaultUserAgent()` in favor of `ClientInterface::MAJOR_VERSION` +- Deprecated `Utils::headersFromLines()`, `Utils::normalizeHeaderKeys()`, `Utils::debugResource()`, and `Utils::normalizeProtocols()` + + +## 8.4.0 - 2026-11-12 + +### Added + +- Add `max_idle_handles` client and cURL handler option to limit idle handles + +### Changed + +- Adjusted `guzzlehttp/psr7` version constraint to `^3.3` +- Send longer-path cookies first in the `Cookie` header, like browsers and libcurl +- Replace stored cookies in place so a refreshed cookie keeps its position in the `Cookie` header + +### Fixed + +- Fix overlapping stream handler transfers swallowing and mixing up PHP errors +- Fix the stream handler sending an empty `From` header with no `from` ini set + + +## 8.3.2 - 2026-11-12 + +### Fixed + +- Fix overlapping stream handler transfers leaving the `from` ini setting blank + + ## 8.3.1 - 2026-10-25 ### Fixed diff --git a/README.md b/README.md index 1c6ca1f98..f4c5dff68 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,9 @@ Guzzle client, including clients that SDKs create. This fork adds: and each easy handle has its own connection cache, so with 3 most concurrent requests would open new connections. `CurlMultiHandler` keeps its default of 50. See [Idle cURL Handles](docs/handlers.md#idle-curl-handles). -- **Upstream pull requests.** The fork includes - [#3935](https://github.com/guzzle/guzzle/pull/3935), which adds the - `max_idle_handles` option for the cURL handlers. Stream handling fixes use - upstream's implementations. +- **Fixes not in upstream.** Setting a cookie the jar already holds also removes + stored cookies that were changed into duplicates of it. Response header + parsing keeps headers out of exception traces, as they can carry credentials. > [!IMPORTANT] > This fork keeps upstream's public API. Once installed, it replaces diff --git a/composer.json b/composer.json index f28cfa3f0..463da7616 100644 --- a/composer.json +++ b/composer.json @@ -54,10 +54,11 @@ "php": "^8.4", "ext-json": "*", "ext-swoole": "*", - "guzzlehttp/psr7": "^3.2", + "guzzlehttp/psr7": "^3.4", "hypervel/guzzle-promises": "^3.1", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", "symfony/polyfill-php80": "^1.25", "symfony/polyfill-php82": "^1.27" }, @@ -88,7 +89,7 @@ "name": "guzzle/client-integration-tests", "version": "v4.0.1", "require": { - "guzzlehttp/psr7": "^3.2", + "guzzlehttp/psr7": "^3.4", "php": "^7.4 || ^8.0", "php-http/message": "^1.0 || ^2.0", "phpunit/phpunit": "^9.6.34", diff --git a/docs/contributing/curl-connection-reuse.md b/docs/contributing/curl-connection-reuse.md index 9424ccb54..28fc107bb 100644 --- a/docs/contributing/curl-connection-reuse.md +++ b/docs/contributing/curl-connection-reuse.md @@ -25,11 +25,13 @@ connections alive in a **connection cache** and reuses them for later transfers on the same handle — or across handles, if you share them (§3). `CurlFactory` pools easy handles: on `release()` it calls `curl_reset()` (which -clears per-request options) and returns the handle to a small pool; `create()` -pops a pooled handle and re-applies the next request's options. The key fact: -**`curl_reset()` does not close the underlying connection** — reuse is the -whole point — so a pooled handle can carry a live connection from one request -into the next. +clears per-request options) and returns the handle to a pool of at most +`max_idle_handles` idle handles (by default 256 for `CurlHandler` and 50 for +`CurlMultiHandler`), closing it instead when the pool is full; `create()` pops a +pooled handle and re-applies the next request's options. The key fact: +**`curl_reset()` does not close the underlying connection** — reuse is the whole +point — so a pooled handle can carry a live connection from one request into the +next. The option pipeline is: Guzzle request options (`proxy`, `cert`, …) → an internal `$conf` array of `CURLOPT_* => value` → `curl_setopt_array()`. diff --git a/docs/cookies.md b/docs/cookies.md index 923595ef3..4e16aae05 100644 --- a/docs/cookies.md +++ b/docs/cookies.md @@ -35,8 +35,8 @@ Different implementations exist for the `GuzzleHttp\Cookie\CookieJarInterface` : The built-in `CookieJar` admits at most 50 cookies from one response. It ignores any `Set-Cookie` field value longer than 8,190 bytes. A generated `Cookie` header contains at most 150 stored cookies, and its canonical line including -`Cookie: ` is limited to 8,190 bytes. Later cookies are omitted after either -output limit is reached. +`Cookie: ` is limited to 8,190 bytes. Cookies stored later are omitted after +either output limit is reached. You can manually set cookies into a cookie jar with the named constructor `fromArray(array $cookies, $domain)`. diff --git a/docs/guzzle-and-psr-7.md b/docs/guzzle-and-psr-7.md index 0078e20ea..805769f63 100644 --- a/docs/guzzle-and-psr-7.md +++ b/docs/guzzle-and-psr-7.md @@ -3,7 +3,7 @@ This page covers how Guzzle integrates PSR-7 requests, responses, streams, and URIs while sending HTTP requests. Generic PSR-7 message, URI, stream, and helper documentation lives in -[`guzzlehttp/psr7`](https://github.com/guzzle/psr7/blob/3.2/README.md). +[`guzzlehttp/psr7`](https://github.com/guzzle/psr7/blob/3.4/README.md). ## Sending PSR-7 Requests @@ -34,7 +34,7 @@ middleware and handlers. Guzzle uses PSR-7 stream objects to represent request and response bodies. For general stream creation, metadata, decorators, and PHP stream resource integration, see the -[PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.2/docs/streams-and-decorators.md). +[PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.4/docs/streams-and-decorators.md). For response bodies, the built-in stream handler creates or wraps the sink/default stream with the configured @@ -86,4 +86,4 @@ itself is created with the - [Quick Start](quick-start.md) - [Request Options](request-options.md) -- [PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.2/docs/streams-and-decorators.md) +- [PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.4/docs/streams-and-decorators.md) diff --git a/docs/handlers.md b/docs/handlers.md index 70cbbb234..b327ffc68 100644 --- a/docs/handlers.md +++ b/docs/handlers.md @@ -69,6 +69,37 @@ system. > have a cookie middleware associated with a client, then setting the `cookies` > request option will have no effect on the request. +### Default Handler Factory + +`GuzzleHttp\Utils::setDefaultHandlerFactory()` sets a factory that creates the +default handler in place of the built-in selection. The factory receives the +handler options and a callable that returns the handler Guzzle would have +chosen: + +```php +use GuzzleHttp\Middleware; +use GuzzleHttp\Utils; +use Psr\Http\Message\RequestInterface; + +$factory = function (array $handlerOptions, callable $default): callable { + $addHeader = Middleware::mapRequest(function (RequestInterface $request) { + return $request->withHeader('X-Foo', 'bar'); + }); + + return $addHeader($default()); +}; + +Utils::setDefaultHandlerFactory($factory); +``` + +The factory is consulted each time a default handler is chosen, after the +handler options have been checked for type and value. Clients that already exist +keep their handler, and a handler provided explicitly never reaches the factory. +Passing null restores the built-in selection. + +The factory is process-wide, so set it from application bootstrap code, not from +a library. + ### PSR-17 Factories The PSR-17 factory request options are owned by different layers: @@ -102,10 +133,9 @@ custom handlers are responsible for honoring these options themselves. ### Idle cURL Handles `max_idle_handles` (int|null): Maximum number of idle cURL easy handles retained -by each default cURL handler. Accepts a non-negative integer or null. Zero -disables idle handle retention; null or omission keeps the defaults of 256 for -`CurlHandler` and 50 for `CurlMultiHandler`. This setting does not affect the -stream handler. +by each default cURL handler. Zero disables retention; null or omission keeps +the defaults of 256 for `CurlHandler` and 50 for `CurlMultiHandler`. This +setting does not affect the stream handler. Pass this option to the client constructor when Guzzle creates the default handler: @@ -118,23 +148,24 @@ $client = new Client([ ]); ``` -One value applies separately to each cURL handler Guzzle creates. In this -example, both the synchronous and asynchronous handlers retain at most 64 idle -easy handles each. Handles are created as requests need them, not allocated in -advance. +In this example, the synchronous and asynchronous handlers each retain at most +64 idle easy handles. Handles are created as requests need them, not allocated +in advance. -Keeping more idle easy handles can improve reuse after concurrent requests, -particularly when a coroutine runtime allows synchronous requests to overlap. It -also retains more native resources. This is not a limit on active requests or -network connections: a synchronous easy handle can cache connections to several -origins, and `CurlMultiHandler` has its own connection cache separate from its -idle easy handles. +Retaining more idle handles can improve connection reuse when synchronous +requests overlap, such as under a coroutine runtime, at the cost of more native +resources. It does not limit active requests or network connections: a +synchronous easy handle can cache connections to several origins, and +`CurlMultiHandler` has its own connection cache separate from its idle easy +handles. A handle released into a full pool is closed with the connections it +holds, so zero makes every synchronous request open a new connection unless +persistent transport sharing pools connections, while `CurlMultiHandler` keeps +reusing them through its multi handle. The option is also accepted by `GuzzleHttp\Utils::chooseHandler()` and the `CurlHandler` and `CurlMultiHandler` constructors. A non-null value cannot be -combined with a custom client handler or a custom `handle_factory`: configure -the option on the custom handler's constructor, or retention on the custom -factory, instead. +combined with a custom client handler or a custom `handle_factory`; configure +the cURL handler or the factory instead. ### Closing cURL Handlers @@ -208,10 +239,13 @@ connection caps are configured. Synchronous requests still use `CurlHandler`. One client can serve concurrent coroutines; each promise must still be created and completed in its owning coroutine. +The callable passed to a [default handler factory](#default-handler-factory) +returns this default handler, so a factory that wraps it keeps the coroutine +handler. A factory that creates its own handler replaces it. + `max_idle_multi_handlers` (int|null): Maximum number of idle cURL multi handlers -retained for coroutine requests. Accepts a non-negative integer or null. Zero -disables retention; null or omission keeps the default of 64. Cannot be combined -with connection caps or a custom handler. +retained for coroutine requests. Zero disables retention; null or omission keeps +the default of 64. Cannot be combined with connection caps or a custom handler. ```php $client = new \GuzzleHttp\Client(['max_idle_multi_handlers' => 16]); diff --git a/docs/overview.md b/docs/overview.md index 64e4394da..b124121b4 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -30,7 +30,7 @@ curl -sS https://getcomposer.org/installer | php You can add Guzzle as a dependency using Composer: ```bash -composer require hypervel/guzzle:^8.3 +composer require hypervel/guzzle:^8.5 ``` Alternatively, you can specify Guzzle as a dependency in your project's existing @@ -39,7 +39,7 @@ composer.json file: ```js { "require": { - "hypervel/guzzle": "^8.3" + "hypervel/guzzle": "^8.5" } } ``` diff --git a/docs/package-ecosystem.md b/docs/package-ecosystem.md index 75da67eb3..659366ef9 100644 --- a/docs/package-ecosystem.md +++ b/docs/package-ecosystem.md @@ -10,7 +10,7 @@ application needs that package's lower-level or specialized behavior. | Package | Use it for | Documentation | |---------|------------|---------------| | `hypervel/guzzle` | Sending synchronous and asynchronous HTTP requests. | [Quick Start](quick-start.md) | -| `guzzlehttp/psr7` | Creating and manipulating PSR-7 requests, responses, streams, and URIs. | [PSR-7 docs](https://github.com/guzzle/psr7/blob/3.2/docs/psr-7-messages.md) | +| `guzzlehttp/psr7` | Creating and manipulating PSR-7 requests, responses, streams, and URIs. | [PSR-7 docs](https://github.com/guzzle/psr7/blob/3.4/docs/psr-7-messages.md) | | `hypervel/guzzle-promises` | Working directly with promises returned by asynchronous operations. | [Promises docs](https://github.com/hypervel/guzzle-promises/blob/3.1/docs/promise-quick-start.md) | Install `hypervel/guzzle` for normal application HTTP work. It already depends diff --git a/docs/request-options.md b/docs/request-options.md index 159a6bfef..c8ed9fd51 100644 --- a/docs/request-options.md +++ b/docs/request-options.md @@ -2013,7 +2013,7 @@ response body resources where practical. Request bodies that already implement > gzip/deflate decoding, and should stream the resource rather than buffer it > entirely into memory. The full contract is described under *Creating Streams* > in the -> [PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.2/docs/streams-and-decorators.md#creating-streams). +> [PSR-7 stream documentation](https://github.com/guzzle/psr7/blob/3.4/docs/streams-and-decorators.md#creating-streams). > Supply a stream implementation you trust. ## uri_factory diff --git a/src/Client.php b/src/Client.php index e71edd2e4..8c6569a84 100644 --- a/src/Client.php +++ b/src/Client.php @@ -74,14 +74,13 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface * response streaming ("stream" => true) and does not limit overlapping * buffered calls. * - max_idle_handles: (int|null) Maximum number of idle cURL easy handles - * retained by each default cURL handler. Accepts a non-negative integer - * or null. Zero disables idle handle retention; null or omission keeps - * the defaults of 256 for CurlHandler and 50 for CurlMultiHandler. This - * setting does not affect the stream handler. + * retained by each default cURL handler. Zero disables retention; null or + * omission keeps the defaults of 256 for CurlHandler and 50 for + * CurlMultiHandler. This setting does not affect the stream handler. * - max_idle_multi_handlers: (int|null) Maximum number of idle cURL multi - * handlers retained for coroutine requests. Accepts a non-negative integer - * or null. Zero disables retention; null or omission keeps the default of - * 64. Cannot be combined with connection caps or a custom handler. + * handlers retained for coroutine requests. Zero disables retention; null + * or omission keeps the default of 64. Cannot be combined with connection + * caps or a custom handler. * - max_total_connections: (int|null) Maximum concurrent connections * overall, enforced by the default CurlMultiHandler. The default stream * fallback receives the cap as a marker only: it rejects enabled @@ -181,21 +180,16 @@ public function __construct( array $config = [] ) { $handlerOptions = []; - foreach (['max_host_connections', 'max_total_connections'] as $capOption) { - if (\array_key_exists($capOption, $config)) { - if ($config[$capOption] !== null) { - $handlerOptions[$capOption] = $config[$capOption]; + foreach (['max_host_connections', 'max_idle_handles', 'max_idle_multi_handlers', 'max_total_connections'] as $handlerOption) { + if (\array_key_exists($handlerOption, $config)) { + if ($config[$handlerOption] !== null) { + $handlerOptions[$handlerOption] = $config[$handlerOption]; } - unset($config[$capOption]); + unset($config[$handlerOption]); } } - $maxIdleHandles = $config['max_idle_handles'] ?? null; - unset($config['max_idle_handles']); - $maxIdleMultiHandlers = $config['max_idle_multi_handlers'] ?? null; - unset($config['max_idle_multi_handlers']); - // Deliberately not unset: the value also becomes the default // "multiplex" request option, which the configured handler accepts. $handlerMultiplex = ($config['multiplex'] ?? null) === Multiplexing::NONE; @@ -205,14 +199,6 @@ public function __construct( unset($config['transport_sharing']); if (!isset($config['handler'])) { - if ($maxIdleHandles !== null) { - $handlerOptions['max_idle_handles'] = $maxIdleHandles; - } - - if ($maxIdleMultiHandlers !== null) { - $handlerOptions['max_idle_multi_handlers'] = $maxIdleMultiHandlers; - } - if ($transportSharingMode !== TransportSharing::NONE) { $handlerOptions['transport_sharing'] = $transportSharingMode; } @@ -226,9 +212,9 @@ public function __construct( : HandlerStack::create(Utils::chooseHandler($handlerOptions)); } elseif (!\is_callable($config['handler'])) { throw new InvalidArgumentException('handler must be a callable'); - } elseif ($maxIdleHandles !== null) { + } elseif (isset($handlerOptions['max_idle_handles'])) { throw new InvalidArgumentException('The "max_idle_handles" client option requires Guzzle to create the default handler. Configure the option on the CurlHandler or CurlMultiHandler constructor when providing a custom handler.'); - } elseif ($maxIdleMultiHandlers !== null) { + } elseif (isset($handlerOptions['max_idle_multi_handlers'])) { throw new InvalidArgumentException('The "max_idle_multi_handlers" client option requires Guzzle to create the default handler. Configure the idle pool on ContextualCurlMultiHandler when providing a custom handler.'); } elseif ($handlerOptions !== []) { throw new InvalidArgumentException('The "max_host_connections" and "max_total_connections" client options require Guzzle to create the default handler. Configure the options on the CurlMultiHandler constructor for numeric enforcement, or on the StreamHandler constructor to reject enabled response streaming, when providing a custom handler.'); @@ -748,6 +734,11 @@ public static function removeGlobalMiddleware(string $name): void unset(self::$globalMiddleware[$name]); } + private static function defaultUserAgent(): string + { + return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION); + } + private function buildUri( UriInterface $uri, #[\SensitiveParameter] @@ -959,7 +950,7 @@ private function configureDefaults( // Add the default user-agent header. if (!isset($this->config['headers'])) { - $this->config['headers'] = ['User-Agent' => Utils::defaultUserAgent()]; + $this->config['headers'] = ['User-Agent' => self::defaultUserAgent()]; } else { self::assertHeaderOptionTypes($this->config['headers']); @@ -973,7 +964,7 @@ private function configureDefaults( } if (!$hasUserAgent) { - $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + $this->config['headers']['User-Agent'] = self::defaultUserAgent(); } } } diff --git a/src/Cookie/CookieJar.php b/src/Cookie/CookieJar.php index e3ed1d1e3..e9ed31971 100644 --- a/src/Cookie/CookieJar.php +++ b/src/Cookie/CookieJar.php @@ -196,6 +196,8 @@ public function setCookie( } // Resolve conflicts with previously set cookies + $replaced = false; + $unchanged = false; foreach ($this->cookies as $i => $c) { // Two cookies are identical, when their path, and domain are // identical. @@ -207,22 +209,43 @@ public function setCookie( continue; } - // Replace the old cookie when its value, expiry or flags changed + // An expired cookie is gone, so it must not lend its position + if ($c->isExpired()) { + unset($this->cookies[$i]); + continue; + } + + // A stored cookie can be mutated into a duplicate, so drop later matches + if ($replaced || $unchanged) { + unset($this->cookies[$i]); + continue; + } + + // Replace the old cookie in place when its value, expiry or flags + // changed, so it keeps its position among the other cookies if ($cookie->getValue() !== $c->getValue() || $cookie->getExpires() !== $c->getExpires() || $cookie->getDiscard() !== $c->getDiscard() || $cookie->getSecure() !== $c->getSecure() || $cookie->getHttpOnly() !== $c->getHttpOnly() ) { - unset($this->cookies[$i]); + $this->cookies[$i] = $cookie; + $replaced = true; continue; } - // The cookie exists, so no need to continue + // The cookie exists. Upstream returns here, which skips dropping + // later duplicates, so keep scanning + $unchanged = true; + } + + if ($unchanged) { return false; } - $this->cookies[] = $cookie; + if (!$replaced) { + $this->cookies[] = $cookie; + } return true; } @@ -369,6 +392,7 @@ public function withCookieHeader( RequestInterface $request ): RequestInterface { $values = []; + $count = 0; $headerLength = 8; $uri = $request->getUri(); $scheme = $uri->getScheme(); @@ -390,16 +414,20 @@ public function withCookieHeader( break; } - $values[] = $name.'='.$value; + $values[\strlen($cookie->getPath())][] = $name.'='.$value; $headerLength += $separatorLength + $valueLength; - if (\count($values) === self::MAX_REQUEST_COOKIES) { + if (++$count === self::MAX_REQUEST_COOKIES) { break; } } } + // Longer paths first, then creation order, as in RFC 6265 section 5.4, + // sorted after the limits so later cookies cannot crowd out older ones + \krsort($values); + return $values - ? $request->withHeader('Cookie', \implode('; ', $values)) + ? $request->withHeader('Cookie', \implode('; ', \array_merge(...$values))) : $request; } diff --git a/src/Exception/RequestException.php b/src/Exception/RequestException.php index c14fb54d8..b18c524af 100644 --- a/src/Exception/RequestException.php +++ b/src/Exception/RequestException.php @@ -60,7 +60,7 @@ public static function create( $label = 'Unsuccessful request'; } - $uri = \GuzzleHttp\Psr7\Utils::redactUriForMessage($request->getUri()); + $uri = \GuzzleHttp\Psr7\UriRedactor::redactUriForMessage($request->getUri()); // Client error: `GET /` resulted in a `404 Not Found` response: ... (truncated) $message = \sprintf( diff --git a/src/Handler/ContextualCurlMultiHandler.php b/src/Handler/ContextualCurlMultiHandler.php index da238d212..1a4a70594 100644 --- a/src/Handler/ContextualCurlMultiHandler.php +++ b/src/Handler/ContextualCurlMultiHandler.php @@ -18,7 +18,7 @@ * connections. Concurrent coroutines use separate handlers; requests in the * same coroutine share a handler while its transfers are active. * - * @see https://github.com/hypervel/guzzle/blob/8.3/docs/handlers.md#coroutine-handlers + * @see https://github.com/hypervel/guzzle/blob/8.5/docs/handlers.md#coroutine-handlers */ final class ContextualCurlMultiHandler { diff --git a/src/Handler/CurlFactory.php b/src/Handler/CurlFactory.php index aa3e6db42..2a8d01aab 100644 --- a/src/Handler/CurlFactory.php +++ b/src/Handler/CurlFactory.php @@ -26,7 +26,6 @@ use GuzzleHttp\RequestOptions; use GuzzleHttp\TransferStats; use GuzzleHttp\TransportSharing; -use GuzzleHttp\Utils; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamFactoryInterface; @@ -1412,7 +1411,7 @@ private static function createRejection( ); if ('' !== $sanitizedError) { - $safeUri = Psr7\Utils::redactUriForMessage($uri); + $safeUri = Psr7\UriRedactor::redactUriForMessage($uri); if ($safeUri !== '' && false === \strpos($sanitizedError, $safeUri)) { $message .= \sprintf(' for %s', $safeUri); } @@ -1525,7 +1524,7 @@ private static function redactProxyUserInfo( return $error; } - return Psr7\Utils::redactUserInfoInString($error, $proxy); + return Psr7\UriRedactor::redactUserInfoInString($error, $proxy); } /** @@ -2161,7 +2160,7 @@ private function getDefaultConf( EasyHandle $easy ): array { $uri = $easy->request->getUri(); - $protocols = Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']); + $protocols = Protocols::normalize($easy->options['protocols'] ?? ['http', 'https']); $scheme = $uri->getScheme(); if (!\in_array($scheme, $protocols, true)) { throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', Psr7\DiagnosticValue::escape($scheme)), $easy->request); @@ -2856,7 +2855,7 @@ private function applyHandlerOptions( } if (!empty($options['debug'])) { - $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']); + $conf[\CURLOPT_STDERR] = DebugResource::from($options['debug']); $conf[\CURLOPT_VERBOSE] = true; } } diff --git a/src/Handler/CurlHandler.php b/src/Handler/CurlHandler.php index f588aef6d..f22e87515 100644 --- a/src/Handler/CurlHandler.php +++ b/src/Handler/CurlHandler.php @@ -42,8 +42,7 @@ final class CurlHandler * * - handle_factory: Optional curl factory used to create cURL handles. * - max_idle_handles: Optional maximum number of idle cURL easy handles. - * Accepts a non-negative integer or null. Zero disables idle handle - * retention; null or omission keeps the default of 256. + * Zero disables retention; null or omission keeps the default of 256. * - transport_sharing: Optional transport sharing mode. * * @param array{handle_factory?: ?CurlFactoryInterface, max_idle_handles?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler @@ -56,19 +55,20 @@ public function __construct(array $options = []) } } + CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler'); + $transportSharing = $options['transport_sharing'] ?? null; + $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); + $maxIdleHandles = $options['max_idle_handles'] ?? 256; if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); } - if (isset($options['max_idle_handles'], $options['handle_factory'])) { - throw new InvalidArgumentException('The "max_idle_handles" option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); - } - - CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler'); - $transportSharing = $options['transport_sharing'] ?? null; - $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { + if (isset($options['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + } + $this->shareHandleState = null; $this->factory = $options['handle_factory']; $this->ownsFactory = false; diff --git a/src/Handler/CurlMultiHandler.php b/src/Handler/CurlMultiHandler.php index 099f9491a..940c12c48 100644 --- a/src/Handler/CurlMultiHandler.php +++ b/src/Handler/CurlMultiHandler.php @@ -194,13 +194,12 @@ final class CurlMultiHandler * This handler accepts the following options: * * - handle_factory: An optional factory used to create curl handles - * - max_idle_handles: Optional maximum number of idle cURL easy handles. - * Accepts a non-negative integer or null. Zero disables idle handle - * retention; null or omission keeps the default of 50. * - transport_sharing: Optional transport sharing mode. * - select_timeout: Optional timeout (in seconds) to block before timing * out while selecting curl handles. Defaults to 1 second. * - max_host_connections: Optional maximum concurrent connections per host. + * - max_idle_handles: Optional maximum number of idle cURL easy handles. + * Zero disables retention; null or omission keeps the default of 50. * - max_total_connections: Optional maximum concurrent connections overall. * - multiplex: Optional Multiplexing::NONE to disallow multiplexing on * this handler's multi handle. The eager, wait, and required modes are @@ -234,14 +233,6 @@ public function __construct(array $options = []) throw new InvalidArgumentException('The "multiplex" CurlMultiHandler option requires CURLMOPT_PIPELINING, but it is not available in the installed PHP cURL extension.'); } - $maxIdleHandles = $options['max_idle_handles'] ?? 50; - if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { - throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); - } - if (isset($options['max_idle_handles'], $options['handle_factory'])) { - throw new InvalidArgumentException('The "max_idle_handles" option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); - } - CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlMultiHandler'); $transportSharing = $options['transport_sharing'] ?? null; $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); @@ -284,7 +275,16 @@ public function __construct(array $options = []) } } + $maxIdleHandles = $options['max_idle_handles'] ?? 50; + if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { + throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); + } + if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { + if (isset($options['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" CurlMultiHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + } + $this->shareHandleState = null; $this->factory = $options['handle_factory']; $this->ownsFactory = false; diff --git a/src/Handler/DebugResource.php b/src/Handler/DebugResource.php new file mode 100644 index 000000000..c2bdc38da --- /dev/null +++ b/src/Handler/DebugResource.php @@ -0,0 +1,36 @@ +options['decode_content'] ?? false; if ($framingFailure === null && $decodeContent !== false && isset($normalizedKeys['content-encoding'])) { $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; diff --git a/src/Handler/HeaderProcessor.php b/src/Handler/HeaderProcessor.php index cdd5d2c7d..9ebf46b8d 100644 --- a/src/Handler/HeaderProcessor.php +++ b/src/Handler/HeaderProcessor.php @@ -5,7 +5,6 @@ namespace GuzzleHttp\Handler; use GuzzleHttp\Psr7; -use GuzzleHttp\Utils; /** * @internal @@ -25,8 +24,11 @@ private function __construct() * * @throws \RuntimeException */ - public static function parseHeaders(array $headers): array - { + public static function parseHeaders( + // Unlike upstream, keep headers out of traces as they can carry credentials + #[\SensitiveParameter] + array $headers + ): array { if ($headers === []) { throw new \RuntimeException('Expected a non-empty array of header data'); } @@ -73,7 +75,28 @@ public static function parseHeaders(array $headers): array } } - return [$version, (int) $status, $reason, Utils::headersFromLines($headers)]; + return [$version, (int) $status, $reason, self::headersFromLines($headers)]; + } + + /** + * Parses an array of header lines into an associative array of headers. + * + * @param iterable $lines Header lines array of strings in the following + * format: "Name: Value" + */ + public static function headersFromLines( + // Unlike upstream, keep headers out of traces as they can carry credentials + #[\SensitiveParameter] + iterable $lines + ): array { + $headers = []; + + foreach ($lines as $line) { + $parts = \explode(':', $line, 2); + $headers[\trim($parts[0], " \n\r\t\0\x0B")][] = isset($parts[1]) ? \trim($parts[1], " \n\r\t\0\x0B") : null; + } + + return $headers; } public static function isStatusLineCandidate(string $line): bool @@ -171,13 +194,15 @@ public static function assertContentLengthWithinPlatformLimit(?string $length): public static function validateResponseFraming( string $method, int $status, + // Unlike upstream, keep headers out of traces as they can carry credentials + #[\SensitiveParameter] array $headers ): ?string { if (!self::responseCanHaveBody($method, $status)) { return null; } - $normalizedKeys = Utils::normalizeHeaderKeys($headers); + $normalizedKeys = self::normalizeHeaderKeys($headers); $contentLength = self::removeHeader('Content-Length', $headers); try { @@ -207,8 +232,11 @@ public static function validateResponseFraming( * @throws \RuntimeException when a coding is unsupported or follows chunked * on the same field line */ - public static function parseTransferEncoding(array $headers): bool - { + public static function parseTransferEncoding( + // Unlike upstream, keep headers out of traces as they can carry credentials + #[\SensitiveParameter] + array $headers + ): bool { $chunked = false; foreach ($headers as $name => $values) { @@ -264,6 +292,20 @@ public static function removeHeader(string $name, array &$headers): array return $values; } + /** + * Creates an associative array of lowercase header names to the actual + * header casing. + */ + public static function normalizeHeaderKeys(array $headers): array + { + $result = []; + foreach (\array_keys($headers) as $key) { + $result[Psr7\Utils::asciiToLower((string) $key)] = $key; + } + + return $result; + } + /** * Whether a response uses ordinary body framing. A response to HEAD, a * response with a 1xx, 204, or 304 status code, or a 2xx response to diff --git a/src/Handler/Protocols.php b/src/Handler/Protocols.php new file mode 100644 index 000000000..2860308cf --- /dev/null +++ b/src/Handler/Protocols.php @@ -0,0 +1,47 @@ + $msg, - 'file' => $file, - 'line' => $line, - ]; - - return true; - }); - - try { - $resource = $callback(); - } finally { - \restore_error_handler(); - } + $scope = new Psr7\ErrorScope(); + $resource = $scope->run($callback); if (!$resource) { $details = []; - foreach ($errors as $err) { + foreach ($scope->getErrors() as $err) { foreach ($err as $key => $value) { $rendered = $key === 'message' && $diagnosticUri !== null ? UriDiagnostic::redactInMessage((string) $value, $diagnosticUri) @@ -1025,12 +1020,21 @@ static function () use ($context, $params) { // Blank the from ini setting for the transfer so ambient // configuration cannot leak into a From header; the wrapper // cannot omit the header, so a configured ini sends it empty. - $iniFrom = \function_exists('ini_set') ? \ini_set('from', '') : false; + // An empty setting is left alone, as blanking an unset one adds + // the header. Overlapping transfers share the setting, so only + // the first one saves it and only the last one restores it. + $blankFrom = \function_exists('ini_set'); + if ($blankFrom) { + $iniFrom = \ini_get('from') !== '' ? \ini_set('from', '') : false; + if (self::$fromBlankDepth++ === 0) { + self::$fromToRestore = $iniFrom; + } + } try { $resource = @\fopen((string) $uri, 'r', false, $contextResource); } finally { - if ($iniFrom !== false) { - \ini_set('from', $iniFrom); + if ($blankFrom && --self::$fromBlankDepth === 0 && self::$fromToRestore !== false) { + \ini_set('from', self::$fromToRestore); } } @@ -1133,7 +1137,7 @@ private static function assertRequestUriSupported( throw new RequestException(\sprintf("The scheme '%s' is not supported.", Psr7\DiagnosticValue::escape($scheme)), $request); } - $protocols = Utils::normalizeProtocols($options['protocols'] ?? ['http', 'https']); + $protocols = Protocols::normalize($options['protocols'] ?? ['http', 'https']); if (!\in_array($scheme, $protocols, true)) { throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', Psr7\DiagnosticValue::escape($scheme)), $request); } @@ -2022,7 +2026,7 @@ private function applyDebugOption( ]; static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; - $value = Utils::debugResource($value); + $value = DebugResource::from($value); $ident = $request->getMethod().' '.$request->getUri()->withFragment(''); self::addNotification( $params, diff --git a/src/Handler/UriDiagnostic.php b/src/Handler/UriDiagnostic.php index 61028a27f..660a1315c 100644 --- a/src/Handler/UriDiagnostic.php +++ b/src/Handler/UriDiagnostic.php @@ -22,7 +22,7 @@ public static function redactInMessage( #[\SensitiveParameter] UriInterface $uri ): string { - $message = Psr7\Utils::redactUserInfoInString($message, (string) $uri); + $message = Psr7\UriRedactor::redactUserInfoInString($message, (string) $uri); $query = $uri->getQuery(); if ($query !== '') { diff --git a/src/RedirectMiddleware.php b/src/RedirectMiddleware.php index 9b23a28e2..280576d91 100644 --- a/src/RedirectMiddleware.php +++ b/src/RedirectMiddleware.php @@ -351,12 +351,12 @@ private static function redirectUri( $resolvedUri = $uriFactory->createUri((string) $resolvedUri); } } catch (\InvalidArgumentException $e) { - throw new BadResponseException(\sprintf('Redirect URI, %s, is invalid.', Psr7\Utils::redactUriStringForMessage($location)), $request, $response, $e); + throw new BadResponseException(\sprintf('Redirect URI, %s, is invalid.', Psr7\UriRedactor::redactUriStringForMessage($location)), $request, $response, $e); } // Ensure that the redirect URI is allowed based on the protocols. if (!\in_array($resolvedUri->getScheme(), $protocols, true)) { - throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', Psr7\Utils::redactUriForMessage($resolvedUri), \implode(', ', $protocols)), $request, $response); + throw new BadResponseException(\sprintf('Redirect URI, %s, does not use one of the allowed redirect protocols: %s', Psr7\UriRedactor::redactUriForMessage($resolvedUri), \implode(', ', $protocols)), $request, $response); } return $resolvedUri; diff --git a/src/RequestOptions.php b/src/RequestOptions.php index 7fe973dbd..a784978a7 100644 --- a/src/RequestOptions.php +++ b/src/RequestOptions.php @@ -12,7 +12,7 @@ /** * This class contains a list of built-in Guzzle request options. * - * @see https://github.com/guzzle/guzzle/blob/8.3/docs/request-options.md + * @see https://github.com/guzzle/guzzle/blob/8.5/docs/request-options.md */ final class RequestOptions { diff --git a/src/Utils.php b/src/Utils.php index c82032390..c254c2bb4 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -10,6 +10,9 @@ use GuzzleHttp\Handler\CurlMultiHandler; use GuzzleHttp\Handler\CurlShareHandleState; use GuzzleHttp\Handler\CurlVersion; +use GuzzleHttp\Handler\DebugResource; +use GuzzleHttp\Handler\HeaderProcessor; +use GuzzleHttp\Handler\Protocols; use GuzzleHttp\Handler\Proxy; use GuzzleHttp\Handler\StreamHandler; use GuzzleHttp\Handler\StreamTlsSessionCache; @@ -19,6 +22,11 @@ final class Utils { + /** + * @var (callable(array, callable(): callable): callable)|null + */ + private static $defaultHandlerFactory; + private function __construct() { } @@ -28,17 +36,23 @@ private function __construct() * * @param iterable $lines Header lines array of strings in the following * format: "Name: Value" + * + * @deprecated Utils::headersFromLines() will be removed in + * guzzlehttp/guzzle:9.0. */ - public static function headersFromLines(iterable $lines): array - { - $headers = []; - - foreach ($lines as $line) { - $parts = \explode(':', $line, 2); - $headers[\trim($parts[0], " \n\r\t\0\x0B")][] = isset($parts[1]) ? \trim($parts[1], " \n\r\t\0\x0B") : null; - } - - return $headers; + public static function headersFromLines( + // Unlike upstream, keep headers out of traces as they can carry credentials + #[\SensitiveParameter] + iterable $lines + ): array { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return HeaderProcessor::headersFromLines($lines); } /** @@ -47,17 +61,39 @@ public static function headersFromLines(iterable $lines): array * @param mixed $value Optional value * * @return resource + * + * @deprecated Utils::debugResource() will be removed in + * guzzlehttp/guzzle:9.0. */ public static function debugResource($value = null) { - if (\is_resource($value)) { - return $value; - } - if (\defined('STDOUT')) { - return \STDOUT; - } + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return DebugResource::from($value); + } - return Psr7\Utils::tryFopen('php://output', 'w'); + /** + * Sets a factory that creates the default handler in place of the built-in + * selection. + * + * The factory receives the handler options and a callable that returns the + * handler Guzzle would have chosen. It is consulted each time a default + * handler is chosen, after the handler options have been checked for type + * and value. Passing null restores the built-in selection. + * + * The factory is process-wide, so set it from application bootstrap code, + * not from a library. + * + * @param (callable(array, callable(): callable): callable)|null $factory + */ + public static function setDefaultHandlerFactory(?callable $factory): void + { + self::$defaultHandlerFactory = $factory; } /** @@ -65,6 +101,9 @@ public static function debugResource($value = null) * * The returned handler is not wrapped by any default middlewares. * + * A factory set with setDefaultHandlerFactory() creates the handler in + * place of the built-in selection. + * * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_idle_handles?: mixed, max_idle_multi_handlers?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options. * * @return callable(RequestInterface, array): PromiseInterface Returns the best handler for the given system. @@ -73,6 +112,10 @@ public static function debugResource($value = null) */ public static function chooseHandler(array $handlerOptions = []): callable { + $sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing'); + $sharingRequired = self::isTransportSharingRequired($sharingMode); + $connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions); + $maxIdleHandles = $handlerOptions['max_idle_handles'] ?? null; if ($maxIdleHandles !== null && (!\is_int($maxIdleHandles) || $maxIdleHandles < 0)) { throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); @@ -83,14 +126,26 @@ public static function chooseHandler(array $handlerOptions = []): callable throw new InvalidArgumentException('max_idle_multi_handlers must be a non-negative integer.'); } - $sharingMode = CurlShareHandleState::normalizeMode($handlerOptions['transport_sharing'] ?? null, 'transport_sharing'); - $sharingRequired = self::isTransportSharingRequired($sharingMode); - $connectionCapsRequired = self::hasConnectionCapOptions($handlerOptions); - if ($maxIdleMultiHandlers !== null && $connectionCapsRequired) { throw new InvalidArgumentException('The "max_idle_multi_handlers" option cannot be combined with connection caps, which require one shared cURL multi handler.'); } + if (self::$defaultHandlerFactory === null) { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions, $maxIdleMultiHandlers); + } + + return (self::$defaultHandlerFactory)($handlerOptions, static function () use ($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions, $maxIdleMultiHandlers): callable { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions, $maxIdleMultiHandlers); + }); + } + + /** + * @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions + * + * @return callable(RequestInterface, array): PromiseInterface + */ + private static function chooseBuiltInHandler(string $sharingMode, bool $sharingRequired, bool $connectionCapsRequired, array $handlerOptions, ?int $maxIdleMultiHandlers): callable + { $sharedPoolCapsSupported = CurlVersion::supportsSharedPoolConnectionCaps(); if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_REQUIRE) { @@ -283,24 +338,41 @@ private static function addStreamHandler(?callable $handler, string $sharingMode /** * Get the default User-Agent string to use with Guzzle. + * + * @deprecated Utils::defaultUserAgent() will be removed in + * guzzlehttp/guzzle:9.0. Use ClientInterface::MAJOR_VERSION + * to build the string instead. */ public static function defaultUserAgent(): string { + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0. Use %s::MAJOR_VERSION to build the string instead.', + __METHOD__, + ClientInterface::class + ); + return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION); } /** * Creates an associative array of lowercase header names to the actual * header casing. + * + * @deprecated Utils::normalizeHeaderKeys() will be removed in + * guzzlehttp/guzzle:9.0. */ public static function normalizeHeaderKeys(array $headers): array { - $result = []; - foreach (\array_keys($headers) as $key) { - $result[Psr7\Utils::asciiToLower((string) $key)] = $key; - } - - return $result; + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return HeaderProcessor::normalizeHeaderKeys($headers); } /** @@ -309,27 +381,19 @@ public static function normalizeHeaderKeys(array $headers): array * @return string[] * * @throws InvalidArgumentException + * + * @deprecated Utils::normalizeProtocols() will be removed in + * guzzlehttp/guzzle:9.0. */ public static function normalizeProtocols($protocols): array { - if (!\is_array($protocols) || $protocols === []) { - throw new InvalidArgumentException('protocols must be a non-empty array of "http" and/or "https"'); - } - - $normalized = []; - - foreach ($protocols as $protocol) { - if (!\is_string($protocol)) { - throw new InvalidArgumentException('protocols must contain only strings'); - } - - if ($protocol !== 'http' && $protocol !== 'https') { - throw new InvalidArgumentException('protocols may only contain "http" and "https"'); - } - - $normalized[$protocol] = true; - } - - return \array_keys($normalized); + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return Protocols::normalize($protocols); } } diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 660546def..3bb745544 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -450,60 +450,69 @@ public function testConnectionCapClientOptionsCannotBeUsedWithCustomHandler(stri ]); } - /** - * @dataProvider idleLimitOptionProvider - */ - public function testRejectsInvalidIdleLimits(string $option): void + public function testMaxIdleHandlesClientOptionCannotBeUsedWithCustomHandler(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage($option.' must be a non-negative integer.'); + $this->expectExceptionMessage('The "max_idle_handles" client option requires Guzzle to create the default handler. Configure the option on the CurlHandler or CurlMultiHandler constructor when providing a custom handler.'); - new Client([$option => -1]); + new Client([ + 'handler' => new MockHandler(), + 'max_idle_handles' => 4, + ]); } - /** - * @dataProvider idleLimitOptionProvider - */ - public function testIdleLimitsCannotBeUsedWithCustomHandler(string $option): void + public function testMaxIdleMultiHandlersClientOptionCannotBeUsedWithCustomHandler(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "'.$option.'" client option requires Guzzle to create the default handler.'); + $this->expectExceptionMessage('The "max_idle_multi_handlers" client option requires Guzzle to create the default handler. Configure the idle pool on ContextualCurlMultiHandler when providing a custom handler.'); - new Client([$option => 0, 'handler' => new MockHandler()]); + new Client([ + 'handler' => new MockHandler(), + 'max_idle_multi_handlers' => 4, + ]); } - public static function idleLimitOptionProvider(): iterable + public function testMaxIdleMultiHandlersClientOptionCannotBeCombinedWithConnectionCaps(): void { - yield 'easy handles' => ['max_idle_handles']; - yield 'multi handlers' => ['max_idle_multi_handlers']; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "max_idle_multi_handlers" option cannot be combined with connection caps, which require one shared cURL multi handler.'); + + new Client([ + 'max_idle_multi_handlers' => 4, + 'max_total_connections' => 2, + ]); } - public function testNullMaxIdleHandlesCanBeUsedWithCustomHandler(): void + public function testNullConnectionCapClientOptionsCanBeUsedWithCustomHandler(): void { - $client = new Client(['max_idle_handles' => null, 'max_idle_multi_handlers' => null, 'handler' => new MockHandler()]); + $client = new Client([ + 'handler' => new MockHandler(), + 'max_host_connections' => null, + 'max_total_connections' => null, + ]); - self::assertArrayNotHasKey('max_idle_handles', $client->getConfig()); - self::assertArrayNotHasKey('max_idle_multi_handlers', $client->getConfig()); + self::assertNull($client->getConfig('max_host_connections')); + self::assertNull($client->getConfig('max_total_connections')); } - public function testIdleHandlerLimitCannotBeCombinedWithConnectionCaps(): void + public function testNullMaxIdleHandlesClientOptionCanBeUsedWithCustomHandler(): void { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "max_idle_multi_handlers" option cannot be combined with connection caps'); + $client = new Client([ + 'handler' => new MockHandler(), + 'max_idle_handles' => null, + ]); - new Client(['max_idle_multi_handlers' => 1, 'max_total_connections' => 2]); + self::assertArrayNotHasKey('max_idle_handles', $client->getConfig()); } - public function testNullConnectionCapClientOptionsCanBeUsedWithCustomHandler(): void + public function testNullMaxIdleMultiHandlersClientOptionCanBeUsedWithCustomHandler(): void { $client = new Client([ 'handler' => new MockHandler(), - 'max_host_connections' => null, - 'max_total_connections' => null, + 'max_idle_multi_handlers' => null, ]); - self::assertNull($client->getConfig('max_host_connections')); - self::assertNull($client->getConfig('max_total_connections')); + self::assertArrayNotHasKey('max_idle_multi_handlers', $client->getConfig()); } /** @@ -525,6 +534,44 @@ public function testRejectsInvalidConnectionCapClientOptionsWhenCurlCannotApplyT } } + /** + * @dataProvider invalidMaxIdleHandlesClientOptionProvider + * + * @param mixed $value + */ + public function testRejectsInvalidMaxIdleHandlesClientOptionWhenCurlIsUnavailable($value): void + { + $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); + + try { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('max_idle_handles must be a non-negative integer.'); + + new Client(['max_idle_handles' => $value]); + } finally { + self::setCurlVersionInfo($previousVersionInfo); + } + } + + /** + * @dataProvider invalidMaxIdleHandlesClientOptionProvider + * + * @param mixed $value + */ + public function testRejectsInvalidMaxIdleMultiHandlersClientOptionWhenCurlIsUnavailable($value): void + { + $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); + + try { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('max_idle_multi_handlers must be a non-negative integer.'); + + new Client(['max_idle_multi_handlers' => $value]); + } finally { + self::setCurlVersionInfo($previousVersionInfo); + } + } + public function testConnectionCapsComposeWithTransportSharing(): void { self::skipIfDefaultCurlHandlerIsUnavailable(); @@ -702,6 +749,13 @@ public static function invalidConnectionCapClientOptionProvider(): iterable } } + public static function invalidMaxIdleHandlesClientOptionProvider(): iterable + { + yield 'negative' => [-1]; + yield 'float' => [1.0]; + yield 'string' => ['1']; + } + public static function strictTransportSharingModeProvider(): iterable { yield 'handler require' => [TransportSharing::HANDLER_REQUIRE, 'Configure the "transport_sharing" option on CurlHandler, CurlMultiHandler, or StreamHandler when providing a custom handler.']; diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index 2667b8add..64e0b59e5 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -619,6 +619,55 @@ public static function changedAttributeProvider(): array ]; } + public function testReplacementKeepsCookiePosition(): void + { + $request = new Request('GET', 'https://example.com/'); + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => ['a=1; Path=/', 'b=1; Path=/', 'c=1; Path=/']])); + self::assertSame('a=1; b=1; c=1', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'b=2; Path=/'])); + + self::assertSame('a=1; b=2; c=1', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + } + + public function testReplacementOfExpiredCookieDoesNotKeepPosition(): void + { + $request = new Request('GET', 'https://example.com/'); + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => ['a=1; Path=/', 'b=1; Path=/', 'c=1; Path=/']])); + $this->jar->getCookieByName('b')->setExpires(1); + + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'b=2; Path=/'])); + + self::assertCount(3, $this->jar); + self::assertSame('a=1; c=1; b=2', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + } + + public function testReplacementRemovesStoredCookieChangedIntoDuplicate(): void + { + $request = new Request('GET', 'https://example.com/'); + $this->jar->extractCookies(new Request('GET', 'https://example.com/app/login'), new Response(200, ['Set-Cookie' => 'sid=abc; Path=/app'])); + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'sid=abc; Path=/'])); + $this->jar->getCookieByName('sid')->setPath('/'); + + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'sid=rotated; Path=/'])); + + self::assertCount(1, $this->jar); + self::assertSame('sid=rotated', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + } + + public function testUnchangedCookieRemovesStoredCookieChangedIntoDuplicate(): void + { + $request = new Request('GET', 'https://example.com/'); + $this->jar->extractCookies(new Request('GET', 'https://example.com/app/login'), new Response(200, ['Set-Cookie' => 'sid=abc; Path=/app'])); + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'sid=stale; Path=/'])); + $cookie = $this->jar->getCookieByName('sid'); + $cookie->setPath('/'); + + self::assertFalse($this->jar->setCookie(clone $cookie)); + self::assertCount(1, $this->jar); + self::assertSame('sid=abc', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + } + public function testDistinctNumericStringCookieNamesCoexist(): void { $this->jar->setCookie(new SetCookie([ @@ -758,6 +807,21 @@ public function testLimitsGeneratedCookieHeaderToOneHundredAndFiftyCookies(): vo self::assertNotContains('c150=value', $values); } + public function testAppliesOutputLimitsBeforeSortingByPath(): void + { + $this->jar->setCookie(new SetCookie(['Name' => 'root', 'Value' => 'value', 'Domain' => 'example.com'])); + for ($i = 0; $i < 150; ++$i) { + $this->jar->setCookie(new SetCookie(['Name' => "c{$i}", 'Value' => 'value', 'Domain' => 'example.com', 'Path' => '/app'])); + } + + $values = \explode('; ', $this->jar->withCookieHeader(new Request('GET', 'https://example.com/app/check'))->getHeaderLine('Cookie')); + + self::assertCount(150, $values); + self::assertSame('c0=value', $values[0]); + self::assertSame('root=value', $values[149]); + self::assertNotContains('c149=value', $values); + } + public function testLimitsGeneratedCookieHeaderLengthAndStopsAtFirstOverflow(): void { $exact = new CookieJar(); @@ -1061,6 +1125,24 @@ public function testConstructorDropsExpiredCookies(): void self::assertCount(0, $jar); } + public function testSendsLongerPathCookiesFirst(): void + { + $this->jar->extractCookies(new Request('GET', 'https://example.com/'), new Response(200, ['Set-Cookie' => 'sid=root; Path=/'])); + $this->jar->extractCookies(new Request('GET', 'https://example.com/app/login'), new Response(200, ['Set-Cookie' => 'sid=specific; Path=/app'])); + + $request = $this->jar->withCookieHeader(new Request('GET', 'https://example.com/app/check')); + + self::assertSame('sid=specific; sid=root', $request->getHeaderLine('Cookie')); + } + + public function testKeepsInsertionOrderForEqualPaths(): void + { + $request = new Request('GET', 'https://example.com/'); + $this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => ['a=1; Path=/', 'b=1; Path=/', 'c=1; Path=/']])); + + self::assertSame('a=1; b=1; c=1', $this->jar->withCookieHeader($request)->getHeaderLine('Cookie')); + } + public function testDoesNotSendHostOnlyCookieToSubdomain(): void { $this->jar->extractCookies( diff --git a/tests/Handler/CurlHandlerTest.php b/tests/Handler/CurlHandlerTest.php index ecc263a22..5e1121aff 100644 --- a/tests/Handler/CurlHandlerTest.php +++ b/tests/Handler/CurlHandlerTest.php @@ -173,17 +173,6 @@ public function testReusesHandles(): void self::assertInstanceOf(FulfilledPromise::class, $a($request, [])); } - public function testClosePreventsReuse(): void - { - $handler = new CurlHandler(); - $handler->close(); - - $this->expectException(\BadMethodCallException::class); - $this->expectExceptionMessage('Cannot use the cURL handler after it has been closed.'); - - $handler(new Request('GET', Server::$url), []); - } - /** * @dataProvider maxIdleHandlesProvider */ @@ -195,27 +184,44 @@ public function testMaxIdleHandlesControlsRetention(array $options, int $expecte $handler = new CurlHandler($options); $factory = self::readFactory($handler); - $handles = []; + $easyHandles = []; for ($i = 0; $i <= $expected; ++$i) { - $handles[] = $factory->create(new Request('GET', Server::$url), []); + $easyHandles[] = $factory->create(new Request('GET', Server::$url), []); } - foreach ($handles as $handle) { - $factory->release($handle); + foreach ($easyHandles as $easy) { + $factory->release($easy); } self::assertCount($expected, self::readIdleHandles($factory)); } - public static function maxIdleHandlesProvider(): array + public static function maxIdleHandlesProvider(): iterable { - return [ - 'default' => [[], 256], - 'null' => [['max_idle_handles' => null], 256], - 'disabled' => [['max_idle_handles' => 0], 0], - 'increased' => [['max_idle_handles' => 257], 257], - 'shared' => [['max_idle_handles' => 4, 'transport_sharing' => TransportSharing::HANDLER_PREFER], 4], - ]; + yield 'default' => [[], 256]; + yield 'null' => [['max_idle_handles' => null], 256]; + yield 'disabled' => [['max_idle_handles' => 0], 0]; + yield 'increased' => [['max_idle_handles' => 257], 257]; + yield 'shared' => [['max_idle_handles' => 4, 'transport_sharing' => TransportSharing::HANDLER_PREFER], 4]; + } + + public function testClosePreventsReuse(): void + { + $handler = new CurlHandler(); + $handler->close(); + + $this->expectException(\BadMethodCallException::class); + $this->expectExceptionMessage('Cannot use the cURL handler after it has been closed.'); + + $handler(new Request('GET', Server::$url), []); + } + + public function testRejectsUnknownConstructorOption(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid CurlHandler constructor option "unknown".'); + + new CurlHandler(['unknown' => true]); } /** @@ -231,28 +237,11 @@ public function testRejectsInvalidMaxIdleHandles($value): void new CurlHandler(['max_idle_handles' => $value]); } - public static function invalidMaxIdleHandlesProvider(): array + public static function invalidMaxIdleHandlesProvider(): iterable { - return [[-1], ['4']]; - } - - public function testMaxIdleHandlesCannotBeUsedWithCustomFactory(): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "max_idle_handles" option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); - - new CurlHandler([ - 'max_idle_handles' => 0, - 'handle_factory' => new CurlFactory(3), - ]); - } - - public function testRejectsUnknownConstructorOption(): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid CurlHandler constructor option "unknown".'); - - new CurlHandler(['unknown' => true]); + yield 'negative' => [-1]; + yield 'float' => [1.0]; + yield 'string' => ['1']; } public function testCloseClosesInternallyCreatedFactory(): void @@ -434,6 +423,27 @@ public function testDisabledTransportSharingCanBeUsedWithCustomFactory(): void self::assertInstanceOf(CurlHandler::class, $handler); } + public function testMaxIdleHandlesCannotBeUsedWithCustomFactory(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + + new CurlHandler([ + 'handle_factory' => new CurlFactory(0), + 'max_idle_handles' => 4, + ]); + } + + public function testNullMaxIdleHandlesCanBeUsedWithCustomFactory(): void + { + $handler = new CurlHandler([ + 'handle_factory' => new CurlFactory(0), + 'max_idle_handles' => null, + ]); + + self::assertInstanceOf(CurlHandler::class, $handler); + } + public function testCloseReleasesShareHandleState(): void { self::skipIfCurlShareIsUnavailable(); @@ -493,15 +503,6 @@ public static function unsupportedTransferEncodingProvider(): iterable yield 'coding after chunked' => ['chunked, gzip', 'Invalid Transfer-Encoding response header: chunked is not the final transfer coding']; } - private static function readIdleHandles(CurlFactory $factory): array - { - $readHandles = \Closure::bind(static function (CurlFactory $factory): array { - return $factory->handles; - }, null, CurlFactory::class); - - return $readHandles($factory); - } - private static function readFactory(CurlHandler $handler): CurlFactory { $readFactory = \Closure::bind(static function (CurlHandler $handler): CurlFactory { @@ -514,6 +515,15 @@ private static function readFactory(CurlHandler $handler): CurlFactory return $factory; } + private static function readIdleHandles(CurlFactory $factory): array + { + $readIdleHandles = \Closure::bind(static function (CurlFactory $factory): array { + return $factory->handles; + }, null, CurlFactory::class); + + return $readIdleHandles($factory); + } + private static function readShareHandleState(CurlHandler $handler): ?CurlShareHandleState { $readShareHandleState = \Closure::bind(static function (CurlHandler $handler): ?CurlShareHandleState { diff --git a/tests/Handler/CurlMultiHandlerTest.php b/tests/Handler/CurlMultiHandlerTest.php index 5b27cddee..1efee49ea 100644 --- a/tests/Handler/CurlMultiHandlerTest.php +++ b/tests/Handler/CurlMultiHandlerTest.php @@ -963,69 +963,6 @@ public function testThrowsWhenCurlMultiOptionNameIsInvalid(): void $a($request, []); } - /** - * @dataProvider maxIdleHandlesProvider - */ - public function testMaxIdleHandlesControlsRetention(array $options, int $expected): void - { - if (isset($options['transport_sharing'])) { - self::skipIfCurlShareIsUnavailable(); - } - - $handler = new CurlMultiHandler($options); - $factory = self::readFactory($handler); - $handles = []; - for ($i = 0; $i <= $expected; ++$i) { - $handles[] = $factory->create(new Request('GET', Server::$url), []); - } - - foreach ($handles as $handle) { - $factory->release($handle); - } - - self::assertCount($expected, self::readIdleHandles($factory)); - } - - public static function maxIdleHandlesProvider(): array - { - return [ - 'default' => [[], 50], - 'null' => [['max_idle_handles' => null], 50], - 'disabled' => [['max_idle_handles' => 0], 0], - 'increased' => [['max_idle_handles' => 51], 51], - 'shared' => [['max_idle_handles' => 51, 'transport_sharing' => TransportSharing::HANDLER_PREFER], 51], - ]; - } - - /** - * @dataProvider invalidMaxIdleHandlesProvider - * - * @param mixed $value - */ - public function testRejectsInvalidMaxIdleHandles($value): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('max_idle_handles must be a non-negative integer.'); - - new CurlMultiHandler(['max_idle_handles' => $value]); - } - - public static function invalidMaxIdleHandlesProvider(): array - { - return [[-1], ['4']]; - } - - public function testMaxIdleHandlesCannotBeUsedWithCustomFactory(): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "max_idle_handles" option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); - - new CurlMultiHandler([ - 'max_idle_handles' => 0, - 'handle_factory' => new CurlFactory(3), - ]); - } - public function testRejectsUnknownConstructorOption(): void { $this->expectException(InvalidArgumentException::class); @@ -1627,6 +1564,58 @@ public static function invalidSelectTimeoutRangeProvider(): iterable yield 'positive sub-millisecond' => [0.0005]; } + /** + * @dataProvider maxIdleHandlesProvider + */ + public function testMaxIdleHandlesControlsRetention(array $options, int $expected): void + { + if (isset($options['transport_sharing'])) { + self::skipIfCurlShareIsUnavailable(); + } + + $handler = new CurlMultiHandler($options); + $factory = self::readFactory($handler); + $easyHandles = []; + for ($i = 0; $i <= $expected; ++$i) { + $easyHandles[] = $factory->create(new Request('GET', Server::$url), []); + } + + foreach ($easyHandles as $easy) { + $factory->release($easy); + } + + self::assertCount($expected, self::readIdleHandles($factory)); + } + + public static function maxIdleHandlesProvider(): iterable + { + yield 'default' => [[], 50]; + yield 'null' => [['max_idle_handles' => null], 50]; + yield 'disabled' => [['max_idle_handles' => 0], 0]; + yield 'increased' => [['max_idle_handles' => 51], 51]; + yield 'shared' => [['max_idle_handles' => 51, 'transport_sharing' => TransportSharing::HANDLER_PREFER], 51]; + } + + /** + * @dataProvider invalidMaxIdleHandlesProvider + * + * @param mixed $value + */ + public function testRejectsInvalidMaxIdleHandles($value): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('max_idle_handles must be a non-negative integer.'); + + new CurlMultiHandler(['max_idle_handles' => $value]); + } + + public static function invalidMaxIdleHandlesProvider(): iterable + { + yield 'negative' => [-1]; + yield 'float' => [1.0]; + yield 'string' => ['1']; + } + public function testTransportSharingOptionAppliesCurlShare(): void { self::skipIfCurlShareIsUnavailable(); @@ -1925,6 +1914,27 @@ public function testDisabledTransportSharingCanBeUsedWithCustomFactory(): void self::assertInstanceOf(CurlMultiHandler::class, $handler); } + public function testMaxIdleHandlesCannotBeUsedWithCustomFactory(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "max_idle_handles" CurlMultiHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + + new CurlMultiHandler([ + 'handle_factory' => new CurlFactory(0), + 'max_idle_handles' => 51, + ]); + } + + public function testNullMaxIdleHandlesCanBeUsedWithCustomFactory(): void + { + $handler = new CurlMultiHandler([ + 'handle_factory' => new CurlFactory(0), + 'max_idle_handles' => null, + ]); + + self::assertInstanceOf(CurlMultiHandler::class, $handler); + } + public function testCloseReleasesShareHandleState(): void { self::skipIfCurlShareIsUnavailable(); @@ -4211,15 +4221,6 @@ private static function hasMultiHandle(CurlMultiHandler $handler): bool return $hasMultiHandle($handler); } - private static function readIdleHandles(CurlFactory $factory): array - { - $readHandles = \Closure::bind(static function (CurlFactory $factory): array { - return $factory->handles; - }, null, CurlFactory::class); - - return $readHandles($factory); - } - private static function readFactory(CurlMultiHandler $handler): CurlFactory { $readFactory = \Closure::bind(static function (CurlMultiHandler $handler): CurlFactory { @@ -4232,6 +4233,15 @@ private static function readFactory(CurlMultiHandler $handler): CurlFactory return $factory; } + private static function readIdleHandles(CurlFactory $factory): array + { + $readIdleHandles = \Closure::bind(static function (CurlFactory $factory): array { + return $factory->handles; + }, null, CurlFactory::class); + + return $readIdleHandles($factory); + } + private static function readShareHandleState(CurlMultiHandler $handler): ?CurlShareHandleState { $readShareHandleState = \Closure::bind(static function (CurlMultiHandler $handler): ?CurlShareHandleState { diff --git a/tests/Handler/DebugResourceTest.php b/tests/Handler/DebugResourceTest.php new file mode 100644 index 000000000..558926813 --- /dev/null +++ b/tests/Handler/DebugResourceTest.php @@ -0,0 +1,16 @@ + ['bar', 'baz'], 'X-Bar' => ['qux']], $headers); } + public function testParsesHeadersFromLines(): void + { + $lines = [ + 'Foo: bar', + 'Foo: baz', + 'Abc: 123', + 'Def: a, b', + ]; + + $expected = [ + 'Foo' => ['bar', 'baz'], + 'Abc' => ['123'], + 'Def' => ['a, b'], + ]; + + self::assertSame($expected, HeaderProcessor::headersFromLines($lines)); + } + + public function testParsesHeadersFromLinesWithMultipleLines(): void + { + $lines = ['Foo: bar', 'Foo: baz', 'Foo: 123']; + $expected = ['Foo' => ['bar', 'baz', '123']]; + + self::assertSame($expected, HeaderProcessor::headersFromLines($lines)); + } + public static function statusLineCandidateProvider(): iterable { yield 'http/1.1' => ['HTTP/1.1 200 OK', true]; @@ -230,6 +256,55 @@ public static function invalidResponseFramingProvider(): iterable ]; } + /** + * @dataProvider headersInExceptionTraceProvider + * + * @param list $arguments + * @param array $sensitiveArguments + */ + public function testKeepsHeadersOutOfExceptionTraces( + string $method, + array $arguments, + array $sensitiveArguments + ): void { + if (\PHP_VERSION_ID < 80200) { + self::markTestSkipped('Sensitive parameters are not redacted before PHP 8.2.'); + } + + $previous = \ini_set('zend.exception_ignore_args', '0'); + + try { + HeaderProcessor::$method(...$arguments); + self::fail('Expected a RuntimeException'); + } catch (\RuntimeException $e) { + $redacted = []; + foreach ($e->getTrace() as $frame) { + if (($frame['class'] ?? null) === HeaderProcessor::class && isset($sensitiveArguments[$frame['function']])) { + self::assertInstanceOf(\SensitiveParameterValue::class, $frame['args'][$sensitiveArguments[$frame['function']]]); + $redacted[] = $frame['function']; + } + } + + self::assertSame(\array_keys($sensitiveArguments), $redacted); + } finally { + \ini_set('zend.exception_ignore_args', $previous); + } + } + + public static function headersInExceptionTraceProvider(): iterable + { + yield 'invalid header line' => [ + 'parseHeaders', + [['HTTP/1.1 200 OK', 'Set-Cookie: sid=secret', 'invalid']], + ['parseHeaders' => 0], + ]; + yield 'invalid framing' => [ + 'validateResponseFraming', + ['GET', 200, ['Set-Cookie' => ['sid=secret'], 'Transfer-Encoding' => ['gzip']]], + ['parseTransferEncoding' => 0, 'validateResponseFraming' => 2], + ]; + } + /** * @dataProvider transferEncodingProvider * @@ -252,6 +327,22 @@ public static function transferEncodingProvider(): iterable yield 'empty list' => [['Transfer-Encoding' => [',']], false]; } + public function testNormalizeHeaderKeys(): void + { + $input = ['HelLo' => 'foo', 'WORld' => 'bar']; + $expected = ['hello' => 'HelLo', 'world' => 'WORld']; + + self::assertSame($expected, HeaderProcessor::normalizeHeaderKeys($input)); + } + + public function testNormalizeHeaderKeysHandlesNumericKeys(): void + { + $input = [0 => 'zero', 'HelLo' => 'foo']; + $expected = [0 => 0, 'hello' => 'HelLo']; + + self::assertSame($expected, HeaderProcessor::normalizeHeaderKeys($input)); + } + public function testReturnsUnrepresentableResponseContentLengthForCallerPolicy(): void { $overflow = ((string) \PHP_INT_MAX).'0'; diff --git a/tests/Handler/ProtocolsTest.php b/tests/Handler/ProtocolsTest.php new file mode 100644 index 000000000..1732a4ee5 --- /dev/null +++ b/tests/Handler/ProtocolsTest.php @@ -0,0 +1,25 @@ +expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('protocols may only contain "http" and "https"'); + + Protocols::normalize(['HTTPS']); + } +} diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index 674fab3ff..376ea06f2 100644 --- a/tests/Handler/StreamHandlerTest.php +++ b/tests/Handler/StreamHandlerTest.php @@ -2462,6 +2462,32 @@ public function testDoesNotSendTheFromIniValue(): void self::assertSame('', Server::received()[0]->getHeaderLine('From')); } + public function testDoesNotSendAFromHeaderWhenTheIniIsNotSet(): void + { + $this->queueRes(); + $handler = new StreamHandler(); + $previous = \ini_get_all(null, false)['from']; + \ini_restore('from'); + + try { + if (\ini_get_all(null, false)['from'] !== null) { + self::markTestSkipped('The from ini setting is configured.'); + } + + $handler(new Request('GET', Server::$url), [])->wait(); + $after = \ini_get_all(null, false)['from']; + } finally { + \ini_restore('from'); + if ($previous !== null) { + \ini_set('from', $previous); + } + } + + self::assertFalse(Server::received()[0]->hasHeader('From')); + // ini_get() reports an unset setting and an empty one alike. + self::assertNull($after); + } + public function testSendsExplicitFromHeaderWhenTheIniIsSet(): void { $this->queueRes(); @@ -2479,6 +2505,141 @@ public function testSendsExplicitFromHeaderWhenTheIniIsSet(): void self::assertSame(['request@example.com'], Server::received()[0]->getHeader('From')); } + public function testDoesNotSendAFromIniValueSetDuringAnotherTransfer(): void + { + Server::flush(); + Server::enqueue([ + new Response(200, ['Content-Length' => '8'], 'hi there'), + new Response(200, ['Content-Length' => '8'], 'hi there'), + ]); + $handler = new StreamHandler(); + $outerFrom = null; + $previous = \ini_set('from', 'ini@example.com'); + + try { + $handler(new Request('GET', Server::$url), [ + 'progress' => static function () use ($handler, &$outerFrom): void { + if ($outerFrom === null) { + $outerFrom = \ini_get('from'); + \ini_set('from', 'other@example.com'); + $handler(new Request('GET', Server::$url), [])->wait(); + } + }, + ])->wait(); + } finally { + if ($previous !== false) { + \ini_set('from', $previous); + } + } + + // The nested transfer started inside the outer open. + self::assertSame('', $outerFrom); + self::assertSame('', Server::received()[1]->getHeaderLine('From')); + } + + public function testDoesNotSendAFromIniValueSetWhileAnotherTransferConnects(): void + { + Server::flush(); + Server::enqueue([ + new Response(200, ['Content-Length' => '8'], 'hi there'), + new Response(200, ['Content-Length' => '8'], 'hi there'), + ]); + $handler = new StreamHandler(); + $wrapper = new class { + /** @var resource */ + public $context; + + public function stream_open(): bool + { + return true; + } + + public function stream_write(string $data): int + { + \stream_context_get_options($this->context)['guzzle-test']['write']($data); + + return \strlen($data); + } + }; + \stream_wrapper_register('guzzle-test', \get_class($wrapper)); + $nested = false; + $debug = \fopen('guzzle-test://debug', 'w', false, \stream_context_create(['guzzle-test' => [ + 'write' => static function (string $data) use ($handler, &$nested): void { + if (!$nested && \strpos($data, '[CONNECT]') !== false) { + $nested = true; + \ini_set('from', 'other@example.com'); + $handler(new Request('GET', Server::$url.'b'), [])->wait(); + } + }, + ]])); + $previous = \ini_set('from', ''); + + try { + $handler(new Request('GET', Server::$url.'a'), ['debug' => $debug])->wait(); + } finally { + if ($previous !== false) { + \ini_set('from', $previous); + } + \fclose($debug); + \stream_wrapper_unregister('guzzle-test'); + } + + // The nested transfer completed before the outer request was built. + $received = Server::received(); + self::assertSame('/b', $received[0]->getUri()->getPath()); + self::assertSame('', $received[0]->getHeaderLine('From')); + self::assertSame('/a', $received[1]->getUri()->getPath()); + self::assertSame('', $received[1]->getHeaderLine('From')); + } + + public function testRestoresTheFromIniAfterOverlappingTransfers(): void + { + if (\PHP_VERSION_ID < 80100) { + self::markTestSkipped('Fibers are unavailable.'); + } + + Server::flush(); + Server::enqueue([ + new Response(200, ['Content-Length' => '8'], 'hi there'), + new Response(200, ['Content-Length' => '8'], 'hi there'), + ]); + $handler = new StreamHandler(); + $transfer = static function () use ($handler): void { + $suspended = false; + $handler(new Request('GET', Server::$url), [ + 'progress' => static function () use (&$suspended): void { + if (!$suspended) { + $suspended = true; + \Fiber::suspend(\ini_get('from')); + } + }, + ])->wait(); + }; + $previous = \ini_set('from', 'ini@example.com'); + + try { + $first = new \Fiber($transfer); + $second = new \Fiber($transfer); + + // Both transfers are parked inside the open with the setting blanked. + self::assertSame('', $first->start()); + self::assertSame('', $second->start()); + + $first->resume(); + $second->resume(); + + self::assertSame('ini@example.com', \ini_get('from')); + } finally { + // Unlike upstream, destroy the fibers first: a fiber still suspended + // after a failed assertion restores the setting when destroyed + unset($first, $second); + + if ($previous !== false) { + \ini_set('from', $previous); + } + } + } + protected function getSendResult(array $opts): ResponseInterface { $this->queueRes(); @@ -3623,6 +3784,46 @@ public function testPreservesTransferExceptionThrownByProgressCallback(): void } } + public function testDoesNotCaptureUnrelatedErrorsWhileSuspendedInProgressCallback(): void + { + if (\PHP_VERSION_ID < 80100) { + self::markTestSkipped('Fibers are unavailable.'); + } + + $this->queueRes(); + $handler = new StreamHandler(); + $fiber = new \Fiber(static function () use ($handler): void { + $suspended = false; + $handler(new Request('GET', Server::$url), [ + 'progress' => static function () use (&$suspended): void { + if (!$suspended) { + $suspended = true; + \Fiber::suspend(); + } + }, + ])->wait(); + }); + $errors = []; + \set_error_handler(static function (int $level, string $message) use (&$errors): bool { + $errors[] = $message; + + return true; + }); + + try { + $fiber->start(); + self::assertTrue($fiber->isSuspended()); + + \trigger_error('Unrelated warning', \E_USER_WARNING); + + $fiber->resume(); + } finally { + \restore_error_handler(); + } + + self::assertSame(['Unrelated warning'], $errors); + } + public function testProgressOverflowValueThrows(): void { $this->expectException(\OverflowException::class); diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 76c7af23c..0ca13ba9a 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -4,16 +4,20 @@ namespace GuzzleHttp\Tests; +use GuzzleHttp\Client; use GuzzleHttp\Exception\InvalidArgumentException; use GuzzleHttp\Handler\ContextualCurlMultiHandler; use GuzzleHttp\Handler\CurlFactory; use GuzzleHttp\Handler\CurlHandler; use GuzzleHttp\Handler\CurlMultiHandler; use GuzzleHttp\Handler\CurlVersion; +use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Handler\StreamHandler; use GuzzleHttp\Handler\StreamTlsSessionCache; +use GuzzleHttp\HandlerStack; use GuzzleHttp\Multiplexing; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Response; use GuzzleHttp\TransportSharing; use GuzzleHttp\Utils; use PHPUnit\Framework\TestCase; @@ -25,147 +29,11 @@ public static function noBodyProvider(): array return [['get'], ['head'], ['delete']]; } - public function testParsesHeadersFromLines(): void - { - $lines = [ - 'Foo: bar', - 'Foo: baz', - 'Abc: 123', - 'Def: a, b', - ]; - - $expected = [ - 'Foo' => ['bar', 'baz'], - 'Abc' => ['123'], - 'Def' => ['a, b'], - ]; - - self::assertSame($expected, Utils::headersFromLines($lines)); - } - - public function testParsesHeadersFromLinesWithMultipleLines(): void - { - $lines = ['Foo: bar', 'Foo: baz', 'Foo: 123']; - $expected = ['Foo' => ['bar', 'baz', '123']]; - - self::assertSame($expected, Utils::headersFromLines($lines)); - } - public function testChooseHandler(): void { self::assertIsCallable(Utils::chooseHandler()); } - public function testChooseHandlerForwardsMaxIdleHandlesToBothCurlHandlers(): void - { - self::skipIfDefaultCurlMultiHandlerIsUnavailable(); - - $handler = Utils::chooseHandler(['max_idle_handles' => 0]); - $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); - if (isset($handlers['streaming'])) { - $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); - } - - self::assertInstanceOf(CurlHandler::class, $handlers['sync']); - $handlers['default'] = self::createPooledHandler($handlers['default']); - foreach ($handlers as $curlHandler) { - $factory = \Closure::bind(static function ($handler): CurlFactory { - return $handler->factory; - }, null, \get_class($curlHandler))($curlHandler); - $easy = $factory->create(new Request('GET', 'http://example.com'), []); - $factory->release($easy); - - $idleHandles = \Closure::bind(static function (CurlFactory $factory): array { - return $factory->handles; - }, null, CurlFactory::class)($factory); - self::assertSame([], $idleHandles); - } - } - - public function testChooseHandlerKeepsDefaultIdleHandleLimits(): void - { - self::skipIfDefaultCurlMultiHandlerIsUnavailable(); - - $handler = Utils::chooseHandler(); - $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); - if (isset($handlers['streaming'])) { - $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); - } - - $maxHandles = static function ($curlHandler): int { - $factory = \Closure::bind(static function ($handler): CurlFactory { - return $handler->factory; - }, null, \get_class($curlHandler))($curlHandler); - - return \Closure::bind(static function (CurlFactory $factory): int { - return $factory->maxHandles; - }, null, CurlFactory::class)($factory); - }; - - self::assertInstanceOf(CurlHandler::class, $handlers['sync']); - $handlers['default'] = self::createPooledHandler($handlers['default']); - self::assertSame(256, $maxHandles($handlers['sync'])); - self::assertSame(50, $maxHandles($handlers['default'])); - } - - /** - * @dataProvider idleHandlerLimitProvider - * - * @param array $options - */ - public function testChooseHandlerConfiguresIdleHandlerLimit(array $options, int $expected): void - { - self::skipIfDefaultCurlMultiHandlerIsUnavailable(); - - $handler = Utils::chooseHandler($options); - $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); - if (isset($handlers['streaming'])) { - $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); - } - - $limit = \Closure::bind(static function (ContextualCurlMultiHandler $handler): int { - return $handler->maxIdleHandlers; - }, null, ContextualCurlMultiHandler::class)($handlers['default']); - - self::assertSame($expected, $limit); - } - - public static function idleHandlerLimitProvider(): iterable - { - yield 'default' => [[], 64]; - yield 'disabled' => [['max_idle_multi_handlers' => 0], 0]; - yield 'configured' => [['max_idle_multi_handlers' => 3], 3]; - } - - public function testChooseHandlerRejectsInvalidMaxIdleHandlesWithoutCurl(): void - { - $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); - - try { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('max_idle_handles must be a non-negative integer.'); - - Utils::chooseHandler(['max_idle_handles' => -1]); - } finally { - self::setCurlVersionInfo($previousVersionInfo); - } - } - - public function testChooseHandlerAllowsStreamFallbackWithMaxIdleHandles(): void - { - if (!(bool) \ini_get('allow_url_fopen')) { - self::markTestSkipped('This test requires allow_url_fopen.'); - } - - $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); - - try { - self::assertInstanceOf(StreamHandler::class, Utils::chooseHandler(['max_idle_handles' => 4])); - } finally { - self::setCurlVersionInfo($previousVersionInfo); - } - } - public function testChooseHandlerAcceptsPreferredTransportSharing(): void { self::skipIfDefaultCurlHandlerIsUnavailable(); @@ -425,6 +293,101 @@ public function testChooseHandlerForwardsMultiplexNoneToTheCurlMultiHandler(): v } } + public function testChooseHandlerForwardsMaxIdleHandlesToBothCurlHandlers(): void + { + self::skipIfDefaultCurlMultiHandlerIsUnavailable(); + + $handler = Utils::chooseHandler(['max_idle_handles' => 0]); + $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); + if (isset($handlers['streaming'])) { + $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); + } + + self::assertInstanceOf(CurlHandler::class, $handlers['sync']); + self::assertInstanceOf(ContextualCurlMultiHandler::class, $handlers['default']); + foreach ([$handlers['sync'], self::createPooledHandler($handlers['default'])] as $curlHandler) { + $factory = \Closure::bind(static function ($curlHandler): CurlFactory { + return $curlHandler->factory; + }, null, \get_class($curlHandler))($curlHandler); + $factory->release($factory->create(new Request('GET', 'http://example.com'), [])); + + $idleHandles = \Closure::bind(static function (CurlFactory $factory): array { + return $factory->handles; + }, null, CurlFactory::class)($factory); + self::assertSame([], $idleHandles); + } + } + + public function testChooseHandlerFallsBackToTheStreamHandlerWithMaxIdleHandles(): void + { + if (!\ini_get('allow_url_fopen')) { + self::markTestSkipped('The allow_url_fopen ini setting is required.'); + } + + $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); + + try { + self::assertInstanceOf(StreamHandler::class, Utils::chooseHandler(['max_idle_handles' => 4])); + } finally { + self::setCurlVersionInfo($previousVersionInfo); + } + } + + public function testChooseHandlerKeepsDefaultIdleHandleLimits(): void + { + self::skipIfDefaultCurlMultiHandlerIsUnavailable(); + + $handler = Utils::chooseHandler(); + $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); + if (isset($handlers['streaming'])) { + $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); + } + + $maxHandles = static function ($curlHandler): int { + $factory = \Closure::bind(static function ($handler): CurlFactory { + return $handler->factory; + }, null, \get_class($curlHandler))($curlHandler); + + return \Closure::bind(static function (CurlFactory $factory): int { + return $factory->maxHandles; + }, null, CurlFactory::class)($factory); + }; + + self::assertInstanceOf(CurlHandler::class, $handlers['sync']); + $handlers['default'] = self::createPooledHandler($handlers['default']); + self::assertSame(256, $maxHandles($handlers['sync'])); + self::assertSame(50, $maxHandles($handlers['default'])); + } + + /** + * @dataProvider idleHandlerLimitProvider + * + * @param array $options + */ + public function testChooseHandlerConfiguresIdleHandlerLimit(array $options, int $expected): void + { + self::skipIfDefaultCurlMultiHandlerIsUnavailable(); + + $handler = Utils::chooseHandler($options); + $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); + if (isset($handlers['streaming'])) { + $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); + } + + $limit = \Closure::bind(static function (ContextualCurlMultiHandler $handler): int { + return $handler->maxIdleHandlers; + }, null, ContextualCurlMultiHandler::class)($handlers['default']); + + self::assertSame($expected, $limit); + } + + public static function idleHandlerLimitProvider(): iterable + { + yield 'default' => [[], 64]; + yield 'disabled' => [['max_idle_multi_handlers' => 0], 0]; + yield 'configured' => [['max_idle_multi_handlers' => 3], 3]; + } + public function testChooseHandlerAcceptsDisabledTransportSharing(): void { $_SERVER['curl_test'] = true; @@ -439,43 +402,225 @@ public function testChooseHandlerAcceptsDisabledTransportSharing(): void } } - public function testDefaultUserAgent(): void + public function testChooseHandlerUsesTheDefaultHandlerFactory(): void { - self::assertIsString(Utils::defaultUserAgent()); + $handler = new MockHandler(); + $received = []; + Utils::setDefaultHandlerFactory(static function (array $handlerOptions) use ($handler, &$received): callable { + $received[] = $handlerOptions; + + return $handler; + }); + + try { + $handlerOptions = ['max_idle_handles' => 4, 'multiplex' => Multiplexing::NONE]; + + self::assertSame($handler, Utils::chooseHandler()); + self::assertSame($handler, Utils::chooseHandler($handlerOptions)); + self::assertSame([[], $handlerOptions], $received); + + Utils::setDefaultHandlerFactory(null); + + self::assertNotSame($handler, Utils::chooseHandler()); + self::assertCount(2, $received); + } finally { + Utils::setDefaultHandlerFactory(null); + } + } + + /** + * @dataProvider invalidHandlerOptionProvider + */ + public function testChooseHandlerValidatesHandlerOptionsBeforeCallingTheDefaultHandlerFactory(array $handlerOptions, string $message): void + { + Utils::setDefaultHandlerFactory(static function (): callable { + self::fail('The default handler factory should not be called.'); + }); + + try { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + Utils::chooseHandler($handlerOptions); + } finally { + Utils::setDefaultHandlerFactory(null); + } } - public function testReturnsDebugResource(): void + public static function invalidHandlerOptionProvider(): iterable { - self::assertIsResource(Utils::debugResource()); + yield 'transport sharing' => [['transport_sharing' => 'invalid'], 'The "transport_sharing" option must be null or a GuzzleHttp\TransportSharing::* constant; received string.']; + yield 'max host connections' => [['max_host_connections' => 0], 'max_host_connections must be a positive integer.']; + yield 'max idle handles' => [['max_idle_handles' => -1], 'max_idle_handles must be a non-negative integer.']; + yield 'max idle multi handlers' => [['max_idle_multi_handlers' => -1], 'max_idle_multi_handlers must be a non-negative integer.']; + yield 'max idle multi handlers with connection caps' => [['max_idle_multi_handlers' => 1, 'max_total_connections' => 2], 'The "max_idle_multi_handlers" option cannot be combined with connection caps, which require one shared cURL multi handler.']; + yield 'max total connections' => [['max_total_connections' => '1'], 'max_total_connections must be a positive integer.']; } - public function testNormalizeHeaderKeys(): void + public function testChooseHandlerDefersEnvironmentChecksToTheBuiltInHandlerCallable(): void { - $input = ['HelLo' => 'foo', 'WORld' => 'bar']; - $expected = ['hello' => 'HelLo', 'world' => 'WORld']; + $previousVersionInfo = self::setCurlVersionInfo([ + 'version' => '8.21.0', + 'features' => self::curlSslFeature(), + ]); - self::assertSame($expected, Utils::normalizeHeaderKeys($input)); + $handler = new MockHandler(); + $builtIn = null; + Utils::setDefaultHandlerFactory(static function (array $handlerOptions, callable $default) use ($handler, &$builtIn): callable { + $builtIn = $default; + + return $handler; + }); + + try { + self::assertSame($handler, Utils::chooseHandler([ + 'transport_sharing' => TransportSharing::PERSISTENT_REQUIRE, + 'max_host_connections' => 1, + ])); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('persistent transport sharing'); + + $builtIn(); + } finally { + Utils::setDefaultHandlerFactory(null); + self::setCurlVersionInfo($previousVersionInfo); + } + } + + public function testChooseHandlerPassesABuiltInHandlerCallableToTheDefaultHandlerFactory(): void + { + if (!\ini_get('allow_url_fopen')) { + self::markTestSkipped('The allow_url_fopen ini setting is required.'); + } + + $previousVersionInfo = self::setCurlVersionInfo(['version' => '7.29.0', 'features' => 0]); + + $handlers = []; + Utils::setDefaultHandlerFactory(static function (array $handlerOptions, callable $default) use (&$handlers): callable { + $handlers = [$default(), $default()]; + + return $handlers[0]; + }); + + try { + $handler = Utils::chooseHandler(['max_host_connections' => 1]); + + self::assertInstanceOf(StreamHandler::class, $handlers[0]); + self::assertInstanceOf(StreamHandler::class, $handlers[1]); + self::assertNotSame($handlers[0], $handlers[1]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Enabling the "stream" request option on a stream handler configured with the "max_host_connections" or "max_total_connections" option is not supported because streamed connections cannot be capped.'); + + $handler(new Request('GET', 'http://localhost/'), ['stream' => true]); + } finally { + Utils::setDefaultHandlerFactory(null); + self::setCurlVersionInfo($previousVersionInfo); + } + } + + public function testBuiltInHandlerCallableKeepsTheCoroutineHandlerIdleLimits(): void + { + self::skipIfDefaultCurlMultiHandlerIsUnavailable(); + + Utils::setDefaultHandlerFactory(static function (array $handlerOptions, callable $default): callable { + return $default(); + }); + + try { + $handler = Utils::chooseHandler(['max_idle_handles' => 0, 'max_idle_multi_handlers' => 3]); + } finally { + Utils::setDefaultHandlerFactory(null); + } + + $handlers = (new \ReflectionFunction($handler))->getStaticVariables(); + if (isset($handlers['streaming'])) { + $handlers = (new \ReflectionFunction($handlers['default']))->getStaticVariables(); + } + + $maxIdleHandlers = \Closure::bind(static function (ContextualCurlMultiHandler $handler): int { + return $handler->maxIdleHandlers; + }, null, ContextualCurlMultiHandler::class)($handlers['default']); + $factory = \Closure::bind(static function (CurlMultiHandler $handler): CurlFactory { + return $handler->factory; + }, null, CurlMultiHandler::class)(self::createPooledHandler($handlers['default'])); + $maxIdleHandles = \Closure::bind(static function (CurlFactory $factory): int { + return $factory->maxHandles; + }, null, CurlFactory::class)($factory); + + self::assertSame(3, $maxIdleHandlers); + self::assertSame(0, $maxIdleHandles); } - public function testNormalizeHeaderKeysHandlesNumericKeys(): void + public function testChooseHandlerRejectsANonCallableFromTheDefaultHandlerFactory(): void { - $input = [0 => 'zero', 'HelLo' => 'foo']; - $expected = [0 => 0, 'hello' => 'HelLo']; + Utils::setDefaultHandlerFactory(static function () { + return 'not callable'; + }); - self::assertSame($expected, Utils::normalizeHeaderKeys($input)); + try { + $this->expectException(\TypeError::class); + + Utils::chooseHandler(); + } finally { + Utils::setDefaultHandlerFactory(null); + } } - public function testNormalizeProtocolsAcceptsLowercaseProtocols(): void + public function testExplicitHandlersBypassTheDefaultHandlerFactory(): void { - self::assertSame(['http', 'https'], Utils::normalizeProtocols(['http', 'https', 'http'])); + $calls = 0; + Utils::setDefaultHandlerFactory(static function () use (&$calls): callable { + ++$calls; + + return new MockHandler(); + }); + + try { + $handler = new MockHandler(); + HandlerStack::create($handler); + new Client(['handler' => $handler]); + + self::assertSame(0, $calls); + } finally { + Utils::setDefaultHandlerFactory(null); + } } - public function testNormalizeProtocolsRejectsUppercaseProtocols(): void + public function testClientsKeepTheHandlerCreatedByTheDefaultHandlerFactory(): void { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('protocols may only contain "http" and "https"'); + $received = []; + Utils::setDefaultHandlerFactory(static function (array $handlerOptions) use (&$received): callable { + $received[] = $handlerOptions; + + return new MockHandler([new Response(201)]); + }); + + try { + $first = new Client(); + + Utils::setDefaultHandlerFactory(static function (array $handlerOptions) use (&$received): callable { + $received[] = $handlerOptions; + + return new MockHandler([new Response(202)]); + }); - Utils::normalizeProtocols(['HTTPS']); + $second = new Client(['max_idle_handles' => 4]); + + Utils::setDefaultHandlerFactory(null); + + self::assertSame([[], ['max_idle_handles' => 4]], $received); + self::assertSame(201, $first->get('http://example.com')->getStatusCode()); + self::assertSame(202, $second->get('http://example.com')->getStatusCode()); + } finally { + Utils::setDefaultHandlerFactory(null); + } + } + + public function testDefaultUserAgent(): void + { + self::assertIsString(Utils::defaultUserAgent()); } private static function skipIfDefaultCurlHandlerIsUnavailable(): void