src/EventSubscriber/GlobalHttpCacheSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\Security\Core\Security;
  7. class GlobalHttpCacheSubscriber implements EventSubscriberInterface
  8. {
  9.     public function __construct(private Security $security)
  10.     {
  11.     }
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             KernelEvents::RESPONSE => ['onResponse', -10],
  16.         ];
  17.     }
  18.     public function onResponse(ResponseEvent $event): void
  19.     {
  20.         if (!$event->isMainRequest()) {
  21.             return;
  22.         }
  23.         $request $event->getRequest();
  24.         if ($request->getMethod() !== 'GET') {
  25.             return;
  26.         }
  27.         $response $event->getResponse();
  28.         if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) {
  29.             return;
  30.         }
  31.         $cacheControl $response->headers->get('Cache-Control');
  32.         if ($cacheControl && (str_contains($cacheControl'no-store') || str_contains($cacheControl'no-cache'))) {
  33.             return;
  34.         }
  35.         if ($cacheControl) {
  36.             return;
  37.         }
  38.         $isAuthenticated = (bool) $this->security->getUser();
  39.         if ($isAuthenticated) {
  40.             $response->setPrivate();
  41.             $response->setMaxAge(30);
  42.             $response->setSharedMaxAge(0);
  43.             $response->headers->set('Vary''Cookie, Authorization'false);
  44.         } else {
  45.             $response->setPublic();
  46.             $response->setMaxAge(300);
  47.             $response->setSharedMaxAge(600);
  48.             $response->headers->set('Vary''Accept-Encoding, Accept-Language'false);
  49.             $response->headers->set(
  50.                 'Cache-Control',
  51.                 trim($response->headers->get('Cache-Control') . ', stale-while-revalidate=30, stale-if-error=600')
  52.             );
  53.             $contentType = (string) $response->headers->get('Content-Type');
  54.             if (str_contains($contentType'application/json') && !$response->getEtag()) {
  55.                 $response->setEtag(sha1((string) $response->getContent()));
  56.             }
  57.         }
  58.     }
  59. }