src/Security/Voter/ChangePlanVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Utils\Commons;
  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. class ChangePlanVoter extends Voter
  10. {
  11.     const CHANGE_PLAN 'CHANGE_PLAN';
  12.     private $commons;
  13.     private $security;
  14.     public function __construct(Security $securityCommons $commons)
  15.     {
  16.         $this->security $security;
  17.         $this->commons $commons;
  18.     }
  19.     /**
  20.      * @param string $attribute
  21.      * @param mixed $subject
  22.      * @return bool
  23.      */
  24.     protected function supports($attribute$subject): bool
  25.     {
  26.         if (!in_array($attribute,
  27.             [self::CHANGE_PLAN]
  28.         )) {
  29.             return false;
  30.         }
  31.         return true;
  32.     }
  33.     /**
  34.      * @param string $attribute
  35.      * @param mixed $subject
  36.      * @param TokenInterface $token
  37.      * @return bool
  38.      */
  39.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  40.     {
  41.         if ($this->security->isGranted('ROLE_ADMIN')) {
  42.             return true;
  43.         }
  44.         /** @var User $user */
  45.         $user $token->getUser();
  46.         if (!$user instanceof UserInterface) {
  47.             return false;
  48.         }
  49.         switch ($attribute) {
  50.             case 'CHANGE_PLAN':
  51.                 return $this->canChangePlan($user);
  52.         }
  53.         return false;
  54.     }
  55.     /** Return True if have Buy Permission else return false */
  56.     private function canChangePlan(User $user): bool
  57.     {
  58.         $permissions $this->commons->getUserPermissions($user);
  59.         if ($permissions) {
  60.             if (array_key_exists('changePlan'$permissions)) {
  61.                 if (in_array('Change'$permissions['changePlan'])) {
  62.                     return true;
  63.                 }
  64.             }
  65.         }
  66.         return false;
  67.     }
  68. }