src/CoreBundle/Security/TextbookVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace CoreBundle\Security;
  3. use CoreBundle\Service\TextbookVoterService;
  4. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  5. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  6. use UserBundle\Entity\User;
  7. class TextbookVoter extends Voter
  8. {
  9. const CAN_STUDENT_ACCESS = 'canStudentAccess';
  10. const CAN_TEACHER_ACCESS = 'canTeacherAccess';
  11. private $service;
  12. public function __construct(TextbookVoterService $service)
  13. {
  14. $this->service = $service;
  15. }
  16. /**
  17. * @inheritDoc
  18. */
  19. protected function supports($attribute, $subject): bool
  20. {
  21. return in_array($attribute, [self::CAN_STUDENT_ACCESS, self::CAN_TEACHER_ACCESS]);
  22. }
  23. /**
  24. * @inheritDoc
  25. */
  26. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  27. {
  28. $user = $token->getUser();
  29. if (!$user instanceof User) {
  30. /* The user must be logged in; if not, deny access */
  31. return false;
  32. }
  33. switch ($attribute) {
  34. case self::CAN_STUDENT_ACCESS:
  35. return $this->service->canStudentAccess($user);
  36. case self::CAN_TEACHER_ACCESS:
  37. return $this->service->canTeacherAccess($user);
  38. default:
  39. return false;
  40. }
  41. }
  42. }