首页 > 解决方案 > 在 collectionOperations (GET) 上使用 Symfony 投票者

问题描述

我想在 API PLATFORM 中使用 symfony 选民。itempsOperations我在(GET, PUT, DELETE)上使用它时没有任何问题,但是当我在collectionOperations特别是在 GET 中使用它时(POST 效果很好),我无法访问 $subject 因为在 GET 操作 API PLATFORM 返回一个“ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator”的实例,而不是实体对象。

* @ApiResource(
*         collectionOperations={
*              "GET"={
*                   "access_control"="is_granted('GET', object)",
*               },
*               "POST"={
*                   "access_control"="is_granted('ADD', object)",
*                }
*         }
* )

我怎样才能解决这个问题?

标签: phpsymfonyapi-platform.com

解决方案


我遇到了同样的问题,不知道这是功能还是错误。因为我们基本上是在要求一组这样的资源。考虑到这一点,我想分页对象是有意义的。

围绕此问题的解决方案可能如下:


@\Entity\YourEntity.php

* @ApiResource(
*         collectionOperations={
*              "GET"={
*                   "access_control"="is_granted('GET', _api_resource_class)",
*               },
*         }
* )

@\Security\Voter\YourVoter.php
/**
 * Determines if the attribute and subject are supported by this voter.
 *
 * @param string $attribute An attribute
 * @param mixed  $subject   The subject to secure, e.g. an object the user wants to access or any other PHP type
 *
 * @return bool True if the attribute and subject are supported, false otherwise
 */
protected function supports($attribute, $subject)
{


    // If the subject is a string check if class exists to support collectionOperations
    if(is_string($subject) && class_exists($subject)) {
        $subject = new $subject;
    }

    if(in_array($attribute, ['GET'])
        && $subject instanceof YourEntity) {
        return true;
    }

推荐阅读