src/Security/Voter/QuestionaryAttemptVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\QuestionaryAttempt;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class QuestionaryAttemptVoter extends Voter
  8. {
  9.     const CAN_VIEW 'can_view';
  10.     const CAN_VOTE 'can_vote';
  11.     protected function supports($attribute$subject)
  12.     {
  13.         return
  14.             in_array($attribute, [
  15.                 self::CAN_VIEW,
  16.                 self::CAN_VOTE,
  17.             ])
  18.             && $subject instanceof QuestionaryAttempt
  19.         ;
  20.     }
  21.     /**
  22.      * @param string $attribute
  23.      * @param QuestionaryAttempt $subject
  24.      * @param TokenInterface $token
  25.      *
  26.      * @return bool
  27.      */
  28.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  29.     {
  30.         /** @var User $user */
  31.         $user $token->getUser();
  32.         switch ($attribute) {
  33.             case self::CAN_VIEW:
  34.                 return
  35.                     $user == $subject->getStudent()
  36.                     && (
  37.                         !$subject->getQuestionary()
  38.                         || $subject->getQuestionary()
  39.                         && $subject->getQuestionary()->isActive()
  40.                     )
  41.                     && (
  42.                         !$subject->getAvailableAt()
  43.                         || $subject->getAvailableAt() < new \DateTime()
  44.                     )
  45.                 ;
  46.             case self::CAN_VOTE:
  47.                 return $this->voteOnAttribute(self::CAN_VIEW$subject$token)
  48.                     && !$subject->getIsDone()
  49.                 ;
  50.             default:
  51.                 return false;
  52.         }
  53.     }
  54. }