src/EventSubscriber/UseCaseSelectionSubscriber.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use App\Service\UseCaseCatalogService;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Security\Core\Security;
  10. class UseCaseSelectionSubscriber implements EventSubscriberInterface
  11. {
  12.     private const CATALOG_PATH '/';
  13.     /**
  14.      * @var array<int, string>
  15.      */
  16.     private const ALLOWED_PREFIXES = [
  17.         self::CATALOG_PATH,
  18.         '/logout',
  19.         '/api/use-cases',
  20.         '/build',
  21.         '/assets',
  22.         '/images',
  23.         '/img',
  24.         '/officials-imgs',
  25.         '/uploads',
  26.         '/fonts',
  27.         '/bundles',
  28.         '/i18n',
  29.         '/_profiler',
  30.         '/_wdt',
  31.         '/favicon.ico',
  32.         '/robots.txt',
  33.         '/sitemap',
  34.         '/hub',
  35.     ];
  36.     public function __construct(
  37.         private readonly Security $security,
  38.         private readonly UseCaseCatalogService $catalogService,
  39.     ) {
  40.     }
  41.     public static function getSubscribedEvents(): array
  42.     {
  43.         return [
  44.             KernelEvents::REQUEST => [['onKernelRequest'10]],
  45.         ];
  46.     }
  47.     public function onKernelRequest(RequestEvent $event): void
  48.     {
  49.         if (!$event->isMainRequest()) {
  50.             return;
  51.         }
  52.         $request $event->getRequest();
  53.         if ($request->isMethod('OPTIONS')) {
  54.             return;
  55.         }
  56.         $user $this->security->getUser();
  57.         if (!$user instanceof User) {
  58.             return;
  59.         }
  60.         if ($this->catalogService->hasSelection($user)) {
  61.             return;
  62.         }
  63.         $path $request->getPathInfo() ?: '/';
  64.         if ($this->isAllowedPath($path)) {
  65.             return;
  66.         }
  67.         if (str_starts_with($path'/api/')) {
  68.             return;
  69.         }
  70.         $event->setResponse(new RedirectResponse(self::CATALOG_PATH));
  71.     }
  72.     private function isAllowedPath(string $path): bool
  73.     {
  74.         foreach (self::ALLOWED_PREFIXES as $prefix) {
  75.             if (str_starts_with($path$prefix)) {
  76.                 return true;
  77.             }
  78.         }
  79.         return false;
  80.     }
  81. }