src/EventSubscriber/AdminSectionSubscriber.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Controller\Admin\AbstractAdminController;
  4. use App\Controller\Admin\SectionSessionController;
  5. use App\Service\Admin\Session;
  6. use Symfony\Bundle\FrameworkBundle\Controller\RedirectController;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. /**
  11.  * Vérifie qu'une variable de session déterminant la section du back-office soit existante, sinon redirige l'utilisateur
  12.  * vers la page de sélection
  13.  */
  14. class AdminSectionSubscriber implements EventSubscriberInterface
  15. {
  16.     public function __construct(
  17.         private readonly Session $adminSession,
  18.         private readonly UrlGeneratorInterface $urlGenerator
  19.     ) {
  20.     }
  21.     public function onKernelController(ControllerEvent $event): void
  22.     {
  23.         $callable $event->getController();
  24.         if (is_array($callable) && null !== $callable[0]) {
  25.             $controller $callable[0];
  26.             if ($controller instanceof AbstractAdminController) {
  27.                 if ($controller instanceof SectionSessionController) {
  28.                     return;
  29.                 }
  30.                 if (null === $this->adminSession->getSection()) {
  31.                     $event->setController(function () use ($event) {
  32.                         return (new RedirectController($this->urlGenerator))
  33.                             ->redirectAction($event->getRequest(), 'admin_section_choice');
  34.                     });
  35.                 }
  36.             }
  37.         }
  38.     }
  39.     public static function getSubscribedEvents(): array
  40.     {
  41.         return [
  42.             'kernel.controller' => 'onKernelController',
  43.         ];
  44.     }
  45. }