<?php
namespace App\Voter\__Accounting;
use App\Entity\Accounting\Invoice;
use App\Voter\VoterTrait;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class AccountingInvoiceVoter extends Voter
{
use VoterTrait;
const LIST = "ACCOUNTING_INVOICE_LIST";
const GET_INVOICE = "ACCOUNTING_INVOICE_GET_INVOICE";
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [
self::LIST,
self::GET_INVOICE,
]) && ($subject === null || $subject instanceof Invoice);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::LIST:
return $this->voteOnList($loggedUser);
case self::GET_INVOICE:
return $this->voteOnGetInvoice($subject, $loggedUser);
}
return false;
}
private function voteOnList(UserInterface $loggedUser): bool
{
return in_array(self::LIST, $loggedUser->getRoles());
}
private function voteOnGetInvoice(?Invoice $invoice, UserInterface $loggedUser): bool
{
if (null === $invoice) {
return false;
}
return in_array(self::GET_INVOICE, $loggedUser->getRoles());
}
}