BankAccountVoter.php 1.8 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\BankAccount;
  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 BankAccountVoter extends Voter
  11. {
  12. public function __construct(private Security $security)
  13. { }
  14. protected function supports($attribute, $subject): bool
  15. {
  16. return in_array($attribute, ['BANK_ACCOUNT_READ', 'BANK_ACCOUNT_EDIT'])
  17. && $subject instanceof BankAccount;
  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 'BANK_ACCOUNT_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 'BANK_ACCOUNT_EDIT':
  41. if($subject->getOrganization()->count() === 1){
  42. return $this->security->isGranted('ROLE_ORGANIZATION')
  43. && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
  44. }
  45. break;
  46. }
  47. return false;
  48. }
  49. }