Symfony 4.2.2渲染导航栏时TraceableVoter构造函数报TypeError
解决Symfony 4.2.2中TraceableVoter触发的VoteEvent TypeError问题
从错误堆栈和你提供的信息来看,问题的核心是你自定义的ExampleVoter类的投票方法返回了null,而非Symfony要求的整数投票结果。
Symfony的VoteEvent构造函数第4个参数必须是整数(对应VoterInterface定义的三个常量:ACCESS_GRANTED、ACCESS_DENIED、ACCESS_ABSTAIN),但你的ExampleVoter返回了null,导致TraceableVoter在调用VoteEvent时传入非法值,触发了TypeError。
具体修复步骤:
- 定位你的
ExampleVoter类(通常位于src/Security/Voter/目录下) - 检查
voteOnAttribute方法(如果是直接重写基类的vote方法则检查该方法),确保它始终返回以下三个常量之一:\Symfony\Component\Security\Core\Authorization\Voter\VoterInterface::ACCESS_GRANTED(代表允许访问)\Symfony\Component\Security\Core\Authorization\Voter\VoterInterface::ACCESS_DENIED(代表拒绝访问)\Symfony\Component\Security\Core\Authorization\Voter\VoterInterface::ACCESS_ABSTAIN(代表该投票器不处理当前请求,交给其他投票器判断)
错误示例(返回null或无返回值):
protected function voteOnAttribute($attribute, $subject, TokenInterface $token) { $user = $token->getUser(); if (!$user instanceof User) { // 此处漏写返回值,默认返回null } // 其他权限判断逻辑... }
修复后的示例:
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use App\Entity\User; protected function voteOnAttribute($attribute, $subject, TokenInterface $token) { $user = $token->getUser(); if (!$user instanceof User) { // 用户未登录,根据需求返回ABSTAIN或DENIED return VoterInterface::ACCESS_ABSTAIN; } // 你的权限判断逻辑 if ('ROLE_USER' === $attribute) { return VoterInterface::ACCESS_GRANTED; } // 若当前投票器不处理该属性,返回ABSTAIN return VoterInterface::ACCESS_ABSTAIN; }
- 保存修改后,清除Symfony缓存(开发环境执行
php bin/console cache:clear),重新访问首页即可。
额外确认项:
- 确保
ExampleVoter正确继承了Symfony\Component\Security\Core\Authorization\Voter\Voter - 确认Symfony自动注册了该投票器服务(Symfony 4默认会自动注册
src/目录下的所有类为服务,除非你手动修改了服务配置)
内容的提问来源于stack exchange,提问作者user10640506
相关产品推荐
相关产品推荐

