src/Security/Voter/ExpertReportRequestVoter.php line 13

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\Security\Voter;
  3. use InvalidArgumentException;
  4. use MedBrief\MSR\Entity\ExpertReportRequest;
  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 ExpertReportRequestVoter 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 const ADMINISTRATION = 'ADMINISTRATION';
  17. public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
  18. {
  19. }
  20. public function supportsAttribute($attribute): bool
  21. {
  22. return in_array($attribute, [
  23. self::CREATE,
  24. self::READ,
  25. self::UPDATE,
  26. self::DELETE,
  27. self::ADMINISTRATION,
  28. ]);
  29. }
  30. public function supportsClass($class): bool
  31. {
  32. $supportedClass = ExpertReportRequest::class;
  33. return $supportedClass === $class || is_subclass_of($class, $supportedClass);
  34. }
  35. #[Override]
  36. public function vote(TokenInterface $token, $entity, array $attributes)
  37. {
  38. if (!$this->supportsClass($entity && !is_array($entity) ? $entity::class : '')) {
  39. return VoterInterface::ACCESS_ABSTAIN;
  40. }
  41. if (1 !== count($attributes)) {
  42. throw new InvalidArgumentException(
  43. 'Only one attribute is allowed for Medbrief Voters.'
  44. );
  45. }
  46. $attribute = $attributes[0];
  47. if (!$this->supportsAttribute($attribute)) {
  48. return VoterInterface::ACCESS_ABSTAIN;
  49. }
  50. $user = $token->getUser();
  51. if (!$user instanceof UserInterface) {
  52. return VoterInterface::ACCESS_DENIED;
  53. }
  54. // Admin users can do everything
  55. if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  56. return VoterInterface::ACCESS_GRANTED;
  57. }
  58. // Grab Project this ExpertReportRequestRequest belongs to
  59. $project = $entity->getProject();
  60. // If you can READ the project, you can read the ExpertReportRequestRequest
  61. if ($attribute === self::READ && $this->authorizationChecker->isGranted('READ', $project)) {
  62. return VoterInterface::ACCESS_GRANTED;
  63. }
  64. return VoterInterface::ACCESS_DENIED;
  65. }
  66. }