src/Security/Voter/HowToStartVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\User;
  4. use App\Utils\Commons;
  5. use LogicException;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Core\User\UserInterface;
  10. class HowToStartVoter extends Voter
  11. {
  12.     const HOW_TO_START_VIEW 'HOW_TO_START_VIEW';
  13.     /**
  14.      * @var Security
  15.      */
  16.     private $security;
  17.     /**
  18.      * @var Commons
  19.      */
  20.     private $commons;
  21.     /**
  22.      * @var array
  23.      */
  24.     private $permissions;
  25.     /**
  26.      * SupportVoter constructor.
  27.      * @param Security $security
  28.      * @param Commons $commons
  29.      */
  30.     public function __construct(Security $securityCommons $commons)
  31.     {
  32.         $this->security $security;
  33.         $this->commons $commons;
  34.         $this->permissions = [];
  35.     }
  36.     /**
  37.      * @param string $attribute
  38.      * @param mixed $subject
  39.      * @return bool
  40.      */
  41.     protected function supports($attribute$subject): bool
  42.     {
  43.         // if the attribute isn't one we support, return false
  44.         if (!in_array($attribute,
  45.             [self::HOW_TO_START_VIEW]
  46.         )) {
  47.             return false;
  48.         }
  49.         return true;
  50.     }
  51.     /**
  52.      * @param string $attribute
  53.      * @param mixed $subject
  54.      * @param TokenInterface $token
  55.      * @return bool
  56.      */
  57.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  58.     {
  59.         /** @var User $user */
  60.         $user $token->getUser();
  61.         // if the user is anonymous, do not grant access
  62.         if (!$user instanceof UserInterface) {
  63.             return false;
  64.         }
  65.         $this->permissions $this->commons->getUserPermissions($user);
  66.         switch ($attribute) {
  67.             case self::HOW_TO_START_VIEW:
  68.                 return $this->canView();
  69.         }
  70.         throw new LogicException('Invalid attribute: ' $attribute);
  71.     }
  72.     /**
  73.      * Return True if have View Permission else return false
  74.      * @return bool
  75.      */
  76.     private function canView(): bool
  77.     {
  78.         if ($this->security->isGranted('ROLE_ADMIN')) {
  79.             return true;
  80.         }
  81.         if (array_key_exists('howtostart'$this->permissions)) {
  82.             if (in_array('View'$this->permissions['howtostart'])) {
  83.                 return true;
  84.             }
  85.         }
  86.         return false;
  87.     }
  88. }