src/Security/Voter/StudentVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Job\Student;
  4. use App\Entity\User;
  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. class StudentVoter extends Voter
  9. {
  10.     const READ 'STUDENT_READ';
  11.     const UPDATE 'STUDENT_UPDATE';
  12.     const DELETE 'STUDENT_DELETE';
  13.     private $security;
  14.     /**
  15.      * @param Security $security
  16.      */
  17.     public function __construct(Security $security)
  18.     {
  19.         $this->security $security;
  20.     }
  21.     protected function supports($attribute$subject)
  22.     {
  23.         // if the attribute isn't one we support, return false
  24.         if (!in_array($attribute, [self::READself::UPDATEself::DELETE])) {
  25.             return false;
  26.         }
  27.         // only vote on User objects inside this voter
  28.         if (!$subject instanceof Student) {
  29.             return false;
  30.         }
  31.         return true;
  32.     }
  33.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  34.     {
  35.         $currentUser $token->getUser();
  36.         if (!$currentUser instanceof User) {
  37.             // the user must be logged in; if not, deny access
  38.             return false;
  39.         }
  40.         if ($this->security->isGranted(User::ROLE_ADMIN)) {
  41.             return true;
  42.         }
  43.         switch ($attribute) {
  44.             case self::READ:
  45.                 return $this->canRead($currentUser);
  46.             case self::UPDATE:
  47.                 return $this->canUpdate($currentUser);
  48.             case self::DELETE:
  49.                 return $this->canDelete($currentUser);
  50.         }
  51.         throw new \LogicException('This code should not be reached!');
  52.     }
  53.     private function canRead(User $currentUser)
  54.     {
  55.         if ($this->security->isGranted(User::ROLE_LECTURER)) {
  56.             return true;
  57.         }
  58.         return false;
  59.     }
  60.     private function canUpdate(User $currentUser)
  61.     {
  62.         if ($this->security->isGranted(User::ROLE_LECTURER)) {
  63.             return true;
  64.         }
  65.         return false;
  66.     }
  67.     private function canDelete(User $currentUser)
  68.     {
  69.         return false;
  70.     }
  71. }