src/Security/Voter/Customer/IllnessVoter.php line 14
<?php
namespace App\Security\Voter\Customer;
use App\Entity\Customer\Illness;
use App\Entity\Admin\CustomerUser;
use App\Repository\Customer\SettingsRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\SecurityBundle\Security;
class IllnessVoter extends Voter
{
final public const EDIT = 'ILLNESS_ENTITY_EDIT';
final public const VIEW = 'ILLNESS_ENTITY_VIEW';
final public const DELETE = 'ILLNESS_ENTITY_DELETE';
public function __construct(
private readonly Security $security, private readonly SettingsRepository $settingsRepository)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
if(!in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])){
return false;
}
if (!$subject instanceof Illness) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
if (!$this->security->isGranted('ROLE_STAFF')){
return false;
}
// ... (check conditions and return true to grant permission) ...
return match($attribute) {
self::VIEW => $this->canView($subject, $user),
self::EDIT => $this->canEdit($subject),
self::DELETE => $this->canDelete(),
default => throw new \LogicException('This code should not be reached!')
};
}
private function canView(Illness $entity, CustomerUser $user): bool
{
if ($this->canEdit($entity)) {
return true;
}
if ($entity->getStaff()->getId() == $user->getStaff()) {
return true;
}
return false;
}
private function canEdit(?Illness $entity): bool
{
if ($entity == null){
return true;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
$settings = $this->settingsRepository->getByKey("staff_illness_application");
if ($settings->getMetaValueString() == "1" and $entity->getStaff() == null) {
return true;
}
return false;
}
private function canDelete(): bool
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
return false;
}
}