ContactPointVoter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voter;
  4. use App\Entity\Access\Access;
  5. use App\Entity\Core\ContactPoint;
  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. use Symfony\Component\Security\Core\User\UserInterface;
  10. class ContactPointVoter extends Voter
  11. {
  12. public function __construct(private Security $security)
  13. { }
  14. protected function supports($attribute, $subject): bool
  15. {
  16. return in_array($attribute, ['CONTACT_POINT_READ', 'CONTACT_POINT_EDIT', 'CONTACT_POINT_DELETE'])
  17. && $subject instanceof ContactPoint;
  18. }
  19. /**
  20. * @param string $attribute
  21. * @param mixed $subject
  22. * @param TokenInterface $token
  23. * @return bool
  24. */
  25. protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
  26. {
  27. /** @var Access $user */
  28. $user = $token->getUser();
  29. // if the user is anonymous, do not grant access
  30. if (!$user instanceof UserInterface) {
  31. return false;
  32. }
  33. switch ($attribute) {
  34. case 'CONTACT_POINT_READ':
  35. if($subject->getOrganization()->count() === 1){
  36. return $this->security->isGranted('ROLE_ORGANIZATION_VIEW')
  37. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  38. }
  39. break;
  40. case 'CONTACT_POINT_EDIT':
  41. case 'CONTACT_POINT_DELETE':
  42. if($subject->getOrganization()->count() === 1){
  43. return $this->security->isGranted('ROLE_ORGANIZATION')
  44. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  45. }
  46. break;
  47. }
  48. return false;
  49. }
  50. }