<?php
namespace App\EventSubscriber;
use App\Entity\User;
use App\Service\UseCaseCatalogService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
class UseCaseSelectionSubscriber implements EventSubscriberInterface
{
private const CATALOG_PATH = '/';
/**
* @var array<int, string>
*/
private const ALLOWED_PREFIXES = [
self::CATALOG_PATH,
'/logout',
'/api/use-cases',
'/build',
'/assets',
'/images',
'/img',
'/officials-imgs',
'/uploads',
'/fonts',
'/bundles',
'/i18n',
'/_profiler',
'/_wdt',
'/favicon.ico',
'/robots.txt',
'/sitemap',
'/hub',
];
public function __construct(
private readonly Security $security,
private readonly UseCaseCatalogService $catalogService,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 10]],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
if ($request->isMethod('OPTIONS')) {
return;
}
$user = $this->security->getUser();
if (!$user instanceof User) {
return;
}
if ($this->catalogService->hasSelection($user)) {
return;
}
$path = $request->getPathInfo() ?: '/';
if ($this->isAllowedPath($path)) {
return;
}
if (str_starts_with($path, '/api/')) {
return;
}
$event->setResponse(new RedirectResponse(self::CATALOG_PATH));
}
private function isAllowedPath(string $path): bool
{
foreach (self::ALLOWED_PREFIXES as $prefix) {
if (str_starts_with($path, $prefix)) {
return true;
}
}
return false;
}
}