0

我正在使用 ApiPlatform 制作 CheeseListing RESTful API。

我为我的 CheeseListing 对象做了一个投票者:

class CheeseListingVoter extends Voter
{

...

protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    // if the user is anonymous, do not grant access
    if (!$user instanceof UserInterface) {
    return false;
}

/** $var CheeseListing $subject */

// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
    case 'EDIT':
        if($subject->getOwner() === $user){
            return true;
        }
...

为什么当是一个对象并且是一个Iri“/api/users/1”$subject->getOwner() === $user时会返回true$token->getUser()$subject->getOwner()

4

2 回答 2

0

答案:即使 ApiResource 的/api/CheeseListing/Get Endpoint 返回用户的 Iri :比如

{
    "title": "..."
    "owner": "/api/users/1"
}

Owner 字段实际上是一个对象。ApiResource 有它自己的功能,可以将 Iri 转换为对象,反之亦然。

发布时同样适用/api/CheeseListing,您会得到以下信息:

{
    "title": "..."
    "owner": "/api/users/1"
}

它实际上转换"/api/users/1"为用户对象

于 2021-01-07T09:13:19.303 回答
-1

不要使用 if() 并尝试使用 id,因为在您的实体用户中,我认为您没有 getOwner()。尝试这个 :

switch ($attribute) {
    case 'EDIT':
        return $subject->getId() === $user->getId()
于 2021-01-06T16:24:50.253 回答