src/Security/Voter/LicenceRenewalTermVoter.php line 12

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Security\Voter;
  3. use MedBrief\MSR\Entity\LicenceRenewalTerm;
  4. use Override;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class LicenceRenewalTermVoter extends Voter
  10. {
  11. public const EDIT = 'EDIT';
  12. public const DELETE = 'DELETE';
  13. public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
  14. {
  15. }
  16. #[Override]
  17. protected function supports($attribute, $subject): bool
  18. {
  19. return in_array($attribute, [
  20. self::EDIT,
  21. self::DELETE,
  22. ])
  23. && $subject instanceof LicenceRenewalTerm;
  24. }
  25. #[Override]
  26. protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
  27. {
  28. $user = $token->getUser();
  29. // if the user is anonymous, do not grant access
  30. if (!$user instanceof UserInterface) {
  31. return false;
  32. }
  33. // ... (check conditions and return true to grant permission) ...
  34. return match ($attribute) {
  35. self::EDIT => $this->canUpdate(),
  36. self::DELETE => $this->canDelete(),
  37. default => false,
  38. };
  39. }
  40. private function canUpdate(): bool
  41. {
  42. // if a user can delete, they can also update
  43. if ($this->canDelete()) {
  44. return true;
  45. }
  46. return $this->authorizationChecker->isGranted('ROLE_ADMIN');
  47. }
  48. private function canDelete(): bool
  49. {
  50. return $this->authorizationChecker->isGranted('ROLE_ADMIN');
  51. }
  52. }