src/Voter/UserVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Voter;
  3. use App\Entity\Supplier;
  4. use App\Entity\User as UserEntity;
  5. use App\Model\User\User;
  6. use Exception;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. class UserVoter extends Voter
  10. {
  11.     public const SEARCH_USER 'search_user';
  12.     private $user;
  13.     public function __construct(User $user)
  14.     {
  15.         $this->user            $user;
  16.     }
  17.     protected function supports($attribute$subject): bool
  18.     {
  19.         // if the attribute isn't one we support, return false
  20.         if (! in_array($attribute, [
  21.             self::SEARCH_USER
  22.         ])) {
  23.             return false;
  24.         }
  25.         return true;
  26.     }
  27.     /**
  28.      * @param string $attribute
  29.      * @param Supplier $entity
  30.      *
  31.      * @return bool
  32.      * @throws Exception
  33.      */
  34.     protected function voteOnAttribute($attribute$entityTokenInterface $token): bool
  35.     {
  36.         $userEntity $token->getUser();
  37.         if (! $userEntity instanceof UserEntity) {
  38.             // the user must be logged in; if not, deny access
  39.             return false;
  40.         }
  41.         $this->user->setEntity($userEntity);
  42.         switch ($attribute) {
  43.             case self::SEARCH_USER:
  44.                 return $this->user->canSearchUser();
  45.         }
  46.         return false;
  47.     }
  48. }