src/Security/Core/TextbookVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\Security\Core;
  3. use App\Entity\User\User;
  4. use App\Services\Core\TextbookVoterService;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  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. // && $subject instanceof Textbook;
  23. // 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"
  24. // Leaving it here for now to help in debugging potential access issues
  25. }
  26. /**
  27. * @inheritDoc
  28. */
  29. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  30. {
  31. $user = $token->getUser();
  32. if (!$user instanceof User) {
  33. /* The user must be logged in; if not, deny access */
  34. return false;
  35. }
  36. switch ($attribute) {
  37. case self::CAN_STUDENT_ACCESS:
  38. return $this->service->canStudentAccess($user);
  39. case self::CAN_TEACHER_ACCESS:
  40. return $this->service->canTeacherAccess($user);
  41. default:
  42. return false;
  43. }
  44. }
  45. }