src/Security/Voter/UserVoter.php line 10

Open in your IDE?
  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. use Symfony\Component\Security\Core\User\UserInterface;
  7. class UserVoter extends Voter
  8. {
  9.     public const VIEW 'USER_VIEW';
  10.     public const EDIT 'USER_EDIT';
  11.     /**
  12.      * @inheritDoc
  13.      */
  14.     protected function supports(string $attributemixed $subject): bool
  15.     {
  16.         // Only vote on User objects and supported attributes
  17.         return in_array($attribute, [self::VIEWself::EDIT])
  18.             && $subject instanceof User;
  19.     }
  20.     /**
  21.      * @inheritDoc
  22.      */
  23.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  24.     {
  25.         $currentUser $token->getUser();
  26.         if (!$currentUser instanceof UserInterface) {
  27.             return false// not logged in
  28.         }
  29.         /** @var User $user */
  30.         $user $subject;
  31.         switch ($attribute) {
  32.             case self::VIEW:
  33.                 return $this->canView($user$currentUser);
  34.             case self::EDIT:
  35.                 return $this->canEdit($user$currentUser);
  36.         }
  37.         return false;
  38.     }
  39.     private function canView(User $userUserInterface $currentUser): bool
  40.     {
  41.         // Admins can view everyone
  42.         if (in_array('ROLE_ADMIN'$currentUser->getRoles(), true)) {
  43.             return true;
  44.         }
  45.         // A user can view their own data
  46.         return $currentUser === $user;
  47.     }
  48.     private function canEdit(User $userUserInterface $currentUser): bool
  49.     {
  50.         // Admins can edit everyone
  51.         if (in_array('ROLE_ADMIN'$currentUser->getRoles(), true)) {
  52.             return true;
  53.         }
  54.         // A user can edit only their own profile
  55.         return $currentUser === $user;
  56.     }
  57. }