<?php
namespace App\Voter;
use App\Entity\Invoice;
use App\Entity\User as UserEntity;
use App\Model\InvoiceFactory;
use App\Model\User\User;
use Exception;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class InvoiceVoter extends Voter
{
public const REMOVE = 'remove';
public const SHOW = 'show';
private $user;
private $invoiceFactory;
public function __construct(User $user, InvoiceFactory $invoiceFactory)
{
$this->user = $user;
$this->invoiceFactory = $invoiceFactory;
}
/**
* @param string $attribute
* @param mixed $subject
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (! in_array($attribute, [
self::REMOVE,
self::SHOW
])) {
return false;
}
// only vote on Supplier objects inside this voter
if (! $subject instanceof Invoice) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $entity
* @return bool|void
* @throws Exception
*/
protected function voteOnAttribute($attribute, $entity, TokenInterface $token): bool
{
$userEntity = $token->getUser();
if (! $userEntity instanceof UserEntity) {
// the user must be logged in; if not, deny access
return false;
}
$this->user->setEntity($userEntity);
$invoice = $this->invoiceFactory->createModel($entity);
switch ($attribute) {
case self::SHOW:
return $this->user->canSeeInvoiceEntity($entity);
case self::REMOVE:
return $invoice->canBeRemovedBy($this->user);
}
return false;
}
}