Api 平台所需的过滤器

Ayt*_*Nzt 1 symfony api-platform.com symfony-4.2

我使用 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*ven 5

您可以通过事件系统强制执行过滤器。

/**
 * @ApiResource
 */
class Resource {
    ...
}
Run Code Online (Sandbox Code Playgroud)
<?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');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)