src/Security/Voter/UserVoter.php line 13

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. /**
  8.  * Class UserVoter.
  9.  */
  10. class UserVoter extends Voter
  11. {
  12.     // Permissions.
  13.     const ACCOUNT_VIEW 'account_view';
  14.     // Full list.
  15.     const PERMISSIONS = [
  16.         self::ACCOUNT_VIEW,
  17.     ];
  18.     /**
  19.      * {@inheritdoc}
  20.      */
  21.     protected function supports($attribute$subject): bool
  22.     {
  23.         return in_array($attributeself::PERMISSIONS) && ($subject instanceof User);
  24.     }
  25.     /**
  26.      * {@inheritdoc}
  27.      */
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  29.     {
  30.         /** @var User $user */
  31.         $user $token->getUser();
  32.         // If the user is anonymous, do not grant access.
  33.         if (!$user instanceof UserInterface) {
  34.             return false;
  35.         }
  36.         // Check conditions and provide access bases on it.
  37.         switch ($attribute) {
  38.             case self::ACCOUNT_VIEW:
  39.                 return $this->canView($subject$user);
  40.             default:
  41.                 break;
  42.         }
  43.         return false;
  44.     }
  45.     /**
  46.      * Check that current user can view account space.
  47.      */
  48.     public function canView(User $subjectUser $user): bool
  49.     {
  50.         return $subject->getId() === $user->getId();
  51.     }
  52. }