Skip to content

[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 1 commit into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver;
use Symfony\Component\HttpKernel\Controller\ErrorController;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\EventListener\CacheAttributeListener;
use Symfony\Component\HttpKernel\EventListener\DisallowRobotsIndexingListener;
use Symfony\Component\HttpKernel\EventListener\ErrorListener;
use Symfony\Component\HttpKernel\EventListener\LocaleListener;
Expand Down Expand Up @@ -117,5 +118,9 @@
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'request'])

->set('controller.cache_attribute_listener', CacheAttributeListener::class)
->tag('kernel.event_subscriber')

;
};
84 changes: 84 additions & 0 deletions src/Symfony/Component/HttpKernel/Attribute/Cache.php
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,
) {
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Add constructor argument `bool $catchThrowable` to `HttpKernel`
* Add `ControllerEvent::getAttributes()` to handle attributes on controllers
* Add `#[Cache]` to describe the default HTTP cache headers on controllers

6.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface
/**
* {@inheritdoc}
*/
public function createArgumentMetadata(string|object|array $controller, \ReflectionClass $class = null, \ReflectionFunction $reflection = null): array
public function createArgumentMetadata(string|object|array $controller, \ReflectionClass $class = null, \ReflectionFunctionAbstract $reflection = null): array
{
$arguments = [];

Expand Down
14 changes: 12 additions & 2 deletions src/Symfony/Component/HttpKernel/Event/ControllerEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,18 @@ public function setController(callable $controller, array $attributes = null): v
unset($this->attributes);
}

$action = new \ReflectionFunction($controller(...));
$this->getRequest()->attributes->set('_controller_reflectors', [str_contains($action->name, '{closure}') ? null : $action->getClosureScopeClass(), $action]);
if (\is_array($controller) && method_exists(...$controller)) {
$action = new \ReflectionMethod(...$controller);
$class = new \ReflectionClass($controller[0]);
} elseif (\is_string($controller) && false !== $i = strpos($controller, '::')) {
$action = new \ReflectionMethod($controller);
$class = new \ReflectionClass(substr($controller, 0, $i));
} else {
$action = new \ReflectionFunction($controller(...));
$class = str_contains($action->name, '{closure}') ? null : $action->getClosureScopeClass();
}

$this->getRequest()->attributes->set('_controller_reflectors', [$class, $action]);
$this->controller = $controller;
}

Expand Down
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],
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;
}
}
Loading