<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class PublicApiCacheSubscriber implements EventSubscriberInterface
{
private const PUBLIC_API_PREFIXES = [
'/api/leaderboard/top',
'/i18n/',
];
public function __construct(private Security $security)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onResponse', 0],
];
}
public function onResponse(ResponseEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if ($request->getMethod() !== 'GET') {
return;
}
$path = $request->getPathInfo() ?? '';
$isPublicPath = false;
foreach (self::PUBLIC_API_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix)) {
$isPublicPath = true;
break;
}
}
if (!$isPublicPath) {
return;
}
if ($this->security->getUser()) {
return;
}
$response = $event->getResponse();
$response->setPublic();
$response->setMaxAge(300);
$response->setSharedMaxAge(600);
}
}