Symfony 4 选民 - OnetoMany 关系

Symfony 4 voters - OnetoMany relation

我有一个存储广告 ID 和用户 ID 的应用程序实体

class User implements UserInterface, \Serializable
{
 /**
 * @ORM\OneToMany(targetEntity="App\Entity\Application", mappedBy="author", orphanRemoval=true)
 */
 private $applications;
 }

应用实体

class Application
{

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Advert", inversedBy="applications")
 * @ORM\JoinColumn(nullable=false)
 */
private $advert;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="applications")
 * @ORM\JoinColumn(nullable=false)
 */
private $author;
}

我想要的是如果当前用户已经申请了特定广告(查看广告时)可以拒绝操作的选民 迄今为止 在选民中尝试

class AdvertApplicationsVoter 扩展了 Voter {

protected function supports($attribute, $subject)
{
    return in_array($attribute, ['APP_APPLY', 'ADVERT_APPLY'])  && $subject instanceof Application;
}

/**
 * @param string $attribute
 * @param mixed $subject
 * @param TokenInterface $token
 * @return bool
 */
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    $apl = $user->getApplications();
    // if the user is anonymous, do not grant access
    if (!$user instanceof User) {
        return false;
    }

    switch ($attribute) {
        case 'APP_APPLY':
            return $this->dw($user, $subject);
            break;
        case 'ADVERT_APPLY':
            // logic to determine if the user can VIEW
            // return true or false
            break;
    }

    return false;
}

private function applied(?User $user, Advert $app)
{
    return $user->getId() === $app->getApplications()->getKeys();
}
private function aa(?User $user, Application $app)
{
    return $user->getApplications() === $app->getAdvert();
}

private function dw(?User $user, Application $app)
{
    foreach($user->getApplications() as $app) {
        if ($app->getAdvert() === $app) {
            return false;
        }
    }
    return true;
 }
}

我正在获得访问权限,我不知道如何调试选民

提前致谢

假设您正确设置了投票器(因此使用 supportsvoteOnAttribute 方法)。

那么你只需要改变你的方法:

private function dw(?User $user, Advert $advert)
{
    foreach($user->getApplications() as $userApplication) {
        if ($userApplication->getAdvert() === $advert) {
            return false;
        }
    }
    return true;
 }
}

您的方法的问题在于您正在比较 ArrayCollection 应用程序对象