自定义数据提供程序上的ApiFilter搜索不起作用

时间:2019-01-09 04:05:55

标签: php api symfony api-platform.com

在我的实体上有注释

/**
 * @ApiResource()
 * @ApiFilter(SearchFilter::class, properties={"city"})
 * @ApiFilter(BooleanFilter::class, properties={"isFeatured"})
 * @ApiFilter(NumericFilter::class, properties={"projectId": "exact"})
 */

创建的自定义数据提供程序

  app.data_provider.project_data_provider:
    autoconfigure: false
    class: 'AppBundle\DataProvider\ProjectDataProvider'
    arguments:
      - '@doctrine'
      - '@request_stack'
      - !tagged 'api_platform.doctrine.orm.query_extension.collection'
    tags:
      - { name: 'api_platform.collection_data_provider', priority: 1 }
      - { name: 'api_platform.item_data_provider', priority: 2 }

我在https://api-platform.com/docs/core/data-providers/#injecting-extensions-pagination-filter-eagerloading-etc

处关注了文档

除这些过滤器外,所有其他功能都可以使用。

我已经尝试创建自定义过滤器,但这也没有帮助我获得所需的结果。

编辑

这是请求对象

Request {#9
  +attributes: ParameterBag {#12
    #parameters: array:8 [
      "_controller" => "api_platform.action.get_collection"
      "_format" => null
      "_api_resource_class" => "AppBundle\Entity\Project"
      "_api_collection_operation_name" => "get"
      "_route" => "api_projects_get_collection"
      "_route_params" => array:3 [
        "_format" => null
        "_api_resource_class" => "AppBundle\Entity\Project"
        "_api_collection_operation_name" => "get"
      ]
      "_firewall_context" => "security.firewall.map.context.api"
      "_api_normalization_context" => array:6 [
        "groups" => array:2 [
          0 => "user"
          1 => "user-read"
        ]
        "collection_operation_name" => "get"
        "operation_type" => "collection"
        "resource_class" => "AppBundle\Entity\Project"
        "request_uri" => "/api/projects?city=bekasi"
        "uri" => "http://local.net/api/projects?city=bekasi"
      ]
    ]
  }
  +request: ParameterBag {#10
    #parameters: []
  }
  +query: ParameterBag {#11
    #parameters: array:1 [
      "city" => "bekasi"
    ]
  }
  +server: ServerBag {#15
    #parameters: array:38 [
      "REDIRECT_HTTP_AUTHORIZATION" => "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.ey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1KrhN5f1KIqrSmZ_kR0O9Kdvs-Feol-y0f7jNSR-kDEXRh6s8lIY9Ahl9J7I5yv8wZDqPNbGtV-rkFenMtJ-MkvViPfBwYGYILUyZOOametTsup9KMGIgI7ciUh4bTKVrNEGbJk5t6JAlfhunbJ3bDeRD81Zk4dSJRBLv0xPWECxbEr6JNsZbAy_8Mkf_lSPziYfOIBcP97GlMNt6V9hhjkdRodNtxee735-N00BamcqsWnAN_o8u5w5MUzoRyAO4FcMrswqjnLHBwHvQLJ0U1Ys7kXaKF2gyReLOEPQumF8veAUfn4Qs8gum9CbHog0MFIo0HlMYlvOL_vU3QGCdKkD8h7Vkj2WEKAZ2Z9GYm5xpXocEXFNFjZJeJ9gqPkq7FoUjaP7BHUABFN9t1eCA8M5ZIqtJLNRyPI646dIzPSdx5pVT7uCl-n_PdpkhMT_-AVFesSfl9YOgb39FEEhu3k_z-3nkgdEBuPWB3aKxtT4ILwrysd-_f7MBp_k5HJ5yJ2mnl2ucSOPjdlHs0RXD5rPSxoJQk7IdYirgC5e_ZN_W69QEzqHf-r4Zs0c0EiJS79mWRP9aMBBwbrHv93MoH9ysNDktYEtblV_SmKdlmK413iut1462PXRPpjRkIcZ5tYYPL0"
      "HTTP_ACCEPT" => "application/json"
      "HTTP_CACHE_CONTROL" => "no-cache"
      "HTTP_POSTMAN_TOKEN" => "5cce7f80-dc5f-4e5d-a0a1-273c8d4209b6"
      "HTTP_USER_AGENT" => "PostmanRuntime/7.4.0"
      "HTTP_HOST" => "local.net"
      "HTTP_ACCEPT_ENCODING" => "gzip, deflate"
      "HTTP_REFERER" => "http://local.net/app_dev.php/api/projects?city=bekasi"
      "HTTP_CONNECTION" => "keep-alive"
      "PATH" => "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
      "SERVER_SIGNATURE" => "<address>Apache/2.4.25 (Debian) Server at local.net Port 80</address>\n"
      "SERVER_SOFTWARE" => "Apache/2.4.25 (Debian)"
      "SERVER_NAME" => "local.net"
      "SERVER_ADDR" => "172.18.0.4"
      "SERVER_PORT" => "80"
      "REMOTE_ADDR" => "172.18.0.1"
      "DOCUMENT_ROOT" => "/var/www/someapi/web"
      "REQUEST_SCHEME" => "http"
      "CONTEXT_PREFIX" => ""
      "CONTEXT_DOCUMENT_ROOT" => "/var/www/someapi/web"
      "SERVER_ADMIN" => "[no address given]"
      "SCRIPT_FILENAME" => "/var/www/someapi/web/app_dev.php"
      "REMOTE_PORT" => "57620"
      "REDIRECT_URL" => "/api/projects"
      "REDIRECT_QUERY_STRING" => "city=bekasi"
      "GATEWAY_INTERFACE" => "CGI/1.1"
      "SERVER_PROTOCOL" => "HTTP/1.1"
      "REQUEST_METHOD" => "GET"
      "QUERY_STRING" => "city=bekasi"
      "REQUEST_URI" => "/api/projects?city=bekasi"
      "SCRIPT_NAME" => "/app_dev.php"
      "PHP_SELF" => "/app_dev.php"
      "REQUEST_TIME_FLOAT" => 1547089326.338
      "REQUEST_TIME" => 1547089326
      "argv" => array:1 [
        0 => "city=bekasi"
      ]
      "argc" => 1
    ]
  }
  +files: FileBag {#14
    #parameters: []
  }
  +cookies: ParameterBag {#13
    #parameters: []
  }
  +headers: HeaderBag {#16
    #headers: array:10 [
      "authorization" => array:1 [
        0 => "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE1NDcwMTI4MjcsImV4cCI6MTYxMDEyNjczMSwicm9sZXMiOlsiUk9MRV9BRE1JTiIsIlJPTEVfVVNFUiJdLCJ1c2VybmFtZSI6Iis2MzkyMTU4MjkwMzAifQ.k5bVAn0jvyDg1t53EDC686EI5vnZKghvJwAI1KrhN5f1KIqrSmZ_kR0O9Kdvs-Feol-y0f7jNSR-kDEXRh6s8lIY9Ahl9J7I5yv8wZDqPNbGtV-rkFenMtJ-MkvViPfBwYGYILUyZOOametTsup9KMGIgI7ciUh4bTKVrNEGbJk5t6JAlfhunbJ3bDeRD81Zk4dSJRBLv0xPWECxbEr6JNsZbAy_8Mkf_lSPziYfOIBcP97GlMNt6V9hhjkdRodNtxee735-N00BamcqsWnAN_o8u5w5MUzoRyAO4FcMrswqjnLHBwHvQLJ0U1Ys7kXaKF2gyReLOEPQumF8veAUfn4Qs8gum9CbHog0MFIo0HlMYlvOL_vU3QGCdKkD8h7Vkj2WEKAZ2Z9GYm5xpXocEXFNFjZJeJ9gqPkq7FoUjaP7BHUABFN9t1eCA8M5ZIqtJLNRyPI646dIzPSdx5pVT7uCl-n_PdpkhMT_-AVFesSfl9YOgb39FEEhu3k_z-3nkgdEBuPWB3aKxtT4ILwrysd-_f7MBp_k5HJ5yJ2mnl2ucSOPjdlHs0RXD5rPSxoJQk7IdYirgC5e_ZN_W69QEzqHf-r4Zs0c0EiJS79mWRP9aMBBwbrHv93MoH9ysNDktYEtblV_SmKdlmK413iut1462PXRPpjRkIcZ5tYYPL0"
      ]
      "accept" => array:1 [
        0 => "application/json"
      ]
      "cache-control" => array:1 [
        0 => "no-cache"
      ]
      "postman-token" => array:1 [
        0 => "5cce7f80-dc5f-4e5d-a0a1-273c8d4209b6"
      ]
      "user-agent" => array:1 [
        0 => "PostmanRuntime/7.4.0"
      ]
      "host" => array:1 [
        0 => "local.net"
      ]
      "accept-encoding" => array:1 [
        0 => "gzip, deflate"
      ]
      "referer" => array:1 [
        0 => "http://local.net/app_dev.php/api/projects?city=bekasi"
      ]
      "connection" => array:1 [
        0 => "keep-alive"
      ]
      "x-php-ob-level" => array:1 [
        0 => 0
      ]
    ]
    #cacheControl: array:1 [
      "no-cache" => true
    ]
  }
  #content: null
  #languages: null
  #charsets: null
  #encodings: null
  #acceptableContentTypes: null
  #pathInfo: "/api/projects"
  #requestUri: "/api/projects?city=bekasi"
  #baseUrl: ""
  #basePath: null
  #method: "GET"
  #format: "json"
  #session: Session {#1324
    #storage: NativeSessionStorage {#1323
      #bags: array:2 [
        "attributes" => SessionBagProxy {#1296
          -bag: AttributeBag {#1318
            -name: "attributes"
            -storageKey: "_sf2_attributes"
            #attributes: []
          }
          -data: &1 []
          -usageIndex: &2 0
        }
        "flashes" => SessionBagProxy {#1291
          -bag: FlashBag {#1317
            -name: "flashes"
            -flashes: []
            -storageKey: "_symfony_flashes"
          }
          -data: &1 []
          -usageIndex: &2 0
        }
      ]
      #started: false
      #closed: false
      #saveHandler: SessionHandlerProxy {#1319
        #handler: StrictSessionHandler {#1322
          -handler: NativeFileSessionHandler {#1321}
          -doDestroy: null
          -sessionName: null
          -prefetchId: null
          -prefetchData: null
          -newSessionId: null
          -igbinaryEmptyData: null
        }
        #wrapper: false
        #saveHandlerName: "user"
      }
      #metadataBag: MetadataBag {#1320
        -name: "__metadata"
        -storageKey: "_sf2_meta"
        #meta: array:3 [
          "c" => 0
          "u" => 0
          "l" => 0
        ]
        -lastUsed: null
        -updateThreshold: "0"
      }
    }
    -flashName: "flashes"
    -attributeName: "attributes"
    -data: &1 []
    -usageIndex: &2 0
  }
  #locale: null
  #defaultLocale: "id"
  -isHostValid: true
  -isForwardedValid: true
  basePath: ""
}

