<?php
namespace App\Security\Voter;
use App\Entity\AbstractCollaborator;
use App\Entity\Reference\ReferenceTransactionStatus;
use App\Entity\Transaction;
use Exception;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class TransactionVoter extends Voter
{
public const PUT = 'PUT';
public const TRANSACTION_STATUS_ALLOWED_TO_PUT = [
ReferenceTransactionStatus::REFERENCE_CODE_TRANSACTION_STATUS_PAID,
ReferenceTransactionStatus::REFERENCE_CODE_TRANSACTION_STATUS_UNDER_COMPROMISE
];
/**
* @var Security
*/
private Security $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === self::PUT && $subject instanceof Transaction;
}
/**
* @throws Exception
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var UserInterface $user */
$user = $token->getUser();
// Deny anonymous users
if (!$user instanceof UserInterface) {
return false;
}
/** @var Transaction $subject */
if ($attribute === self::PUT) {
return (($subject->getOutputAgent() === $user)
&& in_array($subject->getReferenceTransactionStatus()->getCode(), self::TRANSACTION_STATUS_ALLOWED_TO_PUT, true))
|| $this->security->isGranted(
AbstractCollaborator::ROLE_MANAGER
);
}
throw new Exception(sprintf('Unhandled attribute "%s"', $attribute));
}
}