<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Entity\Transaction;
use App\Entity\User;
class TransactionVoter extends Voter
{
public const EDIT = 'TRANSACTION_EDIT';
public const VIEW = 'TRANSACTION_VIEW';
public const REPAIR = 'TRANSACTION_REPAIR';
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW, self::REPAIR]) && $subject instanceof Transaction;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// you know $subject is a Transaction object, thanks to `supports()`
/** @var Transaction $post */
$transaction = $subject;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::EDIT:
case self::REPAIR:
return $this->canEdit($transaction, $user);
case self::VIEW:
return $this->canEdit($transaction, $user);
break;
}
return false;
}
private function canEdit(Transaction $transaction, User $user): bool
{
return $user === $transaction->getUser();
}
}