gpt4 book ai didi

symfony - Api 平台所需的过滤器

转载 作者:行者123 更新时间:2023-12-05 09:14:05 25 4
gpt4 key购买 nike

我使用的是 API 平台,我在 https://api-platform.com/docs/core/filters/#creating-custom-filters 之后定义了一个自定义过滤器

它工作正常,但我需要每次应用程序对特定实体(设置过滤器的位置)执行 GET HTTP 请求时都需要过滤器。

我已经检查了这段代码:

// This function is only used to hook in documentation generators (supported by Swagger and Hydra)
public function getDescription(string $resourceClass): array
{
if (!$this->properties) {
return [];
}

$description = [];
foreach ($this->properties as $property => $strategy) {
$description["similar_$property"] = [
'property' => $property,
'type' => 'string',
'required' => false,
'swagger' => [
'description' => 'Filter using a similar postgres function.',
'name' => $property,
'type' => 'string',
],
];
}

return $description;
}

虽然 getDescription 有一个必填字段,但它只适用于 api 文档,不适用于 HTTP 请求

最佳答案

您可以通过事件系统实现过滤器。

/**
* @ApiResource
*/
class Resource {
...
}
<?php

namespace App\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

class ResourceReadSubscriber implements EventSubscriberInterface
{
/**
* @return array The event names to listen to
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => [
['hasFilter', EventPriorities::PRE_READ],
],
];
}

public function hasFilter(ControllerEvent $event)
{
// first check if this affects the requested resource
$resource = $event->getRequest()->attributes->get('_api_resource_class');

if (Resource::class !== $resource) {
return;
}

// second check if this is the get_collection controller
$controller = $event->getRequest()->attributes->get('_controller');

if ('api_platform.action.get_collection' !== $controller) {
return;
}

// third validate the required filter is set
// we expect a filter via GET parameter 'filter-query-parameter'
if (!$event->getRequest()->query->has('filter-query-parameter')) {
throw new BadRequestHttpException('Filter is required');
}
}
}

关于symfony - Api 平台所需的过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55020369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com