Роль проверки избирателей Symfony 4 в html.twig
Я создал настраиваемого избирателя по имени CustomVoter. Я хочу проверить роль пользователя в html.twig, и если у него есть роль, я хочу что-то сделать. Мой зарегистрированный пользователь имеет роль CAN_REMOVE, указанную в CustomVoter. К сожалению, он не работает или не видит избирателя в 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;
}
}