也许您想让客户选择如何组合过滤条件和逻辑。这可以通过在“and”或“or”中嵌套过滤条件来完成,例如:
/users/?or[username]=super&or[name]=john
这将返回用户名中包含“super”或名称中包含“john”的所有用户。或者,如果您需要更复杂的逻辑和同一属性的多个条件:
/users/?and[name]=john&and[or][][email]=microsoft.com&and[or][][email]=apple.com
这将返回名称中包含 john 并且(电子邮件地址中包含 microsoft.com 或 apple.com)的所有用户。由于描述的嵌套或标准通过 AND 与名称标准组合在一起,名称标准必须始终为真,而电子邮件的标准只有一个需要为真才能返回用户。
要在您的应用程序中进行这项工作,请在您的 api src/Filter 文件夹中创建一个文件 FilterLogic.php
(如果您还没有文件夹,请创建此文件夹),内容如下:
<?php
namespace App\Filter;
use ApiPlatform\Core\Api\FilterCollection;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\FilterInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
/**
* Combines existing API Platform ORM Filters with AND and OR.
* For usage and limitations see https://gist.github.com/metaclass-nl/790a5c8e9064f031db7d3379cc47c794
* Copyright (c) MetaClass, Groningen, 2021. MIT License
*/
class FilterLogic extends AbstractContextAwareFilter
{
/** @var ResourceMetadataFactoryInterface */
private $resourceMetadataFactory;
/** @var ContainerInterface|FilterCollection */
private $filterLocator;
/** @var string Filter classes must match this to be applied with logic */
private $classExp;
/**
* @param ResourceMetadataFactoryInterface $resourceMetadataFactory
* @param ContainerInterface|FilterCollection $filterLocator
* @param $regExp string Filter classes must match this to be applied with logic
* {@inheritdoc}
*/
public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, $filterLocator, string $classExp='//', ManagerRegistry $managerRegistry, RequestStack $requestStack=null, LoggerInterface $logger = null, array $properties = null, NameConverterInterface $nameConverter = null)
{
parent::__construct($managerRegistry, $requestStack, $logger, $properties, $nameConverter);
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->filterLocator = $filterLocator;
$this->classExp = $classExp;
}
/** {@inheritdoc } */
public function getDescription(string $resourceClass): array
{
// No description
return [];
}
/**
* {@inheritdoc}
* @throws ResourceClassNotFoundException
* @throws \LogicException if assumption proves wrong
*/
protected function filterProperty(string $parameter, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null, array $context = [])
{
$filters = $this->getFilters($resourceClass, $operationName);
if ($parameter == 'and') {
$newWhere = $this->applyLogic($filters, 'and', $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
$queryBuilder->andWhere($newWhere);
}
if ($parameter == 'or') {
$newWhere = $this->applyLogic($filters, 'or', $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
$queryBuilder->orWhere($newWhere);
}
}
/**
* Applies filters in compound logic context
* @param FilterInterface[] $filters to apply in context of $operator
* @param string $operator 'and' or 'or
* @return mixed Valid argument for Expr\Andx::add and Expr\Orx::add
* @throws \LogicException if assumption proves wrong
*/
private function applyLogic($filters, $operator, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context)
{
$oldWhere = $queryBuilder->getDQLPart('where');
// replace by marker expression
$marker = new Expr\Func('NOT', []);
$queryBuilder->add('where', $marker);
$subFilters = $context['filters'][$operator];
// print json_encode($subFilters, JSON_PRETTY_PRINT);
$assoc = [];
$logic = [];
foreach ($subFilters as $key => $value) {
if (ctype_digit((string) $key)) {
// allows the same filter to be applied several times, usually with different arguments
$subcontext = $context; //copies
$subcontext['filters'] = $value;
$this->applyFilters($filters, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $subcontext);
// apply logic seperately
if (isset($value['and'])) {
$logic[]['and'] = $value['and'];
}if (isset($value['or'])) {
$logic[]['or'] = $value['or'];
}
} elseif (in_array($key, ['and', 'or'])) {
$logic[][$key] = $value;
} else {
$assoc[$key] = $value;
}
}
// Process $assoc
$subcontext = $context; //copies
$subcontext['filters'] = $assoc;
$this->applyFilters($filters, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $subcontext);
$newWhere = $queryBuilder->getDQLPart('where');
$queryBuilder->add('where', $oldWhere); //restores old where
// force $operator logic upon $newWhere
if ($operator == 'and') {
$adaptedPart = $this->adaptWhere(Expr\Andx::class, $newWhere, $marker);
} else {
$adaptedPart = $this->adaptWhere(Expr\Orx::class, $newWhere, $marker);
}
// Process logic
foreach ($logic as $eachLogic) {
$subcontext = $context; //copies
$subcontext['filters'] = $eachLogic;
$newWhere = $this->applyLogic($filters, key($eachLogic), $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $subcontext);
$adaptedPart->add($newWhere); // empty expressions are ignored by ::add
}
return $adaptedPart; // may be empty
}
private function applyFilters($filters, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context)
{
foreach ($filters as $filter) {
$filter->apply($queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
}
}
/**
* ASSUMPTION: filters do not use QueryBuilder::where or QueryBuilder::add
* and create semantically complete expressions in the sense that expressions
* added to the QueryBundle through ::andWhere or ::orWhere do not depend
* on one another so that the intended logic is not compromised if they are
* recombined with the others by either Doctrine\ORM\Query\Expr\Andx
* or Doctrine\ORM\Query\Expr\Orx.
*
* Replace $where by an instance of $expClass.
* andWhere and orWhere allways add their args at the end of existing or
* new logical expressions, so we started with a marker expression
* to become the deepest first part. The marker should not be returned
* @param string $expClass
* @param Expr\Andx | Expr\Orx $where Result from applying filters
* @param Expr\Func $marker Marks the end of logic resulting from applying filters
* @return Expr\Andx | Expr\Orx Instance of $expClass
* @throws \LogicException if assumption proves wrong
*/
private function adaptWhere($expClass, $where, $marker)
{
if ($where === $marker) {
// Filters did nothing
return new $expClass([]);
}
if (!$where instanceof Expr\Andx && !$where instanceof Expr\Orx) {
// A filter used QueryBuilder::where or QueryBuilder::add or otherwise
throw new \LogicException("Assumpion failure, unexpected Expression: ". $where);
}
$parts = $where->getParts();
if (empty($parts)) {
// A filter used QueryBuilder::where or QueryBuilder::add or otherwise
throw new \LogicException("Assumpion failure, marker not found");
}
if ($parts[0] === $marker) {
// Marker found, recursion ends here
array_shift($parts);
} else {
$parts[0] = $this->adaptWhere($expClass, $parts[0], $marker);
}
return new $expClass($parts);
}
/**
* @param string $resourceClass
* @param string $operationName
* @return FilterInterface[] From resource except $this and OrderFilters
* @throws ResourceClassNotFoundException
*/
protected function getFilters($resourceClass, $operationName)
{
$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
$resourceFilters = $resourceMetadata->getCollectionOperationAttribute($operationName, 'filters', [], true);
$result = [];
foreach ($resourceFilters as $filterId) {
$filter = $this->filterLocator->has($filterId)
? $this->filterLocator->get($filterId)
: null;
if ($filter instanceof FilterInterface
&& !($filter instanceof OrderFilter)
&& $filter !== $this
&& preg_match($this->classExp, get_class($filter))
) {
$result[$filterId] = $filter;
}
}
return $result;
}
}
然后将以下服务配置添加到您的 api config/services.yml:
'App\Filter\FilterLogic':
class: 'App\Filter\FilterLogic'
arguments:
- '@api_platform.metadata.resource.metadata_factory'
- '@api_platform.filter_locator'
public: false
abstract: true
autoconfigure: false
最后像这样调整你的实体:
use App\Filter\FilterLogic;
/**
* @ApiResource
* @ApiFilter(SearchFilter::class, properties={
* "name": "ipartial",
* "username": "ipartial",
* "email": "ipartial",
* })
* @ApiFilter(FilterLogic.class)
*
您也可以通过添加@ApiFilter 注解将其应用到其他类中。
FilterLogic 类的注释是最后一个@ApiFilter 注释,这一点很重要。 正常的过滤仍将照常工作:过滤器决定如何将自己应用于 QueryBuilder。如果都使用 ::andWhere,就像 Api Platform 的内置过滤器一样,ApiFilter 属性/注释的顺序无关紧要,但如果某些使用其他方法,不同的顺序可能会产生不同的结果。 FilterLogic 使用 orWhere 表示“或”,因此顺序很重要。如果它是最后一个过滤器,它的逻辑表达式将成为最顶层的,因此定义了主逻辑。
限制
适用于 Api 平台的内置过滤器,但具有 EXCLUDE_NULL 的 DateFilter 除外。
This DateFilter 子类可能会修复它。
假设过滤器创建语义完整的表达式
通过 ::andWhere 或 ::orWhere 添加到 QueryBundle 的表达式不依赖
彼此之间,以便在重新组合时不会损害预期的逻辑
通过 Doctrine\ORM\Query\Expr\Andx 或 Doctrine\ORM\Query\Expr\Orx 与其他人一起使用。
如果过滤器使用 QueryBuilder::where 或 ::add 可能会失败。
建议您检查所有自定义和第三方过滤器的代码和
不要将那些使用 QueryBuilder::where 或 ::add 与 FilterLogic 结合起来
或者产生在语义上不完整的复杂逻辑。为
语义完整和不完整表达式的示例参见DateFilterTest。
您可以通过配置 classExp 来按类名加入/排除过滤器。例如:
* @ApiFilter(FilterLogic::class, arguments={"classExp"="/ApiPlatform\\Core\\Bridge\\Doctrine\\Orm\\Filter\\+/"})
只会在逻辑上下文中应用 API 平台 ORM 过滤器。