<?php
namespace App\Security;
use App\Entity\User;
use App\Entity\HabilitationProfile;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class HabilitationVoter extends Voter
{
// Tous les codes habilitation connus
public const CODES = [
'VOIR_DASHBOARD',
'SAISIR_VENTE',
'SAISIR_FOURNITURE',
'SAISIR_DEPENSE',
'GERER_PRODUITS',
'GERER_CATEGORIES',
'GERER_FOURNISSEURS',
'GERER_CLIENTS',
'GERER_CAISSE',
'GERER_STOCK',
'VOIR_ALERTES_STOCK',
'VOIR_REPORTING',
'GERER_UTILISATEURS',
'GERER_PROFILS',
'GERER_HABILITATIONS',
];
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, self::CODES, true);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
// ROLE_ADMIN bypasse toutes les vérifications
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
$profile = $user->getProfile();
if (!$profile || !$profile->isActif()) {
return false;
}
foreach ($profile->getHabilitationProfiles() as $hp) {
if (
$hp->isStatus()
&& $hp->getHabilitation() !== null
&& $hp->getHabilitation()->getCode() === $attribute
&& $hp->getHabilitation()->isStatut()
) {
return true;
}
}
return false;
}
}