<?php
namespace MedBrief\MSR\Security\Voter;
use MedBrief\MSR\Entity\LicenceRenewalTerm;
use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class LicenceRenewalTermVoter extends Voter
{
public const EDIT = 'EDIT';
public const DELETE = 'DELETE';
public function __construct(private readonly AuthorizationCheckerInterface $authorizationChecker)
{
}
#[Override]
protected function supports($attribute, $subject): bool
{
return in_array($attribute, [
self::EDIT,
self::DELETE,
])
&& $subject instanceof LicenceRenewalTerm;
}
#[Override]
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
return match ($attribute) {
self::EDIT => $this->canUpdate(),
self::DELETE => $this->canDelete(),
default => false,
};
}
private function canUpdate(): bool
{
// if a user can delete, they can also update
if ($this->canDelete()) {
return true;
}
return $this->authorizationChecker->isGranted('ROLE_ADMIN');
}
private function canDelete(): bool
{
return $this->authorizationChecker->isGranted('ROLE_ADMIN');
}
}