src/EventSubscriber/LoadPermissionSubscriber.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Account;
  4. use App\Entity\AccountOrganization;
  5. use App\Repository\PermissionRepository;
  6. use DateInterval;
  7. use DateTime;
  8. use DateTimeImmutable;
  9. use Exception;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. class LoadPermissionSubscriber implements EventSubscriberInterface
  14. {
  15.     private string               $validityIntervalValue;
  16.     private PermissionRepository $permissionRepository;
  17.     public function __construct(
  18.         string $validityIntervalValue,
  19.         PermissionRepository $permissionRepository,
  20.     ) {
  21.         $this->validityIntervalValue $validityIntervalValue;
  22.         $this->permissionRepository $permissionRepository;
  23.     }
  24.     public static function getSubscribedEvents():array
  25.     {
  26.         return [
  27.             KernelEvents::CONTROLLER => 'onKernelController',
  28.         ];
  29.     }
  30.     /**
  31.      * @throws Exception
  32.      */
  33.     public function onKernelController(ControllerEvent $event):void
  34.     {
  35.         $session $event->getRequest()->getSession();
  36.         $user $session->get('User');
  37.         // S'il y a un utilisateur authentifié
  38.         if ($user) {
  39.             $validity $session->get('PermissionValidity');
  40.             if ($validity === null || $validity < new DateTimeImmutable()) {
  41.                 // Défini la validité des permissions en session
  42.                 $session->set('PermissionValidity',
  43.                     (new DateTime())->add(new DateInterval($this->validityIntervalValue)));
  44.                 $permissions = [];
  45.                 // Récupère les permissions en fonction de l'utilisateur
  46.                 if (in_array('ROLE_ADMIN'$user->getRoles(), true)) {
  47.                     $permissions $this->permissionRepository->findAllNames();
  48.                 } elseif ($user instanceof Account || $user instanceof AccountOrganization) {
  49.                     $permissions $this->permissionRepository->findByAccount($user);
  50.                 }
  51.                 // Défini les permissions en session
  52.                 $session->set('Permission'$permissions);
  53.             }
  54.         }
  55.     }
  56. }