我创建了一个名为 CustomVoter 的自定义选民。我想检查 html.twig 中的用户角色,如果它有角色我想做点什么。我的登录用户具有 CustomVoter 中指示的“CAN_REMOVE”角色。不幸的是,它不起作用或无法在 html.twig 中看到选民。问题是什么?
{% if (is_granted(constant('App\\Security\\Voter\\CustomVoter::CAN_REMOVE'))) %}
// do something
{% endif %}
<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class CustomVoter extends Voter
{
const CAN_REMOVE = 'CAN_REMOVE';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute, [self::CAN_REMOVE])) {
return false;
}
if (!$subject instanceof User) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param User $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::CAN_REMOVE:
return !empty(array_intersect([UserVoter::ROLE_SUPER_ADMIN, self::CAN_REMOVE], $user->getRoles()));
break;
}
return false;
}
}