<?php
namespace App\Security\Voter;
use App\Entity\Gauge\Invoice;
use App\Entity\User;
use App\Repository\Gauge\InvoiceRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class InvoiceVoter extends Voter
{
const EDIT = 'edit';
const DELETE = 'delete';
/**
* @var Security
*/
private Security $security;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::DELETE], true)) {
return false;
}
// only vote on `Invoice` objects
if (!$subject instanceof Invoice) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
/** @var Invoice $targetInvoice */
$targetInvoice = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($targetInvoice);
case self::DELETE:
return $this->canDelete($targetInvoice);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param Invoice $targetInvoice
* @return bool
*/
private function canEdit(Invoice $targetInvoice): bool
{
if (!$this->security->isGranted('view', $targetInvoice->getGauge())) {
return false;
}
if ($this->security->isGranted('ROLE_CAN_EDIT_ALL_INVOICES')) {
return true;
}
if ($this->isLast($targetInvoice) && $this->security->isGranted('ROLE_CAN_EDIT_LAST_INVOICES')) {
return true;
}
return false;
}
/**
* @param Invoice $targetInvoice
* @return bool
*/
private function canDelete(Invoice $targetInvoice): bool
{
if (!$this->security->isGranted('view', $targetInvoice->getGauge())) {
return false;
}
if ($this->security->isGranted('ROLE_CAN_DELETE_ALL_INVOICES')) {
return true;
}
if ($this->isLast($targetInvoice) && $this->security->isGranted('ROLE_CAN_DELETE_LAST_INVOICES')) {
return true;
}
return false;
}
/**
* @param Invoice $targetInvoice
* @return bool
*/
private function isLast(Invoice $targetInvoice): bool
{
/** @var InvoiceRepository $iRepository */
$iRepository = $this->entityManager->getRepository(Invoice::class);
$lastInv = $iRepository->getLastForGauge($targetInvoice->getGauge());
if ($lastInv !== null && $lastInv->getId() === $targetInvoice->getId()) {
return true;
}
return false;
}
}