src/Security/Voter/UserVoter.php line 9

  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. class UserVoter extends Voter
  7. {
  8.     const VIEW 'VIEW';
  9.     const CREATE 'CREATE';
  10.     const EDIT 'EDIT';
  11.     const DELETE 'DELETE';
  12.     protected function supports(string $attributemixed $subject): bool
  13.     {
  14.         $attributeArray = [self::VIEWself::CREATEself::EDITself::DELETE];
  15.         if (!in_array($attribute$attributeArray))
  16.             return false;
  17.         if (!$subject instanceof User)
  18.             return false;
  19.         return true;
  20.     }
  21.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  22.     {
  23.         $user $token->getUser();
  24.         if (!$user instanceof User)
  25.             return false;
  26.         return match ($attribute) {
  27.             self::VIEW => $this->canView($subject$user),
  28.             self::CREATE => $this->canCreate($subject$user),
  29.             self::EDIT => $this->canEdit($subject$user),
  30.             self::DELETE => $this->canDelete($subject$user),
  31.             default => throw new \LogicException('This code should not be reached!')
  32.         };
  33.     }
  34.     private function canCreate(User $supposedUserUser $user): bool
  35.     {
  36.         return in_array(User::ROLE_SUPER_ADMIN$user->getRoles());
  37.     }
  38.     private function canDelete(User $supposedUserUser $user): bool
  39.     {
  40.         if ($user->getId() === $supposedUser->getId()) {
  41.             return false;
  42.         }
  43.         return $this->canCreate($supposedUser$user);
  44.     }
  45.     public function canView(User $supposedUserUser $user): bool
  46.     {
  47.         return true;
  48.     }
  49.     public function canEdit(User $supposedUserUser $user): bool
  50.     {
  51.         if ($this->canCreate($supposedUser$user) || $user->getId() === $supposedUser->getId()) {
  52.             return true;
  53.         }
  54.         return false;
  55.     }
  56. }