Mise à jour, Mai 2025
Cela deviendra une fonction native à partir de Symfony 7.3 avec isGrantedForUser voir https://symfony.com/blog/new-in-symfony-7-3-arbitrary-user-permission-checks
Dans les version antérieures :
Exemple rapide
namespace App\Security\Voter
;
use App\Entity\User
;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface
;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface
;
class UserVoter
extends Voter
{
public const EDIT
= 'USER_EDIT';
public function __construct
(private RoleHierarchyInterface
$roleHierarchy) {
}
protected function supports
(string
$attribute, $subject): bool
{
return \
in_array($attribute, [self::EDIT, self::TRANSFER, self::DELETE, self::SEE_NDE]) &
;&
; $subject instanceof User
;
}
protected function voteOnAttribute
(string
$attribute, $subject, TokenInterface
$token): bool
{
/** @var User $user */
$user = $token->
;getUser
();
//
$subjectRoles = $this->
;roleHierarchy
->
;getReachableRoleNames
($subject->
;getRoles
());
$userRoles = $this->
;roleHierarchy
->
;getReachableRoleNames
($user->
;getRoles
());
//je ne peux pas modifier un utilisateur ayant plus de rôles que moi
if(count($subjectRoles) >
; count($userRoles)) {
return false;
}
return true;
}
}