1 个答案:

答案 0 :(得分:0)

感谢slack chat @api-platform的@norkunas

我通过检查扩展名(如果对象是的实例)使其工作 ContextAwareQueryCollectionExtensionInterfaceContextAwareQueryResultCollectionExtensionInterface类请参见下面的代码

/**
 * Retrieves a collection.
 *
 * @param string $resourceClass
 * @param string|null $operationName
 * @param array $context
 * @return array|\Traversable
 */
public function getCollection(string $resourceClass, string $operationName = null, array $context = [])
{
    $manager = $this->managerRegistry->getManagerForClass($resourceClass);
    $project = $manager->getRepository($resourceClass);
    $queryBuilder = $project->createQueryBuilder('p');
    $queryNameGenerator = new QueryNameGenerator();
    $params = $this->requestStack->getCurrentRequest()->query->all();

    if (!empty($params)) {
        foreach ($this->collectionExtensions as $extension) {
            if ($extension instanceof ContextAwareQueryCollectionExtensionInterface) {
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
            } elseif ($extension instanceof QueryCollectionExtensionInterface) {
                $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName);
            }

            if ($extension instanceof ContextAwareQueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName, $context)) {
                return $extension->getResult($queryBuilder, $resourceClass, $operationName, $context);
            } elseif ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
                return $extension->getResult($queryBuilder);
            }
        }
    }

    return $queryBuilder->getQuery()->getResult();
}