<?php
namespace App\Security\ECommerce;
use App\Entity\ECommerce\Invoice;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class CartArchiveVoter
*
* @package MDL\ECommerceBundle\Security
*/
class InvoiceVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'INVOICE_VIEW';
const PRINT = 'INVOICE_PRINT';
const EDIT = 'INVOICE_EDIT';
const DELETE = 'INVOICE_DELETE';
/**
* CartVoter constructor.
*/
public function __construct(private readonly AccessDecisionManagerInterface $decisionManager)
{
}
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [
self::VIEW,
self::PRINT,
self::EDIT,
self::DELETE,
])) {
return false;
}
// only vote on Cart objects inside this voter
return $subject instanceof Invoice;
}
/**
* @param string $attribute
* @param Invoice $invoice
*
* @return bool
*/
protected function voteOnAttribute($attribute, $invoice, TokenInterface $token)
{
if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
return true;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute) {
self::VIEW => $this->canView($invoice, $user),
self::PRINT => $this->canPrint($invoice, $user),
self::EDIT => $this->canEdit(),
self::DELETE => $this->canDelete(),
default => throw new \LogicException('This code should not be reached!'),
};
}
private function canView(Invoice $invoice, UserInterface $user): bool
{
return $invoice->getCart()->getUser() === $user;
}
private function canPrint(Invoice $invoice, UserInterface $user): bool
{
return $invoice->getCart()->getUser() === $user;
}
private function canEdit(): bool
{
return false;
}
private function canDelete(): bool
{
return false;
}
}