src/Security/Voter/RecordsRequestCentreChildVoter.php line 13

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