src/Security/Voter/GroupementVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Groupement;
  4. use App\Entity\UserAccess;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. class GroupementVoter extends AbstractVoter
  7. {
  8.     public const CREATE 'Groupement:Create';
  9.     public const VIEW 'Groupement:View';
  10.     public const EDIT 'Groupement:Edit';
  11.     public const DELETE 'Groupement:Delete';
  12.     public const CREATE_MAGASIN 'Groupement:Create-Magasin';
  13.     private ?Groupement $groupement null;
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         if ($attribute === self::CREATE) {
  17.             return true;
  18.         }
  19.         return in_array($attribute, [
  20.             self::EDIT,
  21.             self::VIEW,
  22.             self::DELETE,
  23.             self::CREATE_MAGASIN,
  24.         ])
  25.         && $subject instanceof Groupement;
  26.     }
  27.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  28.     {
  29.         $this->user $token->getUser();
  30.         $this->groupement $subject;
  31.         return match ($attribute) {
  32.             self::CREATE => $this->canCreate(),
  33.             self::VIEW => $this->canView(),
  34.             self::EDIT => $this->canEditGroupement(),
  35.             self::DELETE => $this->canDelete(),
  36.             self::CREATE_MAGASIN => $this->canCreateMagasin(),
  37.             default => false,
  38.         };
  39.     }
  40.     private function canCreate(): bool
  41.     {
  42.         return $this->isSuperAdmin();
  43.     }
  44.     private function canView(): bool
  45.     {
  46.         // Read-only superadmins can view all groupements
  47.         if ($this->isReadOnlySuperAdmin()) {
  48.             return true;
  49.         }
  50.         if ($this->isSuperAdmin()) {
  51.             return true;
  52.         }
  53.         return $this->isAdmin()
  54.             && $this->user->canAccessResource($this->groupement, [UserAccess::ROLE_ADMIN]);
  55.     }
  56.     private function canEditGroupement(): bool
  57.     {
  58.         // Only full superadmins can edit, not read-only
  59.         return parent::canEdit();
  60.     }
  61.     public function canDelete(): bool
  62.     {
  63.         // Only full superadmins can delete, not read-only
  64.         return parent::canEdit()
  65.             && $this->groupement->getId()
  66.             && $this->groupement->getMagasins()->isEmpty();
  67.     }
  68.     public function canCreateMagasin(): bool
  69.     {
  70.         // Only full superadmins can create, not read-only
  71.         return parent::canEdit();
  72.     }
  73. }