Symfony 选民常量用法

Symfony Voter constant usages

我定义了一个投票器,特别是 voteOnAttribute 方法,如下所示:

 public function voteOnAttribute($attributes, $subject, TokenInterface $token) {

        $user = $token->getUser();

        if (!$user instanceof User) {
            return false;
            // return static::ACCESS_DENIED
        }
        if(!$subject instanceof PrivateResource) {
            throw new Exception('Media type mismatch : private resource expected here');
        }

        // Check company is elligible here
        if(!$subject->getCompanies()->contains($user->getCompany())){
            return false;
            // return static::ACCESS_DENIED
        }

        return static::ACCESS_GRANTED;
    }

为什么我不能在我的方法中使用 VoterInterface 常量(ACCESS_GRANTEDACCESS_ABSTAINACCESS_DENIED)?

如果我这样做,由于摘要中的方法 vote class Voter :

,访问被拒绝的决定不会被强制执行
public function vote(TokenInterface $token, $subject, array $attributes)
    {
        // abstain vote by default in case none of the attributes are supported
        $vote = self::ACCESS_ABSTAIN;

        foreach ($attributes as $attribute) {
            if (!$this->supports($attribute, $subject)) {
                continue;
            }

            // as soon as at least one attribute is supported, default is to deny access
            $vote = self::ACCESS_DENIED;

            if ($this->voteOnAttribute($attribute, $subject, $token)) {
                // grant access as soon as at least one attribute returns a positive response
                return self::ACCESS_GRANTED;
            }
        }

        return $vote;
    }

由于 ACCESS_DENIED 常量在 VoterInterface 中设置为 -1,因此 if ($this->voteOnAttribute($attribute, $subject, $token)) 条件为真,即使 return 为 -1。

我在这里弄错了什么?这些常量是否计划在我们的自定义 voteOnAttribute 方法中使用?

注:我在security.yml

中将选民策略设置为unanimous

首先我以为我误解了文档。

但是 symfony 版本之间的文档有所不同

假设您使用的是 symfony >= 2.7,您应该 return voteOnAttribute

中的布尔值