我正在尝试向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 '~'
如何使教义理解波浪线?
我正在尝试向ApiPlatform项目中的实体添加自定义过滤器,该过滤器允许我根据给定的正则表达式模式对特定属性进行过滤。根据ApiPlatform文档,我想到了...
结果证明我离我很近,simPod's answer helped me fill the gaps。