From 6bd64dbbe5155107d84a0f67140a8822a709c6d0 Mon Sep 17 00:00:00 2001 From: e-zannelli <41945822+e-zannelli@users.noreply.github.com> Date: Thu, 9 Nov 2023 07:53:45 +0100 Subject: [PATCH] always return stale on rejection (#169) --- src/CacheMiddleware.php | 8 +++----- tests/CacheMiddlewareTest.php | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/CacheMiddleware.php b/src/CacheMiddleware.php index 9e591d8..ee11520 100644 --- a/src/CacheMiddleware.php +++ b/src/CacheMiddleware.php @@ -237,11 +237,9 @@ function (ResponseInterface $response) use ($request, $cacheEntry) { return static::addToCache($this->cacheStorage, $request, $response, $update); }, function ($reason) use ($cacheEntry) { - if ($reason instanceof TransferException) { - $response = static::getStaleResponse($cacheEntry); - if ($response instanceof ResponseInterface) { - return $response; - } + $response = static::getStaleResponse($cacheEntry); + if ($response instanceof ResponseInterface) { + return $response; } return new RejectedPromise($reason); diff --git a/tests/CacheMiddlewareTest.php b/tests/CacheMiddlewareTest.php index a225bc7..2ec64ea 100644 --- a/tests/CacheMiddlewareTest.php +++ b/tests/CacheMiddlewareTest.php @@ -2,9 +2,11 @@ namespace Kevinrob\GuzzleCache\Tests; +use GuzzleHttp\Promise\RejectedPromise; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use Kevinrob\GuzzleCache\CacheEntry; use Kevinrob\GuzzleCache\CacheMiddleware as BaseCacheMiddleware; use Kevinrob\GuzzleCache\Storage\Psr6CacheStorage; use Kevinrob\GuzzleCache\Strategy\CacheStrategyInterface; @@ -35,6 +37,27 @@ public function testRewindAfterReadingStream() $this->assertEquals('seekable stream', $response->getBody()->getContents()); } + + public function testStaleOnRejected() + { + $request = new Request('GET', '/uri'); + $response = (new Response())->withHeader('Cache-Control', 'stale-if-error=120'); + $strategy = $this->createStub(CacheStrategyInterface::class); + $strategy->method('fetch')->willReturn(new CacheEntry( + $request, + $response, + new \DateTime('-1 second') + )); + $handler = function () { + return new RejectedPromise(new \RuntimeException('Unexpected error')); + }; + $middleware = new CacheMiddleware($strategy); + + $result = ($middleware($handler)($request, []))->wait(); + + $this->assertInstanceOf(ResponseInterface::class, $result); + $this->assertEquals(CacheMiddleware::HEADER_CACHE_STALE, $result->getHeaderLine(CacheMiddleware::HEADER_CACHE_INFO)); + } } class CacheMiddleware extends BaseCacheMiddleware