src/Security/Voter/EcohortVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Study;
  4. use App\Entity\Survey;
  5. use App\Entity\User;
  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. class EcohortVoter extends Voter
  10. {
  11.     const ECOHORT_MANAGE   'ECOHORT_MANAGE';
  12.     /**
  13.      * @var Security
  14.      */
  15.     private $security;
  16.     /**
  17.      * UserVoter constructor.
  18.      * @param Security $security
  19.      */
  20.     public function __construct(Security $security)
  21.     {
  22.         $this->security $security;
  23.     }
  24.     protected function supports($attribute$subject)
  25.     {
  26.         return in_array($attribute, [self::ECOHORT_MANAGE])
  27.             && ($subject instanceof Study || $subject instanceof Survey);
  28.     }
  29.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  30.     {
  31.         /** @var User $user */
  32.         $user $token->getUser();
  33.         // if the user is anonymous, do not grant access
  34.         if (!$user instanceof User) {
  35.             return false;
  36.         }
  37.         // if the user is anonymous, do not grant access
  38.         if (!in_array('ROLE_ADMIN'$user->getRoles()) || !in_array('ROLE_ECITY'$user->getRoles())) {
  39.             return false;
  40.         }
  41.         // get user permissions
  42.         $permissions $user->getPermissions();
  43.         if( !is_array($permissions) ) {
  44.             return false;
  45.         }
  46.         switch ($attribute) {
  47.             case self::ECOHORT_MANAGE:
  48.                 if (in_array('ECOHORT_MANAGE'$permissions)) {
  49.                     return true;
  50.                 }
  51.                 break;
  52.         }
  53.         return false;
  54.     }
  55. }