src/CoreBundle/Security/QuizVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace CoreBundle\Security;
  3. use AdminBundle\Service\EasyAdminService;
  4. use CoreBundle\Entity\Quiz;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class QuizVoter extends Voter
  10. {
  11. const PERMISSION = 'quizEntityPermission';
  12. const INDEX_ACTION = 'quizIndexAction';
  13. const NEW_ACTION = 'quizNewAction';
  14. const EDIT_ACTION = 'quizEditAction';
  15. const DELETE_ACTION = 'quizDeleteAction';
  16. private Security $security;
  17. private EasyAdminService $easyAdminService;
  18. private RequestStack $requestStack;
  19. public function __construct(Security $security, EasyAdminService $easyAdminService, RequestStack $requestStack)
  20. {
  21. $this->security = $security;
  22. $this->easyAdminService = $easyAdminService;
  23. $this->requestStack = $requestStack;
  24. }
  25. protected function supports(string $attribute, $subject): bool
  26. {
  27. // For index and new, $subject will always be null. For permission, it will be null when trying to create a new entity.
  28. if (in_array($attribute, [self::INDEX_ACTION, self::NEW_ACTION, self::PERMISSION])) {
  29. return true;
  30. }
  31. if (in_array($attribute, [self::EDIT_ACTION, self::DELETE_ACTION])) {
  32. return $subject instanceof Quiz;
  33. }
  34. return false;
  35. }
  36. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  37. {
  38. if ($attribute === self::INDEX_ACTION) {
  39. // Allow everyone to list - the entity permissions will still apply and hide entities you are not allowed
  40. // to access.
  41. return true;
  42. }
  43. if ($attribute === self::NEW_ACTION || $attribute === self::PERMISSION && $subject === null) {
  44. // Anyone with cms access should be able to create new quizzes
  45. return true;
  46. }
  47. if (!$subject instanceof Quiz) {
  48. throw new \LogicException("Invalid type for voter and attribute.");
  49. }
  50. return $this->checkEntityPermissions($subject);
  51. }
  52. public function checkEntityPermissions(Quiz $subject): bool
  53. {
  54. // ROLE_SUPER_ADMIN inherits ROLE_ADMIN, and will also be included here.
  55. if ($this->security->isGranted('ROLE_ADMIN')) {
  56. return true;
  57. }
  58. $publication = $subject->getPublication();
  59. if ($publication === null) {
  60. try {
  61. // When creating a new quiz in QuizFromPublicationCrudController
  62. $publication = $this->easyAdminService->getPublication($this->requestStack->getCurrentRequest());
  63. } catch (\Exception) {}
  64. }
  65. if ($publication !== null) {
  66. return $this->easyAdminService->userCanAccessPublication($publication);
  67. }
  68. return false;
  69. }
  70. }