src/Security/Voters/Ledger/AccountVoter.php line 15
<?php
declare(strict_types=1);
namespace App\Security\Voters\Ledger;
use App\Entity\Ledger\Account;
use App\Entity\Ledger\GiftAccount;
use App\Entity\Ledger\MainAccount;
use App\Enums\Operation;
use App\Enums\Roles;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AccountVoter extends Voter
{
public function __construct(
private readonly \Symfony\Bundle\SecurityBundle\Security $security,
) {
}
private function checkCreate(TokenInterface $token, Account $subject): bool
{
$currentUser = $token->getUser();
return $subject->getOwner()->getUserIdentifier() === $currentUser->getUserIdentifier();
}
private function checkRead(TokenInterface $token, Account $subject): bool
{
if ($this->security->isGranted(Roles::ROLE_ADMIN)) {
return true;
}
return $token->getUserIdentifier() === $subject->getOwner()->getUserIdentifier();
}
private function checkList(): bool
{
return $this->security->isGranted(Roles::ROLE_ADMIN);
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($subject, [Account::class, GiftAccount::class, MainAccount::class])
&& Operation::match($attribute);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
return match (Operation::tryFrom($attribute)) {
Operation::LIST => $this->checkList(),
Operation::READ => $this->checkRead($token, $subject),
Operation::CREATE => $this->checkCreate($token, $subject),
default => false,
};
}
}