Skip to content

Commit

Permalink
Add an HTTP cache middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
dunglas committed Dec 12, 2017
1 parent c2bb45c commit 5defbd7
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/Illuminate/Http/Middleware/Cache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Illuminate\Http\Middleware;

use Closure;

class Cache
{
/**
* Add cache related HTTP headers.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int|null $maxAge
* @param int|null $sharedMaxAge
* @param bool|null $public
* @param bool|null $etag
* @return \Symfony\Component\HttpFoundation\Response
*/
public function handle($request, Closure $next, int $maxAge = null, int $sharedMaxAge = null, bool $public = null, bool $etag = false)
{
/**
* @var \Symfony\Component\HttpFoundation\Response
*/
$response = $next($request);

if (! $request->isMethodCacheable() || ! $response->getContent()) {
return $response;
}

if (! $response->getContent()) {
return;
}
if ($etag) {
$response->setEtag(md5($response->getContent()));
}
if (null !== $maxAge) {
$response->setMaxAge($maxAge);
}
if (null !== $sharedMaxAge) {
$response->setSharedMaxAge($sharedMaxAge);
}
if (null !== $public) {
$public ? $response->setPublic() : $response->setPrivate();
}

return $response;
}
}
44 changes: 44 additions & 0 deletions tests/Http/Middleware/CacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Illuminate\Tests\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use PHPUnit\Framework\TestCase;
use Illuminate\Http\Middleware\Cache;

class CacheTest extends TestCase
{
public function testDoNotSetHeaderWhenMethodNotCacheable()
{
$request = new Request();
$request->setMethod('PUT');

$response = (new Cache())->handle($request, function () {
return new Response('Hello Laravel');
}, 1, 2, true, true);

$this->assertNull($response->getMaxAge());
$this->assertNull($response->getEtag());
}

public function testDoNotSetHeaderWhenNoContent()
{
$response = (new Cache())->handle(new Request(), function () {
return new Response();
}, 1, 2, true, true);

$this->assertNull($response->getMaxAge());
$this->assertNull($response->getEtag());
}

public function testAddHeaders()
{
$response = (new Cache())->handle(new Request(), function () {
return new Response('some content');
}, 100, 200, true, true);

$this->assertSame('"9893532233caff98cd083a116b013c0b"', $response->getEtag());
$this->assertSame('max-age=100, public, s-maxage=200', $response->headers->get('Cache-Control'));
}
}

0 comments on commit 5defbd7

Please sign in to comment.