首页 > 解决方案 > 使用 Postgresql 的 ApiPlatform Regex 属性过滤器

问题描述

我正在尝试向我的 ApiPlatform 项目中的实体添加自定义过滤器,该过滤器允许我过滤给定正则表达式模式的特定属性。

根据 ApiPlatform 文档,我提出了以下类(这是他们示例的近似副本,只有 where 子句不同):

<?php

namespace App\Filter;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

final class RegexFilter extends AbstractContextAwareFilter
{
    protected function filterProperty(
        string $property,
        $value,
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        string $operationName = null
    ) {
        // otherwise filter is applied to order and page as well
        if (
            !$this->isPropertyEnabled($property, $resourceClass) ||
            !$this->isPropertyMapped($property, $resourceClass)
        ) {
            return;
        }

        $parameterName = $queryNameGenerator->generateParameterName($property); // Generate a unique parameter name to avoid collisions with other filters
        $queryBuilder
            ->andWhere(sprintf('(o.%s ~ :%s) = true', $property, $parameterName))
            ->setParameter($parameterName, $value);
    }

    // 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["regexp_$property"] = [
                'property' => $property,
                'type' => 'string',
                'required' => false,
                'swagger' => [
                    'description' => 'Filter using a regex. This will appear in the Swagger documentation!',
                    'name' => 'Custom name to use in the Swagger documentation',
                    'type' => 'Will appear below the name in the Swagger documentation',
                ],
            ];
        }

        return $description;
    }
}

当我运行我的代码时,这会产生以下 DQL:

SELECT o FROM App\Entity\Vehicle o WHERE (o.licensePlate ~ :licensePlate_p1) = true ORDER BY o.id ASC

但是我无法让 Lexer 理解波浪号 ~ 字符:

Doctrine\ORM\Query\QueryException
[Syntax Error] line 0, col 56: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '~'

我怎样才能让 Doctrine 理解波浪号?

标签: postgresqldoctrineapi-platform.com

解决方案


原来我已经很接近了,simPod 的回答帮助我填补了空白

  • 我复制了他的自定义 DQL 函数并将其添加到我的 Doctrine yaml 配置中
  • 在我的RegexFilter我不得不稍微修改 where 子句:

    ->andWhere(sprintf('REGEX(o.%s, :%s) = true', $property, $parameterName))
    

推荐阅读