src/Security/Voter/Customer/AbsenceVoter.php line 13
<?php
namespace App\Security\Voter\Customer;
use App\Entity\Customer\Absence;
use App\Entity\Admin\CustomerUser;
use App\Repository\Customer\AbsenceTypeRepository;
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 AbsenceVoter extends Voter
{
final public const EDIT = 'ABSENCE_ENTITY_EDIT';
final public const VIEW = 'ABSENCE_ENTITY_VIEW';
final public const DELETE = 'ABSENCE_ENTITY_DELETE';
public function __construct(
private readonly Security $security,
private readonly AbsenceTypeRepository $absenceTypeRepository)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
if(!in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])){
return false;
}
if (!$subject instanceof Absence) {
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;
}
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(Absence $entity, CustomerUser $user): bool
{
if ($this->canEdit($entity)) {
return true;
}
if ($entity->getStaff()->getId() == $user->getStaff()) {
return true;
}
return false;
}
private function canEdit(?Absence $entity): bool
{
$settings = $this->absenceTypeRepository->findById($entity->getAbsenceType()->getId());
if ($settings->isCreateStaff() and $entity->getStaff() == null) {
return true;
}
return $this->security->isGranted('ROLE_ADMIN');
}
private function canDelete(): bool
{
return $this->security->isGranted('ROLE_ADMIN');
}
}