src/EventSubscriber/PublicApiCacheSubscriber.php line 28

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 PublicApiCacheSubscriber implements EventSubscriberInterface
  8. {
  9.     private const PUBLIC_API_PREFIXES = [
  10.         '/api/leaderboard/top',
  11.         '/i18n/',
  12.     ];
  13.     public function __construct(private Security $security)
  14.     {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::RESPONSE => ['onResponse'0],
  20.         ];
  21.     }
  22.     public function onResponse(ResponseEvent $event): void
  23.     {
  24.         if (!$event->isMainRequest()) {
  25.             return;
  26.         }
  27.         $request $event->getRequest();
  28.         if ($request->getMethod() !== 'GET') {
  29.             return;
  30.         }
  31.         $path $request->getPathInfo() ?? '';
  32.         $isPublicPath false;
  33.         foreach (self::PUBLIC_API_PREFIXES as $prefix) {
  34.             if (str_starts_with($path$prefix)) {
  35.                 $isPublicPath true;
  36.                 break;
  37.             }
  38.         }
  39.         if (!$isPublicPath) {
  40.             return;
  41.         }
  42.         if ($this->security->getUser()) {
  43.             return;
  44.         }
  45.         $response $event->getResponse();
  46.         $response->setPublic();
  47.         $response->setMaxAge(300);
  48.         $response->setSharedMaxAge(600);
  49.     }
  50. }