Skip to content

Commit 6bd64db

Browse files
authored
always return stale on rejection (#169)
1 parent 65f85ca commit 6bd64db

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

src/CacheMiddleware.php

+3-5
Original file line numberDiff line numberDiff line change
@@ -237,11 +237,9 @@ function (ResponseInterface $response) use ($request, $cacheEntry) {
237237
return static::addToCache($this->cacheStorage, $request, $response, $update);
238238
},
239239
function ($reason) use ($cacheEntry) {
240-
if ($reason instanceof TransferException) {
241-
$response = static::getStaleResponse($cacheEntry);
242-
if ($response instanceof ResponseInterface) {
243-
return $response;
244-
}
240+
$response = static::getStaleResponse($cacheEntry);
241+
if ($response instanceof ResponseInterface) {
242+
return $response;
245243
}
246244

247245
return new RejectedPromise($reason);

tests/CacheMiddlewareTest.php

+23
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
namespace Kevinrob\GuzzleCache\Tests;
44

5+
use GuzzleHttp\Promise\RejectedPromise;
56
use GuzzleHttp\Psr7\Request;
67
use GuzzleHttp\Psr7\Response;
78
use GuzzleHttp\Psr7\Utils;
9+
use Kevinrob\GuzzleCache\CacheEntry;
810
use Kevinrob\GuzzleCache\CacheMiddleware as BaseCacheMiddleware;
911
use Kevinrob\GuzzleCache\Storage\Psr6CacheStorage;
1012
use Kevinrob\GuzzleCache\Strategy\CacheStrategyInterface;
@@ -35,6 +37,27 @@ public function testRewindAfterReadingStream()
3537

3638
$this->assertEquals('seekable stream', $response->getBody()->getContents());
3739
}
40+
41+
public function testStaleOnRejected()
42+
{
43+
$request = new Request('GET', '/uri');
44+
$response = (new Response())->withHeader('Cache-Control', 'stale-if-error=120');
45+
$strategy = $this->createStub(CacheStrategyInterface::class);
46+
$strategy->method('fetch')->willReturn(new CacheEntry(
47+
$request,
48+
$response,
49+
new \DateTime('-1 second')
50+
));
51+
$handler = function () {
52+
return new RejectedPromise(new \RuntimeException('Unexpected error'));
53+
};
54+
$middleware = new CacheMiddleware($strategy);
55+
56+
$result = ($middleware($handler)($request, []))->wait();
57+
58+
$this->assertInstanceOf(ResponseInterface::class, $result);
59+
$this->assertEquals(CacheMiddleware::HEADER_CACHE_STALE, $result->getHeaderLine(CacheMiddleware::HEADER_CACHE_INFO));
60+
}
3861
}
3962

4063
class CacheMiddleware extends BaseCacheMiddleware

0 commit comments

Comments
 (0)