src/CoreBundle/Security/TextbookVoter.php line 11

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