Skip to content

Commit 674fd7d

Browse files
committed
Replace response body on cache hit
Replacing the response body on cache hits to reduce data transmission
1 parent dd956e4 commit 674fd7d

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

src/Cache.php

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111

1212
use Psr\Http\Message\ResponseInterface;
1313
use Psr\Http\Message\ServerRequestInterface;
14+
use Psr\Http\Message\StreamFactoryInterface;
1415
use Psr\Http\Server\MiddlewareInterface;
1516
use Psr\Http\Server\RequestHandlerInterface;
1617

18+
use Slim\Psr7\Factory\StreamFactory;
1719
use function in_array;
1820
use function is_array;
1921
use function is_numeric;
@@ -45,18 +47,28 @@ class Cache implements MiddlewareInterface
4547
*/
4648
protected $mustRevalidate;
4749

50+
/**
51+
* @var StreamFactoryInterface
52+
*/
53+
protected $streamFactory;
54+
4855
/**
4956
* Create new HTTP cache
5057
*
5158
* @param string $type The cache type: "public" or "private"
5259
* @param int $maxAge The maximum age of client-side cache
5360
* @param bool $mustRevalidate must-revalidate
5461
*/
55-
public function __construct(string $type = 'private', int $maxAge = 86400, bool $mustRevalidate = false)
56-
{
62+
public function __construct(
63+
StreamFactoryInterface $streamFactory,
64+
string $type = 'private',
65+
int $maxAge = 86400,
66+
bool $mustRevalidate = false
67+
) {
5768
$this->type = $type;
5869
$this->maxAge = $maxAge;
5970
$this->mustRevalidate = $mustRevalidate;
71+
$this->streamFactory = $streamFactory;
6072
}
6173

6274
/**
@@ -101,7 +113,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
101113
if ($ifNoneMatch) {
102114
$etagList = preg_split('@\s*,\s*@', $ifNoneMatch);
103115
if (is_array($etagList) && (in_array($etag, $etagList) || in_array('*', $etagList))) {
104-
return $response->withStatus(304);
116+
return $response->withStatus(304)
117+
->withBody($this->streamFactory->createStream(''));
105118
}
106119
}
107120
}
@@ -118,7 +131,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
118131
$ifModifiedSince = $request->getHeaderLine('If-Modified-Since');
119132

120133
if ($ifModifiedSince && $lastModified <= strtotime($ifModifiedSince)) {
121-
return $response->withStatus(304);
134+
return $response->withStatus(304)
135+
->withBody($this->streamFactory->createStream(''));
122136
}
123137
}
124138

0 commit comments

Comments
 (0)