-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[HttpKernel] Add #[Cache()]
to describe the default HTTP cache headers on controllers
#46880
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpKernel\Attribute; | ||
|
||
/** | ||
* Describes the default HTTP cache headers on controllers. | ||
* | ||
* @author Fabien Potencier <fabien@symfony.com> | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::TARGET_FUNCTION)] | ||
final class Cache | ||
{ | ||
public function __construct( | ||
/** | ||
* The expiration date as a valid date for the strtotime() function. | ||
*/ | ||
public ?string $expires = null, | ||
|
||
/** | ||
* The number of seconds that the response is considered fresh by a private | ||
* cache like a web browser. | ||
*/ | ||
public int|string|null $maxage = null, | ||
|
||
/** | ||
* The number of seconds that the response is considered fresh by a public | ||
* cache like a reverse proxy cache. | ||
*/ | ||
public int|string|null $smaxage = null, | ||
|
||
/** | ||
* Whether the response is public or not. | ||
*/ | ||
public ?bool $public = null, | ||
|
||
/** | ||
* Whether or not the response must be revalidated. | ||
*/ | ||
public bool $mustRevalidate = false, | ||
|
||
/** | ||
* Additional "Vary:"-headers. | ||
*/ | ||
public array $vary = [], | ||
|
||
/** | ||
* An expression to compute the Last-Modified HTTP header. | ||
*/ | ||
public ?string $lastModified = null, | ||
|
||
/** | ||
* An expression to compute the ETag HTTP header. | ||
*/ | ||
public ?string $etag = null, | ||
|
||
/** | ||
* max-stale Cache-Control header | ||
* It can be expressed in seconds or with a relative time format (1 day, 2 weeks, ...). | ||
*/ | ||
public int|string|null $maxStale = null, | ||
|
||
/** | ||
* stale-while-revalidate Cache-Control header | ||
* It can be expressed in seconds or with a relative time format (1 day, 2 weeks, ...). | ||
*/ | ||
public int|string|null $staleWhileRevalidate = null, | ||
|
||
/** | ||
* stale-if-error Cache-Control header | ||
* It can be expressed in seconds or with a relative time format (1 day, 2 weeks, ...). | ||
*/ | ||
public int|string|null $staleIfError = null, | ||
) { | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
193 changes: 193 additions & 0 deletions
193
src/Symfony/Component/HttpKernel/EventListener/CacheAttributeListener.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\HttpKernel\EventListener; | ||
|
||
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | ||
use Symfony\Component\ExpressionLanguage\ExpressionLanguage; | ||
use Symfony\Component\HttpFoundation\Request; | ||
use Symfony\Component\HttpFoundation\Response; | ||
use Symfony\Component\HttpKernel\Attribute\Cache; | ||
use Symfony\Component\HttpKernel\Event\ControllerEvent; | ||
use Symfony\Component\HttpKernel\Event\ResponseEvent; | ||
use Symfony\Component\HttpKernel\KernelEvents; | ||
|
||
/** | ||
* Handles HTTP cache headers configured via the Cache attribute. | ||
* | ||
* @author Fabien Potencier <fabien@symfony.com> | ||
*/ | ||
class CacheAttributeListener implements EventSubscriberInterface | ||
{ | ||
/** | ||
* @var \SplObjectStorage<Request, \DateTimeInterface> | ||
*/ | ||
private \SplObjectStorage $lastModified; | ||
|
||
/** | ||
* @var \SplObjectStorage<Request, string> | ||
*/ | ||
private \SplObjectStorage $etags; | ||
|
||
public function __construct( | ||
private ?ExpressionLanguage $expressionLanguage = null, | ||
) { | ||
$this->lastModified = new \SplObjectStorage(); | ||
$this->etags = new \SplObjectStorage(); | ||
} | ||
|
||
/** | ||
* Handles HTTP validation headers. | ||
*/ | ||
public function onKernelController(ControllerEvent $event) | ||
{ | ||
$request = $event->getRequest(); | ||
|
||
if (!\is_array($attributes = $request->attributes->get('_cache') ?? $event->getAttributes()[Cache::class] ?? null)) { | ||
return; | ||
} | ||
|
||
$request->attributes->set('_cache', $attributes); | ||
$response = null; | ||
$lastModified = null; | ||
$etag = null; | ||
|
||
/** @var Cache[] $attributes */ | ||
foreach ($attributes as $cache) { | ||
if (null !== $cache->lastModified) { | ||
$lastModified = $this->getExpressionLanguage()->evaluate($cache->lastModified, $request->attributes->all()); | ||
($response ??= new Response())->setLastModified($lastModified); | ||
} | ||
|
||
if (null !== $cache->etag) { | ||
$etag = hash('sha256', $this->getExpressionLanguage()->evaluate($cache->etag, $request->attributes->all())); | ||
($response ??= new Response())->setEtag($etag); | ||
} | ||
} | ||
|
||
if ($response?->isNotModified($request)) { | ||
$event->setController(static fn () => $response); | ||
$event->stopPropagation(); | ||
|
||
return; | ||
} | ||
|
||
if (null !== $etag) { | ||
$this->etags[$request] = $etag; | ||
} | ||
if (null !== $lastModified) { | ||
$this->lastModified[$request] = $lastModified; | ||
} | ||
} | ||
|
||
/** | ||
* Modifies the response to apply HTTP cache headers when needed. | ||
*/ | ||
public function onKernelResponse(ResponseEvent $event) | ||
{ | ||
$request = $event->getRequest(); | ||
|
||
/** @var Cache[] $attributes */ | ||
if (!\is_array($attributes = $request->attributes->get('_cache'))) { | ||
return; | ||
} | ||
$response = $event->getResponse(); | ||
|
||
// http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-12#section-3.1 | ||
if (!\in_array($response->getStatusCode(), [200, 203, 300, 301, 302, 304, 404, 410])) { | ||
unset($this->lastModified[$request]); | ||
unset($this->etags[$request]); | ||
|
||
return; | ||
} | ||
|
||
if (isset($this->lastModified[$request]) && !$response->headers->has('Last-Modified')) { | ||
$response->setLastModified($this->lastModified[$request]); | ||
} | ||
|
||
if (isset($this->etags[$request]) && !$response->headers->has('Etag')) { | ||
$response->setEtag($this->etags[$request]); | ||
} | ||
|
||
unset($this->lastModified[$request]); | ||
unset($this->etags[$request]); | ||
$hasVary = $response->headers->has('Vary'); | ||
|
||
foreach (array_reverse($attributes) as $cache) { | ||
if (null !== $cache->smaxage && !$response->headers->hasCacheControlDirective('s-maxage')) { | ||
$response->setSharedMaxAge($this->toSeconds($cache->smaxage)); | ||
} | ||
|
||
if ($cache->mustRevalidate) { | ||
$response->headers->addCacheControlDirective('must-revalidate'); | ||
} | ||
|
||
if (null !== $cache->maxage && !$response->headers->hasCacheControlDirective('max-age')) { | ||
$response->setMaxAge($this->toSeconds($cache->maxage)); | ||
} | ||
|
||
if (null !== $cache->maxStale && !$response->headers->hasCacheControlDirective('max-stale')) { | ||
$response->headers->addCacheControlDirective('max-stale', $this->toSeconds($cache->maxStale)); | ||
} | ||
|
||
if (null !== $cache->staleWhileRevalidate && !$response->headers->hasCacheControlDirective('stale-while-revalidate')) { | ||
$response->headers->addCacheControlDirective('stale-while-revalidate', $this->toSeconds($cache->staleWhileRevalidate)); | ||
} | ||
|
||
if (null !== $cache->staleIfError && !$response->headers->hasCacheControlDirective('stale-if-error')) { | ||
$response->headers->addCacheControlDirective('stale-if-error', $this->toSeconds($cache->staleIfError)); | ||
} | ||
|
||
if (null !== $cache->expires && !$response->headers->has('Expires')) { | ||
$response->setExpires(new \DateTimeImmutable('@'.strtotime($cache->expires, time()))); | ||
} | ||
|
||
if (!$hasVary && $cache->vary) { | ||
$response->setVary($cache->vary, false); | ||
} | ||
} | ||
|
||
foreach ($attributes as $cache) { | ||
if (true === $cache->public) { | ||
$response->setPublic(); | ||
} | ||
|
||
if (false === $cache->public) { | ||
$response->setPrivate(); | ||
} | ||
} | ||
} | ||
|
||
public static function getSubscribedEvents(): array | ||
{ | ||
return [ | ||
KernelEvents::CONTROLLER => ['onKernelController', 10], | ||
nicolas-grekas marked this conversation as resolved.
Show resolved
Hide resolved
|
||
KernelEvents::RESPONSE => ['onKernelResponse', -10], | ||
]; | ||
} | ||
|
||
private function getExpressionLanguage(): ExpressionLanguage | ||
{ | ||
return $this->expressionLanguage ??= class_exists(ExpressionLanguage::class) | ||
? new ExpressionLanguage() | ||
: throw new \LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed. Try running "composer require symfony/expression-language".'); | ||
} | ||
|
||
private function toSeconds(int|string $time): int | ||
{ | ||
if (!is_numeric($time)) { | ||
$now = time(); | ||
$time = strtotime($time, $now) - $now; | ||
} | ||
|
||
return $time; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.