src/Security/Voter/SortingSessionSaveVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Security\Voter;
  3. use InvalidArgumentException;
  4. use MedBrief\MSR\Entity\SortingSessionSave;
  5. use MedBrief\MSR\Entity\User;
  6. use Override;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
  10. use Symfony\Component\Security\Core\User\UserInterface;
  11. class SortingSessionSaveVoter implements VoterInterface
  12. {
  13. public const RESTORE_SAVE_POINT = 'RESTORE_SAVE_POINT';
  14. public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
  15. {
  16. }
  17. public function supportsAttribute($attribute): bool
  18. {
  19. return $attribute == self::RESTORE_SAVE_POINT;
  20. }
  21. public function supportsClass($class): bool
  22. {
  23. $supportedClass = SortingSessionSave::class;
  24. return $supportedClass === $class || is_subclass_of($class, $supportedClass);
  25. }
  26. /**
  27. *
  28. * @param mixed $entity
  29. */
  30. #[Override]
  31. public function vote(TokenInterface $token, $entity, array $attributes)
  32. {
  33. /**
  34. * START: This is common code for all Voter::vote() methods
  35. */
  36. // check if class of this object is supported by this voter
  37. if (!$this->supportsClass($entity && !is_array($entity) ? $entity::class : '')) {
  38. return VoterInterface::ACCESS_ABSTAIN;
  39. }
  40. // check if the voter is used correct, only allow one attribute
  41. // this isn't a requirement, it's just one easy way for you to
  42. // design your voter
  43. if (1 !== count($attributes)) {
  44. throw new InvalidArgumentException(
  45. 'Only one attribute is allowed for Medbrief Voters.'
  46. );
  47. }
  48. // set the attribute to check against
  49. $attribute = $attributes[0];
  50. // check if the given attribute is covered by this voter
  51. if (!$this->supportsAttribute($attribute)) {
  52. return VoterInterface::ACCESS_ABSTAIN;
  53. }
  54. // get current logged in user
  55. /** @var User $user */
  56. $user = $token->getUser();
  57. // make sure there is a user object (i.e. that the user is logged in)
  58. if (!$user instanceof UserInterface) {
  59. return VoterInterface::ACCESS_DENIED;
  60. }
  61. // SuperAdmin users can do everything
  62. if ($attribute === self::RESTORE_SAVE_POINT && $this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
  63. return VoterInterface::ACCESS_GRANTED;
  64. }
  65. /**
  66. * END: Common code for all Voter:vote() methods. Put custom logic below.
  67. */
  68. // If we get to the end of this function, then no decisions have been
  69. // made so we deny access
  70. return VoterInterface::ACCESS_DENIED;
  71. }
  72. }