src/Security/Voter/PermissionVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Service\PermissionService;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use Symfony\Component\Security\Core\User\UserInterface;
  7. class PermissionVoter extends Voter
  8. {
  9.     public const PERMISSION 'PERMISSION';
  10.     public function __construct(
  11.         private PermissionService $permissionService
  12.     ) {
  13.     }
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         // Le format attendu est "PERMISSION:module:action"
  17.         return str_starts_with($attribute'PERMISSION:');
  18.     }
  19.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  20.     {
  21.         $user $token->getUser();
  22.         // Si l'utilisateur n'est pas connectĂ©, refuser l'accès
  23.         if (!$user instanceof UserInterface) {
  24.             return false;
  25.         }
  26.         // Extraire le module et l'action de l'attribut
  27.         // Format: "PERMISSION:module:action"
  28.         $parts explode(':'$attribute);
  29.         
  30.         if (count($parts) !== || $parts[0] !== 'PERMISSION') {
  31.             return false;
  32.         }
  33.         $module $parts[1];
  34.         $action $parts[2];
  35.         return $this->permissionService->hasPermission($user$module$action);
  36.     }
  37. }