src/Security/Voters/Ledger/AccountVoter.php line 15

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security\Voters\Ledger;
  4. use App\Entity\Ledger\Account;
  5. use App\Entity\Ledger\GiftAccount;
  6. use App\Entity\Ledger\MainAccount;
  7. use App\Enums\Operation;
  8. use App\Enums\Roles;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  11. class AccountVoter extends Voter
  12. {
  13.     public function __construct(
  14.         private readonly \Symfony\Bundle\SecurityBundle\Security $security,
  15.     ) {
  16.     }
  17.     private function checkCreate(TokenInterface $tokenAccount $subject): bool
  18.     {
  19.         $currentUser $token->getUser();
  20.         return $subject->getOwner()->getUserIdentifier() === $currentUser->getUserIdentifier();
  21.     }
  22.     private function checkRead(TokenInterface $tokenAccount $subject): bool
  23.     {
  24.         if ($this->security->isGranted(Roles::ROLE_ADMIN)) {
  25.             return true;
  26.         }
  27.         return $token->getUserIdentifier() === $subject->getOwner()->getUserIdentifier();
  28.     }
  29.     private function checkList(): bool
  30.     {
  31.         return $this->security->isGranted(Roles::ROLE_ADMIN);
  32.     }
  33.     protected function supports(string $attributemixed $subject): bool
  34.     {
  35.         return in_array($subject, [Account::class, GiftAccount::class, MainAccount::class])
  36.             && Operation::match($attribute);
  37.     }
  38.     protected function voteOnAttribute(string $attributemixed $subjectTokenInterface $token): bool
  39.     {
  40.         return match (Operation::tryFrom($attribute)) {
  41.             Operation::LIST => $this->checkList(),
  42.             Operation::READ => $this->checkRead($token$subject),
  43.             Operation::CREATE => $this->checkCreate($token$subject),
  44.             default => false,
  45.         };
  46.     }
  47. }