src/Security/Voter/SwitchToCustomerVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Data\RoleConstant;
  4. use App\Security\Voter\CRM\CRMAccessVoter;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. /**
  10.  * @extends Voter<string, mixed>
  11.  */
  12. class SwitchToCustomerVoter extends Voter
  13. {
  14.     private Security $security;
  15.     public function __construct(
  16.         Security $security
  17.     ) {
  18.         $this->security $security;
  19.     }
  20.     /**
  21.      * @param string $attribute
  22.      */
  23.     protected function supports($attribute$subject): bool
  24.     {
  25.         return 'CAN_SWITCH_USER' === $attribute && $subject instanceof UserInterface;
  26.     }
  27.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  28.     {
  29.         $user $token->getUser();
  30.         // if the user is anonymous or if the subject is not a user, do not grant access
  31.         if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
  32.             return false;
  33.         }
  34.         // you can still check for ROLE_ALLOWED_TO_SWITCH
  35.         if ($this->security->isGranted(CRMAccessVoter::CRM_ACCESSRoleConstant::ROLE_SUPPORT)) {
  36.             return true;
  37.         }
  38.         return false;
  39.     }
  40. }