<?php
namespace App\Security\Voter;
use App\Entity\DemandeService;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class DemandeServiceVoter extends Voter
{
public const VIEW = 'DEMANDE_VIEW';
public const EDIT = 'DEMANDE_EDIT';
public const DELETE = 'DEMANDE_DELETE';
protected function supports(string $attribute, mixed $subject): bool
{
if (!$subject instanceof DemandeService) {
return false;
}
return in_array($attribute, [self::VIEW, self::EDIT, self::DELETE], true);
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var DemandeService $demande */
$demande = $subject;
if ($this->isDemandeStaff($user)) {
return true;
}
$owner = $demande->getUser();
return null !== $owner && $owner->getId() === $user->getId();
}
private function isDemandeStaff(User $user): bool
{
$roles = $user->getRoles();
return in_array('ROLE_DAE', $roles, true)
|| in_array('ROLE_CHARGE_ASSISTANCE', $roles, true)
|| in_array('ROLE_AGENT_INTERNE', $roles, true)
|| in_array('ROLE_ADMIN', $roles, true);
}
}