From 80c1fb545a6c5d880a082da4f8781907d5666b39 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Sun, 18 Oct 2026 17:10:53 +0100 Subject: [PATCH 01/23] Bump version to 8.4 (#3982) --- .github/workflows/ci.yml | 2 +- .github/workflows/static.yml | 2 +- README.md | 2 +- docs/overview.md | 4 ++-- src/RequestOptions.php | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40c88e971..875b9f4fe 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.4.x-dev jobs: build-lowest-version: diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 9b0363921..98889eaf9 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.4.x-dev jobs: phpstan: diff --git a/README.md b/README.md index 64c403586..e9635dd5c 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ composer require guzzlehttp/guzzle | Version | Status | PHP Version | |---------|--------------|--------------| -| 8.3 | Latest | >=7.4,<8.7 | +| 8.4 | Latest | >=7.4,<8.7 | | 7.16 | Maintenance | >=7.2.5,<8.7 | | 6.5 | End of Life | >=5.5,<8.0 | diff --git a/docs/overview.md b/docs/overview.md index cc50b4f07..2e08a07a5 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 guzzlehttp/guzzle:^8.3 +composer require guzzlehttp/guzzle:^8.4 ``` Alternatively, you can specify Guzzle as a dependency in your project's existing @@ -39,7 +39,7 @@ composer.json file: ```js { "require": { - "guzzlehttp/guzzle": "^8.3" + "guzzlehttp/guzzle": "^8.4" } } ``` diff --git a/src/RequestOptions.php b/src/RequestOptions.php index 7fe973dbd..38482b96f 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.4/docs/request-options.md */ final class RequestOptions { From 39d17ec0d7db5c7f2a98054edabde76df48ea254 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Sun, 25 Oct 2026 11:53:10 +0000 Subject: [PATCH 02/23] Sort the Cookie header by path length and replace cookies in place (#3992) --- CHANGELOG.md | 8 ++++ docs/cookies.md | 4 +- src/Cookie/CookieJar.php | 34 ++++++++++++++--- tests/Cookie/CookieJarTest.php | 69 ++++++++++++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 019430383..12fb1e50a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. +## 8.4.0 - Upcoming + +### Changed + +- 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 + + ## 8.3.1 - Upcoming ### Fixed 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/src/Cookie/CookieJar.php b/src/Cookie/CookieJar.php index e3ed1d1e3..f1aeedc91 100644 --- a/src/Cookie/CookieJar.php +++ b/src/Cookie/CookieJar.php @@ -196,6 +196,7 @@ public function setCookie( } // Resolve conflicts with previously set cookies + $replaced = false; foreach ($this->cookies as $i => $c) { // Two cookies are identical, when their path, and domain are // identical. @@ -207,14 +208,28 @@ 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) { + 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; } @@ -222,7 +237,9 @@ public function setCookie( return false; } - $this->cookies[] = $cookie; + if (!$replaced) { + $this->cookies[] = $cookie; + } return true; } @@ -369,6 +386,7 @@ public function withCookieHeader( RequestInterface $request ): RequestInterface { $values = []; + $count = 0; $headerLength = 8; $uri = $request->getUri(); $scheme = $uri->getScheme(); @@ -390,16 +408,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/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index 2667b8add..eb2c7651e 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -619,6 +619,42 @@ 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 testDistinctNumericStringCookieNamesCoexist(): void { $this->jar->setCookie(new SetCookie([ @@ -758,6 +794,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 +1112,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( From ba8613b3d1e9717eb2d87cec44ba40527295e06c Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Sun, 25 Oct 2026 15:43:54 +0000 Subject: [PATCH 03/23] Add configurable idle cURL handle retention (#3993) Co-authored-by: Raj Siva-Rajah --- CHANGELOG.md | 4 ++ docs/contributing/curl-connection-reuse.md | 12 ++-- docs/handlers.md | 37 ++++++++++ phpstan-baseline.neon | 4 +- src/Client.php | 17 +++-- src/Handler/CurlHandler.php | 18 ++++- src/Handler/CurlMultiHandler.php | 16 ++++- src/Utils.php | 12 +++- tests/ClientTest.php | 47 +++++++++++++ tests/Handler/CurlHandlerTest.php | 82 ++++++++++++++++++++++ tests/Handler/CurlMultiHandlerTest.php | 82 ++++++++++++++++++++++ tests/UtilsTest.php | 43 ++++++++++++ 12 files changed, 355 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12fb1e50a..105eca8e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version ## 8.4.0 - Upcoming +### Added + +- Add `max_idle_handles` client and cURL handler option to limit idle handles + ### Changed - Send longer-path cookies first in the `Cookie` header, like browsers and libcurl diff --git a/docs/contributing/curl-connection-reuse.md b/docs/contributing/curl-connection-reuse.md index 9424ccb54..8126b9188 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 3 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/handlers.md b/docs/handlers.md index c5e1ab36a..500d27919 100644 --- a/docs/handlers.md +++ b/docs/handlers.md @@ -99,6 +99,43 @@ custom handlers are responsible for honoring these options themselves. > stripping that protects against credential leaks on redirects. See the > per-option notes under [Request Options](request-options.md) for specifics. +### Idle cURL Handles + +`max_idle_handles` (int|null): Maximum number of idle cURL easy handles retained +by each default cURL handler. Zero disables retention; null or omission keeps +the defaults of 3 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: + +```php +use GuzzleHttp\Client; + +$client = new Client([ + 'max_idle_handles' => 64, +]); +``` + +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. + +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 cURL handler or the factory instead. + ### Closing cURL Handlers The cURL handlers own native cURL resources. These resources are normally diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 83a51a2b3..4d14f5d2d 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -79,7 +79,7 @@ parameters: path: src/Handler/CurlFactory.php - - message: '#^Offset ''handle_factory''\|''transport_sharing'' on array\{handle_factory\: true, transport_sharing\: true\} in isset\(\) always exists and is not nullable\.$#' + message: '#^Offset ''handle_factory''\|''max_idle_handles''\|''transport_sharing'' on array\{handle_factory\: true, max_idle_handles\: true, transport_sharing\: true\} in isset\(\) always exists and is not nullable\.$#' identifier: isset.offset count: 1 path: src/Handler/CurlHandler.php @@ -325,7 +325,7 @@ parameters: path: src/Pool.php - - message: '#^Parameter \#1 \$options of class GuzzleHttp\\Handler\\CurlHandler constructor expects array\{handle_factory\?\: GuzzleHttp\\Handler\\CurlFactoryInterface\|null, transport_sharing\?\: mixed\}, array\ given\.$#' + message: '#^Parameter \#1 \$options of class GuzzleHttp\\Handler\\CurlHandler constructor expects array\{handle_factory\?\: GuzzleHttp\\Handler\\CurlFactoryInterface\|null, max_idle_handles\?\: mixed, transport_sharing\?\: mixed\}, array\ given\.$#' identifier: argument.type count: 2 path: src/Utils.php diff --git a/src/Client.php b/src/Client.php index 650d64bbe..eccd54715 100644 --- a/src/Client.php +++ b/src/Client.php @@ -68,6 +68,10 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface * fallback receives the cap as a marker only: it rejects enabled * 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. Zero disables retention; null or + * omission keeps the defaults of 3 for CurlHandler and 50 for + * CurlMultiHandler. This setting does not affect the stream 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 @@ -84,6 +88,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface * base_uri?: string|UriInterface, * transport_sharing?: string|null, * max_host_connections?: int|null, + * max_idle_handles?: int|null, * max_total_connections?: int|null, * allow_redirects?: bool|array{ * max?: int, @@ -165,13 +170,13 @@ 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_total_connections'] as $handlerOption) { + if (\array_key_exists($handlerOption, $config)) { + if ($config[$handlerOption] !== null) { + $handlerOptions[$handlerOption] = $config[$handlerOption]; } - unset($config[$capOption]); + unset($config[$handlerOption]); } } @@ -197,6 +202,8 @@ public function __construct( : HandlerStack::create(Utils::chooseHandler($handlerOptions)); } elseif (!\is_callable($config['handler'])) { throw new InvalidArgumentException('handler must be a callable'); + } 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 ($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.'); } elseif ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) { diff --git a/src/Handler/CurlHandler.php b/src/Handler/CurlHandler.php index 57f84fab5..ed4fa7198 100644 --- a/src/Handler/CurlHandler.php +++ b/src/Handler/CurlHandler.php @@ -25,6 +25,7 @@ final class CurlHandler private const KNOWN_CONSTRUCTOR_OPTIONS = [ 'handle_factory' => true, + 'max_idle_handles' => true, 'transport_sharing' => true, ]; @@ -40,9 +41,11 @@ final class CurlHandler * Accepts an associative array of options: * * - handle_factory: Optional curl factory used to create cURL handles. + * - max_idle_handles: Optional maximum number of idle cURL easy handles. + * Zero disables retention; null or omission keeps the default of 3. * - transport_sharing: Optional transport sharing mode. * - * @param array{handle_factory?: ?CurlFactoryInterface, transport_sharing?: mixed} $options Array of options to use with the handler + * @param array{handle_factory?: ?CurlFactoryInterface, max_idle_handles?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler */ public function __construct(array $options = []) { @@ -56,7 +59,16 @@ public function __construct(array $options = []) $transportSharing = $options['transport_sharing'] ?? null; $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing'); + $maxIdleHandles = $options['max_idle_handles'] ?? 3; + if (!\is_int($maxIdleHandles) || $maxIdleHandles < 0) { + throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); + } + if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) { + if (isset($options['max_idle_handles'])) { + throw new InvalidArgumentException('The "max_idle_handles" CurlHandler option cannot be combined with a custom "handle_factory". Configure idle handle retention on the factory instead.'); + } + $this->shareHandleState = null; $this->factory = $options['handle_factory']; $this->ownsFactory = false; @@ -69,8 +81,8 @@ public function __construct(array $options = []) : null; $this->factory = $this->shareHandleState !== null - ? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState) - : new CurlFactory(3); + ? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState) + : new CurlFactory($maxIdleHandles); $this->ownsFactory = true; } diff --git a/src/Handler/CurlMultiHandler.php b/src/Handler/CurlMultiHandler.php index 79612ff1e..1e239b2ed 100644 --- a/src/Handler/CurlMultiHandler.php +++ b/src/Handler/CurlMultiHandler.php @@ -33,6 +33,7 @@ final class CurlMultiHandler private const KNOWN_CONSTRUCTOR_OPTIONS = [ 'handle_factory' => true, 'max_host_connections' => true, + 'max_idle_handles' => true, 'max_total_connections' => true, 'multiplex' => true, 'options' => true, @@ -162,6 +163,8 @@ final class CurlMultiHandler * - 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 @@ -237,7 +240,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; @@ -247,8 +259,8 @@ public function __construct(array $options = []) : null; $this->factory = $this->shareHandleState !== null - ? new CurlFactory(50, $this->shareHandleState->mode, $this->shareHandleState) - : new CurlFactory(50); + ? new CurlFactory($maxIdleHandles, $this->shareHandleState->mode, $this->shareHandleState) + : new CurlFactory($maxIdleHandles); $this->ownsFactory = true; } diff --git a/src/Utils.php b/src/Utils.php index fd5765dda..96ab99cbc 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -64,7 +64,7 @@ public static function debugResource($value = null) * * The returned handler is not wrapped by any default middlewares. * - * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options. + * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options. * * @return callable(RequestInterface, array): PromiseInterface Returns the best handler for the given system. * @@ -76,6 +76,11 @@ public static function chooseHandler(array $handlerOptions = []): callable $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.'); + } + $sharedPoolCapsSupported = CurlVersion::supportsSharedPoolConnectionCaps(); if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_REQUIRE) { @@ -136,7 +141,7 @@ private static function hasConnectionCapOptions(array $handlerOptions): bool } /** - * @param array{max_host_connections?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions + * @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions * * @return (callable(RequestInterface, array): PromiseInterface)|null */ @@ -159,6 +164,9 @@ private static function createCurlHandler(string $sharingMode, array $handlerOpt } $curlHandlerOptions = self::createCurlHandlerOptions($sharingMode); + if (isset($handlerOptions['max_idle_handles'])) { + $curlHandlerOptions['max_idle_handles'] = $handlerOptions['max_idle_handles']; + } $curlMultiHandlerOptions = $curlHandlerOptions + $connectionCapOptions; if (($handlerOptions['multiplex'] ?? null) === Multiplexing::NONE) { // Forwarded to the CurlMultiHandler only: CurlHandler and diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 519dde257..07a65480e 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -443,6 +443,17 @@ public function testConnectionCapClientOptionsCannotBeUsedWithCustomHandler(stri ]); } + public function testMaxIdleHandlesClientOptionCannotBeUsedWithCustomHandler(): void + { + $this->expectException(InvalidArgumentException::class); + $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([ + 'handler' => new MockHandler(), + 'max_idle_handles' => 4, + ]); + } + public function testNullConnectionCapClientOptionsCanBeUsedWithCustomHandler(): void { $client = new Client([ @@ -455,6 +466,16 @@ public function testNullConnectionCapClientOptionsCanBeUsedWithCustomHandler(): self::assertNull($client->getConfig('max_total_connections')); } + public function testNullMaxIdleHandlesClientOptionCanBeUsedWithCustomHandler(): void + { + $client = new Client([ + 'handler' => new MockHandler(), + 'max_idle_handles' => null, + ]); + + self::assertArrayNotHasKey('max_idle_handles', $client->getConfig()); + } + /** * @dataProvider invalidConnectionCapClientOptionProvider * @@ -474,6 +495,25 @@ 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); + } + } + public function testConnectionCapsComposeWithTransportSharing(): void { self::skipIfDefaultCurlHandlerIsUnavailable(); @@ -651,6 +691,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/Handler/CurlHandlerTest.php b/tests/Handler/CurlHandlerTest.php index f9621682f..c3e81902f 100644 --- a/tests/Handler/CurlHandlerTest.php +++ b/tests/Handler/CurlHandlerTest.php @@ -173,6 +173,38 @@ public function testReusesHandles(): void self::assertInstanceOf(FulfilledPromise::class, $a($request, [])); } + /** + * @dataProvider maxIdleHandlesProvider + */ + public function testMaxIdleHandlesControlsRetention(array $options, int $expected): void + { + if (isset($options['transport_sharing'])) { + self::skipIfCurlShareIsUnavailable(); + } + + $handler = new CurlHandler($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' => [[], 3]; + yield 'null' => [['max_idle_handles' => null], 3]; + yield 'disabled' => [['max_idle_handles' => 0], 0]; + yield 'increased' => [['max_idle_handles' => 4], 4]; + yield 'shared' => [['max_idle_handles' => 4, 'transport_sharing' => TransportSharing::HANDLER_PREFER], 4]; + } + public function testClosePreventsReuse(): void { $handler = new CurlHandler(); @@ -192,6 +224,26 @@ public function testRejectsUnknownConstructorOption(): void new CurlHandler(['unknown' => true]); } + /** + * @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 CurlHandler(['max_idle_handles' => $value]); + } + + public static function invalidMaxIdleHandlesProvider(): iterable + { + yield 'negative' => [-1]; + yield 'float' => [1.0]; + yield 'string' => ['1']; + } + public function testCloseClosesInternallyCreatedFactory(): void { $handler = new CurlHandler(); @@ -371,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(); @@ -442,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 ef77baf6d..72557e6ae 100644 --- a/tests/Handler/CurlMultiHandlerTest.php +++ b/tests/Handler/CurlMultiHandlerTest.php @@ -1561,6 +1561,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(); @@ -1859,6 +1911,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(); @@ -4155,6 +4228,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/UtilsTest.php b/tests/UtilsTest.php index 14378e796..665505321 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -5,6 +5,9 @@ namespace GuzzleHttp\Tests; use GuzzleHttp\Exception\InvalidArgumentException; +use GuzzleHttp\Handler\CurlFactory; +use GuzzleHttp\Handler\CurlHandler; +use GuzzleHttp\Handler\CurlMultiHandler; use GuzzleHttp\Handler\CurlVersion; use GuzzleHttp\Handler\StreamHandler; use GuzzleHttp\Handler\StreamTlsSessionCache; @@ -311,6 +314,46 @@ 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(CurlMultiHandler::class, $handlers['default']); + foreach ([$handlers['sync'], $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 testChooseHandlerAcceptsDisabledTransportSharing(): void { $_SERVER['curl_test'] = true; From 7849540cbe148e99019a179a5c0129ca0ce48fe5 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 16:31:57 +0000 Subject: [PATCH 04/23] Restore the from ini setting after overlapping stream handler transfers (#3995) * Restore the from ini setting after overlapping stream handler transfers * Blank the from ini setting before every transfer again * Cover a from ini value set during another transfer --- CHANGELOG.md | 7 +++ src/Handler/StreamHandler.php | 24 +++++++-- tests/Handler/StreamHandlerTest.php | 76 +++++++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f411b2793..89e3aa9bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. +## 8.3.2 - Upcoming + +### Fixed + +- Fix overlapping stream handler transfers leaving the `from` ini setting blank + + ## 8.3.1 - 2026-10-25 ### Fixed diff --git a/src/Handler/StreamHandler.php b/src/Handler/StreamHandler.php index 3bcc80bce..70ec27da4 100644 --- a/src/Handler/StreamHandler.php +++ b/src/Handler/StreamHandler.php @@ -105,6 +105,16 @@ final class StreamHandler */ private const DEFAULT_IDLE_TIMEOUT_MS = 60000; + /** + * Number of transfers currently holding the from ini setting blank. + */ + private static int $fromBlankDepth = 0; + + /** + * @var string|false + */ + private static $fromToRestore = false; + private ?\Throwable $onStatsException = null; private string $transportSharingMode; @@ -1025,12 +1035,20 @@ 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; + // 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_set('from', ''); + 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); } } diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index 674fab3ff..3a123819e 100644 --- a/tests/Handler/StreamHandlerTest.php +++ b/tests/Handler/StreamHandlerTest.php @@ -2479,6 +2479,82 @@ 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 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 { + if ($previous !== false) { + \ini_set('from', $previous); + } + } + } + protected function getSendResult(array $opts): ResponseInterface { $this->queueRes(); From e65824bd7cd7f79abbb80c89b85f0a2b11490f1b Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 16:35:38 +0000 Subject: [PATCH 05/23] Release 8.3.2 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89e3aa9bc..eae98a5a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. -## 8.3.2 - Upcoming +## 8.3.2 - 2026-11-12 ### Fixed From ec363290f2b6ca70118d0ed8f80e9c70a9d7965b Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 18:39:09 +0000 Subject: [PATCH 06/23] Scope stream handler error capture to the current transfer (#3996) * Raise minimum psr7 version to 3.3 * Scope stream handler error capture to the current transfer --- CHANGELOG.md | 5 ++++ composer.json | 4 +-- docs/guzzle-and-psr-7.md | 6 ++--- docs/package-ecosystem.md | 2 +- docs/request-options.md | 2 +- src/Handler/StreamHandler.php | 20 +++------------ tests/Handler/StreamHandlerTest.php | 40 +++++++++++++++++++++++++++++ 7 files changed, 55 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b148cb00e..ab087afca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,14 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version ### 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 + ## 8.3.2 - 2026-11-12 diff --git a/composer.json b/composer.json index a3f45936f..e830f68a4 100644 --- a/composer.json +++ b/composer.json @@ -54,7 +54,7 @@ "php": "^7.4 || ^8.0", "ext-json": "*", "guzzlehttp/promises": "^3.1", - "guzzlehttp/psr7": "^3.2", + "guzzlehttp/psr7": "^3.3", "psr/http-client": "^1.0", "psr/http-factory": "^1.0", "symfony/polyfill-php80": "^1.25", @@ -84,7 +84,7 @@ "name": "guzzle/client-integration-tests", "version": "v4.0.1", "require": { - "guzzlehttp/psr7": "^3.2", + "guzzlehttp/psr7": "^3.3", "php": "^7.4 || ^8.0", "php-http/message": "^1.0 || ^2.0", "phpunit/phpunit": "^9.6.34", diff --git a/docs/guzzle-and-psr-7.md b/docs/guzzle-and-psr-7.md index 0078e20ea..3385895a1 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.3/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.3/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.3/docs/streams-and-decorators.md) diff --git a/docs/package-ecosystem.md b/docs/package-ecosystem.md index da174daa1..a421413f6 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 | |---------|------------|---------------| | `guzzlehttp/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.3/docs/psr-7-messages.md) | | `guzzlehttp/promises` | Working directly with promises returned by asynchronous operations. | [Promises docs](https://github.com/guzzle/promises/blob/3.1/docs/promise-quick-start.md) | Install `guzzlehttp/guzzle` for normal application HTTP work. It already depends diff --git a/docs/request-options.md b/docs/request-options.md index 159a6bfef..12f7e9c0c 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.3/docs/streams-and-decorators.md#creating-streams). > Supply a stream implementation you trust. ## uri_factory diff --git a/src/Handler/StreamHandler.php b/src/Handler/StreamHandler.php index 70ec27da4..3e907296a 100644 --- a/src/Handler/StreamHandler.php +++ b/src/Handler/StreamHandler.php @@ -895,26 +895,12 @@ private function createResource( #[\SensitiveParameter] ?UriInterface $diagnosticUri = null ) { - $errors = []; - \set_error_handler(static function (int $_, string $msg, string $file, int $line) use (&$errors): bool { - $errors[] = [ - 'message' => $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) diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index 3a123819e..68f8731b1 100644 --- a/tests/Handler/StreamHandlerTest.php +++ b/tests/Handler/StreamHandlerTest.php @@ -3699,6 +3699,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); From 4e2b6abf41661bbfd5ef784715b5470c02c20db6 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 18:55:22 +0000 Subject: [PATCH 07/23] Leave an unset from ini setting untouched in the stream handler (#3997) * Leave an unset from ini setting untouched in the stream handler * Count every open when blanking the from ini setting --- CHANGELOG.md | 1 + src/Handler/StreamHandler.php | 9 ++-- tests/Handler/StreamHandlerTest.php | 81 +++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab087afca..57a30ad2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version ### 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 diff --git a/src/Handler/StreamHandler.php b/src/Handler/StreamHandler.php index 3e907296a..107dc9531 100644 --- a/src/Handler/StreamHandler.php +++ b/src/Handler/StreamHandler.php @@ -106,7 +106,7 @@ final class StreamHandler private const DEFAULT_IDLE_TIMEOUT_MS = 60000; /** - * Number of transfers currently holding the from ini setting blank. + * Number of transfers currently opening, which share the from ini setting. */ private static int $fromBlankDepth = 0; @@ -1021,11 +1021,12 @@ 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. - // Overlapping transfers share the setting, so only the first - // one saves it and only the last one restores it. + // 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_set('from', ''); + $iniFrom = \ini_get('from') !== '' ? \ini_set('from', '') : false; if (self::$fromBlankDepth++ === 0) { self::$fromToRestore = $iniFrom; } diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index 68f8731b1..a47f1119e 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(); @@ -2511,6 +2537,61 @@ public function testDoesNotSendAFromIniValueSetDuringAnotherTransfer(): void 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) { From d3d6055e1b7c9b640170be6341d8b4582f36fd14 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 18:55:45 +0000 Subject: [PATCH 08/23] Release 8.4.0 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57a30ad2d..ccab86db3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. -## 8.4.0 - Upcoming +## 8.4.0 - 2026-11-12 ### Added From 5943ccd053e0d50831ca129e05dd3a0c2a53e4f6 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 21:45:03 +0000 Subject: [PATCH 09/23] Bump version to 8.5 (#3999) --- .github/workflows/ci.yml | 2 +- .github/workflows/static.yml | 2 +- README.md | 2 +- docs/overview.md | 4 ++-- src/RequestOptions.php | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 875b9f4fe..b9d2fb316 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ permissions: contents: read env: - COMPOSER_ROOT_VERSION: 8.4.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 98889eaf9..33f634783 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -9,7 +9,7 @@ permissions: contents: read env: - COMPOSER_ROOT_VERSION: 8.4.x-dev + COMPOSER_ROOT_VERSION: 8.5.x-dev jobs: phpstan: diff --git a/README.md b/README.md index e9635dd5c..bd907e525 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ composer require guzzlehttp/guzzle | Version | Status | PHP Version | |---------|--------------|--------------| -| 8.4 | Latest | >=7.4,<8.7 | +| 8.5 | Latest | >=7.4,<8.7 | | 7.16 | Maintenance | >=7.2.5,<8.7 | | 6.5 | End of Life | >=5.5,<8.0 | diff --git a/docs/overview.md b/docs/overview.md index 2e08a07a5..eccf4910e 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 guzzlehttp/guzzle:^8.4 +composer require guzzlehttp/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": { - "guzzlehttp/guzzle": "^8.4" + "guzzlehttp/guzzle": "^8.5" } } ``` diff --git a/src/RequestOptions.php b/src/RequestOptions.php index 38482b96f..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.4/docs/request-options.md + * @see https://github.com/guzzle/guzzle/blob/8.5/docs/request-options.md */ final class RequestOptions { From 1339729b49d38ef947a975e1b34639cec35f9f44 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Thu, 12 Nov 2026 21:48:17 +0000 Subject: [PATCH 10/23] Add a hook for replacing the default handler (#3998) * Add a hook for replacing the default handler * Narrow the description of the checks run before the default handler factory * Shorten the default handler factory documentation --- CHANGELOG.md | 7 ++ docs/handlers.md | 31 ++++++++ src/Utils.php | 43 ++++++++++ tests/UtilsTest.php | 185 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 266 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ccab86db3..3a89b2261 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. +## 8.5.0 - Upcoming + +### Added + +- Add `Utils::setDefaultHandlerFactory()` to replace the default handler + + ## 8.4.0 - 2026-11-12 ### Added diff --git a/docs/handlers.md b/docs/handlers.md index 500d27919..46ade1061 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: diff --git a/src/Utils.php b/src/Utils.php index 96ab99cbc..fbb4e68b6 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -18,6 +18,11 @@ final class Utils { + /** + * @var (callable(array, callable(): callable): callable)|null + */ + private static $defaultHandlerFactory; + private function __construct() { } @@ -59,11 +64,33 @@ public static function debugResource($value = null) 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; + } + /** * Chooses and creates a default handler to use based on the environment. * * The returned handler is not wrapped by any default middlewares. * + * A factory set with setDefaultHandlerFactory() creates the handler in + * place of the built-in selection. + * * @param array{transport_sharing?: mixed, max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions Handler constructor options. * * @return callable(RequestInterface, array): PromiseInterface Returns the best handler for the given system. @@ -81,6 +108,22 @@ public static function chooseHandler(array $handlerOptions = []): callable throw new InvalidArgumentException('max_idle_handles must be a non-negative integer.'); } + if (self::$defaultHandlerFactory === null) { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions); + } + + return (self::$defaultHandlerFactory)($handlerOptions, static function () use ($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions): callable { + return self::chooseBuiltInHandler($sharingMode, $sharingRequired, $connectionCapsRequired, $handlerOptions); + }); + } + + /** + * @param array{max_host_connections?: mixed, max_idle_handles?: mixed, max_total_connections?: mixed, multiplex?: mixed} $handlerOptions + * + * @return callable(RequestInterface, array): PromiseInterface + */ + private static function chooseBuiltInHandler(string $sharingMode, bool $sharingRequired, bool $connectionCapsRequired, array $handlerOptions): callable + { $sharedPoolCapsSupported = CurlVersion::supportsSharedPoolConnectionCaps(); if ($connectionCapsRequired && !$sharedPoolCapsSupported && $sharingMode === TransportSharing::PERSISTENT_REQUIRE) { diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 665505321..44e328bfe 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -4,15 +4,19 @@ namespace GuzzleHttp\Tests; +use GuzzleHttp\Client; use GuzzleHttp\Exception\InvalidArgumentException; 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; @@ -368,6 +372,187 @@ public function testChooseHandlerAcceptsDisabledTransportSharing(): void } } + public function testChooseHandlerUsesTheDefaultHandlerFactory(): void + { + $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 static function invalidHandlerOptionProvider(): iterable + { + 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 total connections' => [['max_total_connections' => '1'], 'max_total_connections must be a positive integer.']; + } + + public function testChooseHandlerDefersEnvironmentChecksToTheBuiltInHandlerCallable(): void + { + $previousVersionInfo = self::setCurlVersionInfo([ + 'version' => '8.21.0', + 'features' => self::curlSslFeature(), + ]); + + $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 testChooseHandlerRejectsANonCallableFromTheDefaultHandlerFactory(): void + { + Utils::setDefaultHandlerFactory(static function () { + return 'not callable'; + }); + + try { + $this->expectException(\TypeError::class); + + Utils::chooseHandler(); + } finally { + Utils::setDefaultHandlerFactory(null); + } + } + + public function testExplicitHandlersBypassTheDefaultHandlerFactory(): void + { + $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 testClientsKeepTheHandlerCreatedByTheDefaultHandlerFactory(): void + { + $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)]); + }); + + $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()); From 16a041cc9231fab6ec5bb58cc1b564c327a5a0fb Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Fri, 13 Nov 2026 03:11:42 +0000 Subject: [PATCH 11/23] Deprecate the remaining focused Utils helpers and adopt psr7 3.4 (#3983) * Deprecate the remaining focused Utils helpers and adopt promises 3.2 and psr7 3.4 * Keep the default user agent private and deprecate in PHPDoc only * Leave the promises requirement and usage unchanged * Drop the no replacement wording from the changelog * Restore the runtime deprecations for the deprecated Utils methods * Keep calling Utils::modifyRequest() * Split the deprecation changelog entry in two * Require the released psr7 3.4 --- CHANGELOG.md | 9 +++ composer.json | 5 +- docs/guzzle-and-psr-7.md | 6 +- docs/package-ecosystem.md | 2 +- docs/request-options.md | 2 +- src/Client.php | 9 ++- src/Exception/RequestException.php | 2 +- src/Handler/CurlFactory.php | 9 ++- src/Handler/DebugResource.php | 36 ++++++++++ src/Handler/EasyHandle.php | 3 +- src/Handler/HeaderProcessor.php | 37 +++++++++- src/Handler/Protocols.php | 47 ++++++++++++ src/Handler/StreamHandler.php | 7 +- src/Handler/UriDiagnostic.php | 2 +- src/RedirectMiddleware.php | 4 +- src/Utils.php | 100 +++++++++++++++----------- tests/Handler/DebugResourceTest.php | 16 +++++ tests/Handler/HeaderProcessorTest.php | 42 +++++++++++ tests/Handler/ProtocolsTest.php | 25 +++++++ tests/UtilsTest.php | 60 ---------------- 20 files changed, 295 insertions(+), 128 deletions(-) create mode 100644 src/Handler/DebugResource.php create mode 100644 src/Handler/Protocols.php create mode 100644 tests/Handler/DebugResourceTest.php create mode 100644 tests/Handler/ProtocolsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a89b2261..262bd4e63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,15 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version - 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 diff --git a/composer.json b/composer.json index e830f68a4..9b168e0bd 100644 --- a/composer.json +++ b/composer.json @@ -54,9 +54,10 @@ "php": "^7.4 || ^8.0", "ext-json": "*", "guzzlehttp/promises": "^3.1", - "guzzlehttp/psr7": "^3.3", + "guzzlehttp/psr7": "^3.4", "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" }, @@ -84,7 +85,7 @@ "name": "guzzle/client-integration-tests", "version": "v4.0.1", "require": { - "guzzlehttp/psr7": "^3.3", + "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/guzzle-and-psr-7.md b/docs/guzzle-and-psr-7.md index 3385895a1..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.3/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.3/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.3/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/package-ecosystem.md b/docs/package-ecosystem.md index a421413f6..566b88669 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 | |---------|------------|---------------| | `guzzlehttp/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.3/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) | | `guzzlehttp/promises` | Working directly with promises returned by asynchronous operations. | [Promises docs](https://github.com/guzzle/promises/blob/3.1/docs/promise-quick-start.md) | Install `guzzlehttp/guzzle` for normal application HTTP work. It already depends diff --git a/docs/request-options.md b/docs/request-options.md index 12f7e9c0c..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.3/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 eccd54715..91443ab89 100644 --- a/src/Client.php +++ b/src/Client.php @@ -683,6 +683,11 @@ public function getConfig(?string $option = null) : ($this->config[$option] ?? null); } + private static function defaultUserAgent(): string + { + return sprintf('GuzzleHttp/%d', ClientInterface::MAJOR_VERSION); + } + private function buildUri( UriInterface $uri, #[\SensitiveParameter] @@ -894,7 +899,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']); @@ -908,7 +913,7 @@ private function configureDefaults( } if (!$hasUserAgent) { - $this->config['headers']['User-Agent'] = Utils::defaultUserAgent(); + $this->config['headers']['User-Agent'] = self::defaultUserAgent(); } } } 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/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/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..24edafde2 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 @@ -73,7 +72,25 @@ 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(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 @@ -177,7 +194,7 @@ public static function validateResponseFraming( return null; } - $normalizedKeys = Utils::normalizeHeaderKeys($headers); + $normalizedKeys = self::normalizeHeaderKeys($headers); $contentLength = self::removeHeader('Content-Length', $headers); try { @@ -264,6 +281,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 @@ +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/Utils.php b/src/Utils.php index fbb4e68b6..a32f0b5fb 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -9,6 +9,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; @@ -32,17 +35,20 @@ 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; + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return HeaderProcessor::headersFromLines($lines); } /** @@ -51,17 +57,20 @@ 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; - } - - return Psr7\Utils::tryFopen('php://output', 'w'); + \trigger_deprecation( + 'guzzlehttp/guzzle', + '8.5', + '%s() is deprecated and will be removed in 9.0.', + __METHOD__ + ); + + return DebugResource::from($value); } /** @@ -296,24 +305,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); } /** @@ -322,27 +348,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/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]; @@ -252,6 +278,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/UtilsTest.php b/tests/UtilsTest.php index 44e328bfe..c9d502100 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -28,32 +28,6 @@ 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()); @@ -558,40 +532,6 @@ public function testDefaultUserAgent(): void self::assertIsString(Utils::defaultUserAgent()); } - public function testReturnsDebugResource(): void - { - self::assertIsResource(Utils::debugResource()); - } - - public function testNormalizeHeaderKeys(): void - { - $input = ['HelLo' => 'foo', 'WORld' => 'bar']; - $expected = ['hello' => 'HelLo', 'world' => 'WORld']; - - self::assertSame($expected, Utils::normalizeHeaderKeys($input)); - } - - public function testNormalizeHeaderKeysHandlesNumericKeys(): void - { - $input = [0 => 'zero', 'HelLo' => 'foo']; - $expected = [0 => 0, 'hello' => 'HelLo']; - - self::assertSame($expected, Utils::normalizeHeaderKeys($input)); - } - - public function testNormalizeProtocolsAcceptsLowercaseProtocols(): void - { - self::assertSame(['http', 'https'], Utils::normalizeProtocols(['http', 'https', 'http'])); - } - - public function testNormalizeProtocolsRejectsUppercaseProtocols(): void - { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('protocols may only contain "http" and "https"'); - - Utils::normalizeProtocols(['HTTPS']); - } - private static function skipIfDefaultCurlHandlerIsUnavailable(): void { if ( From f8aca40edffeae0ec508b92f4594766083c6e203 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Fri, 13 Nov 2026 03:12:32 +0000 Subject: [PATCH 12/23] Release 8.5.0 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 262bd4e63..24e2d27e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version. -## 8.5.0 - Upcoming +## 8.5.0 - 2026-11-13 ### Added From d60c32b9d99a4f7cf7d329eee8ec122c8ac6cdfa Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:43:54 +0000 Subject: [PATCH 13/23] Validate fork handler options before the default handler factory Guzzle 8.5 added Utils::setDefaultHandlerFactory() and documents that a registered factory is only consulted after the handler options have been checked for type and value. The fork's max_idle_multi_handlers option is checked in the same place, before the factory is called, so a factory never receives an invalid limit or a limit combined with connection caps. Add both fork checks to upstream's provider of options that must fail without calling the factory: a negative max_idle_multi_handlers, and max_idle_multi_handlers combined with max_total_connections, which needs one shared cURL multi handler and so cannot use the coroutine handler pool. --- tests/UtilsTest.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 5152165b5..153931be9 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -452,6 +452,8 @@ public static function invalidHandlerOptionProvider(): iterable 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.']; } From 2c3f8ab1feb4336b972a2e5f17392180ac7b78bd Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:43:54 +0000 Subject: [PATCH 14/23] Keep the coroutine handler limits through the default handler factory A default handler factory receives a callable that returns the handler Guzzle would have chosen. In the fork that is the coroutine-aware default, which leases cURL multi handlers from a pool sized by max_idle_multi_handlers, and whose leased handlers use the client's max_idle_handles. The validated pool size is passed to the built-in selection separately from the handler options, so this path needs its own coverage. Register a factory that returns the built-in handler and check that both the pool size and the idle easy handle limit of a leased handler match the client's options. Dropping the pool size on this path makes the test fail. --- tests/UtilsTest.php | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/UtilsTest.php b/tests/UtilsTest.php index 153931be9..0ca13ba9a 100644 --- a/tests/UtilsTest.php +++ b/tests/UtilsTest.php @@ -520,6 +520,39 @@ public function testChooseHandlerPassesABuiltInHandlerCallableToTheDefaultHandle } } + 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 testChooseHandlerRejectsANonCallableFromTheDefaultHandlerFactory(): void { Utils::setDefaultHandlerFactory(static function () { From 7028a14121224bb8ff78e97360f29bb6b5c46854 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:44:05 +0000 Subject: [PATCH 15/23] Point the coroutine handler reference at the 8.5 branch The fork now tracks upstream's 8.5 branch, and the 8.3 branch will be deleted once this release is published. Update the ContextualCurlMultiHandler @see link so it keeps resolving to the Coroutine Handlers section of the handler guide. --- src/Handler/ContextualCurlMultiHandler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 { From 8a053824901105c3774fe46b0ff4c23786dc4749 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:44:05 +0000 Subject: [PATCH 16/23] Stop listing #3935 as an upstream pull request carried by the fork The fork carried guzzle/guzzle#3935 to provide the max_idle_handles option before upstream accepted it. Upstream shipped the option in 8.4.0 as #3993, and this sync replaces the fork's copy with upstream's implementation, so the README no longer needs to list it. The stream handler fixes mentioned in the same bullet were already upstream's. The fork's remaining difference, the larger CurlHandler default of 256 idle easy handles, is still described in the "More idle cURL handles" bullet. --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index 1c6ca1f98..f882444dc 100644 --- a/README.md +++ b/README.md @@ -53,10 +53,6 @@ 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. > [!IMPORTANT] > This fork keeps upstream's public API. Once installed, it replaces From 19f0dd99db9722e19779c6babf8d240de257022d Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:44:05 +0000 Subject: [PATCH 17/23] Describe max_idle_multi_handlers in upstream's words Upstream's accepted documentation for max_idle_handles reads "Zero disables retention; null or omission keeps the default of ..." without a separate sentence listing the accepted types, which the (int|null) prefix already gives. Use the same wording for max_idle_multi_handlers so the two neighbouring options read alike. The Client constructor documentation and the Coroutine Handlers section of the handler guide share this text word for word, so both are updated together. --- docs/handlers.md | 5 ++--- src/Client.php | 6 +++--- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/handlers.md b/docs/handlers.md index 860949eca..0268c69ee 100644 --- a/docs/handlers.md +++ b/docs/handlers.md @@ -240,9 +240,8 @@ One client can serve concurrent coroutines; each promise must still be created and completed in its owning coroutine. `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/src/Client.php b/src/Client.php index 0cbc93b44..8c6569a84 100644 --- a/src/Client.php +++ b/src/Client.php @@ -78,9 +78,9 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface * 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 From 279b4392373dc80aaf4d7c2bb3e245e958c79a8e Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:44:05 +0000 Subject: [PATCH 18/23] Explain how a default handler factory affects the coroutine handler Guzzle 8.5 lets an application register a default handler factory, which receives a callable that returns the handler Guzzle would have chosen. In the fork that handler leases cURL multi handlers to coroutines. Note in the Coroutine Handlers section that a factory wrapping the callable's handler keeps that behavior, while a factory that creates its own handler replaces it, just as a custom handler option does. --- docs/handlers.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/handlers.md b/docs/handlers.md index 0268c69ee..b327ffc68 100644 --- a/docs/handlers.md +++ b/docs/handlers.md @@ -239,6 +239,10 @@ 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. Zero disables retention; null or omission keeps the default of 64. Cannot be combined with connection caps or a custom handler. From a846205e00a49357f69cf0ccefeb96a356a303e1 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:12:15 +0000 Subject: [PATCH 19/23] Remove later cookie duplicates when the stored cookie is unchanged A stored cookie's path or domain can be changed through the object the jar hands out, which can leave two cookies with the same name, domain and path. Upstream 8.5.0 handles this when an incoming cookie replaces the first match: later matches are dropped. When the incoming cookie was identical to the first match, though, setCookie() returned straight away and the duplicate stayed, so both values were sent in the Cookie header. Keep scanning after an unchanged match so later duplicates are removed the same way, then return false as before, since nothing new was stored. A comment at the change notes how it differs from upstream. The new regression test sits next to upstream's test for the replaced case and calls setCookie() directly so it also checks the return value. --- src/Cookie/CookieJar.php | 10 ++++++++-- tests/Cookie/CookieJarTest.php | 13 +++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Cookie/CookieJar.php b/src/Cookie/CookieJar.php index f1aeedc91..e9ed31971 100644 --- a/src/Cookie/CookieJar.php +++ b/src/Cookie/CookieJar.php @@ -197,6 +197,7 @@ 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. @@ -215,7 +216,7 @@ public function setCookie( } // A stored cookie can be mutated into a duplicate, so drop later matches - if ($replaced) { + if ($replaced || $unchanged) { unset($this->cookies[$i]); continue; } @@ -233,7 +234,12 @@ public function setCookie( 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; } diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index eb2c7651e..64e0b59e5 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -655,6 +655,19 @@ public function testReplacementRemovesStoredCookieChangedIntoDuplicate(): void 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([ From 13b6ce5cdae995387d8e4d22cbe51e7affdb2956 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:12:15 +0000 Subject: [PATCH 20/23] Keep response headers out of exception traces in header parsing StreamHandler::createResponse() already marks the raw response header lines as sensitive, but the HeaderProcessor methods it hands them to didn't. parseHeaders(), validateResponseFraming() and parseTransferEncoding() throw on malformed responses, so with exception arguments enabled their trace frames held the full headers, including Set-Cookie values. headersFromLines() iterates whatever the deprecated Utils::headersFromLines() forwarder is given, so a throwing iterable exposed the lines in both frames. Add #[\SensitiveParameter] to those parameters, in upstream's attribute style, with a short comment at each noting the difference from upstream. Helpers that only rearrange header arrays and can't throw are left alone. The new test triggers an invalid header line and an unsupported transfer coding with a dummy Set-Cookie header, and checks both that the expected frames appear and that their header arguments are redacted. It runs on PHP 8.2 and newer, where the attribute takes effect. --- src/Handler/HeaderProcessor.php | 23 +++++++++---- src/Utils.php | 7 ++-- tests/Handler/HeaderProcessorTest.php | 49 +++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 8 deletions(-) diff --git a/src/Handler/HeaderProcessor.php b/src/Handler/HeaderProcessor.php index 24edafde2..9ebf46b8d 100644 --- a/src/Handler/HeaderProcessor.php +++ b/src/Handler/HeaderProcessor.php @@ -24,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'); } @@ -81,8 +84,11 @@ public static function parseHeaders(array $headers): array * @param iterable $lines Header lines array of strings in the following * format: "Name: Value" */ - public static function headersFromLines(iterable $lines): array - { + 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) { @@ -188,6 +194,8 @@ 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)) { @@ -224,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) { diff --git a/src/Utils.php b/src/Utils.php index 8b8c8baaa..c254c2bb4 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -40,8 +40,11 @@ private function __construct() * @deprecated Utils::headersFromLines() will be removed in * guzzlehttp/guzzle:9.0. */ - public static function headersFromLines(iterable $lines): array - { + 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', diff --git a/tests/Handler/HeaderProcessorTest.php b/tests/Handler/HeaderProcessorTest.php index 8a8457dc4..9640f2723 100644 --- a/tests/Handler/HeaderProcessorTest.php +++ b/tests/Handler/HeaderProcessorTest.php @@ -256,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 * From efb56e26c69ec44bff64f9b5367f55245e64a04d Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:12:15 +0000 Subject: [PATCH 21/23] Destroy suspended fibers before restoring the from setting testRestoresTheFromIniAfterOverlappingTransfers parks two transfers in fibers while the from ini setting is blanked. If an assertion failed while a fiber was still suspended, the test's finally block restored the previous setting first, then the fiber was destroyed when the test method returned. Destroying it ran the stream handler's own finally block, which put back the test's ini@example.com value and leaked it into later tests. Unset the fibers at the start of the finally block so their cleanup runs before the test restores the setting. --- tests/Handler/StreamHandlerTest.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/Handler/StreamHandlerTest.php b/tests/Handler/StreamHandlerTest.php index a47f1119e..376ea06f2 100644 --- a/tests/Handler/StreamHandlerTest.php +++ b/tests/Handler/StreamHandlerTest.php @@ -2630,6 +2630,10 @@ public function testRestoresTheFromIniAfterOverlappingTransfers(): void 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); } From de36e6bcaa51c62bc25a559d456564b59c913f8c Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:12:15 +0000 Subject: [PATCH 22/23] List the fork's fixes to inherited upstream bugs in the README AGENTS.md asks for fork-only changes to be recorded in the README's Hypervel Fork section. Add a short entry for the cookie duplicate fix and the header redaction in response parsing, neither of which is in upstream. --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index f882444dc..f4c5dff68 100644 --- a/README.md +++ b/README.md @@ -53,6 +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). +- **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 From 008b8073a613a42922c6b17aea5451d83efa18b9 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:12:15 +0000 Subject: [PATCH 23/23] Allow fixing inherited upstream bugs in the fork Confirmed upstream bugs that are worth fixing can now be fixed directly in the fork, with a short code comment explaining why the code differs from upstream. They don't need an upstream pull request unless the owner asks for one. The reconcile rule for syncs now covers any fix the fork carries, not only fixes submitted to upstream as pull requests, so a later upstream fix for the same bug is reconciled with ours the same way. --- AGENTS.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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