New*_*191 5 php symfony api-platform.com symfony5
我正在使用 Symfony 5 和 API 平台。
我的一个类有一个通过侦听器设置的属性postLoad。该属性仅在某些条件下设置(否则为NULL),我希望允许 REST API 用户根据该属性是否为空或有值来过滤资源。
因为虚拟属性没有持久化到数据库中,所以我假设没有任何 Doctrine 过滤器(例如 )ExistsFilter将对该属性起作用。
如何使用 Symfony 5 和 API 平台为虚拟属性创建过滤功能?
您可以创建自己的自定义 ORM 过滤器。
一个非常简单的例子来展示它是如何完成的:
假设有一个类:
Foo {
public int $weight;
public function isHeavy(): bool {
return $this->weight > 40;
}
}
Run Code Online (Sandbox Code Playgroud)
由于heavy是“虚拟”属性,因此您无法直接对其进行过滤。
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractContextAwareFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;
class HeavyFilter extends AbstractContextAwareFilter
{
public function getDescription(string $resourceClass): array
{
// I'm making the filter available only
if (Foo::class !== $resourceClass) {
return [];
}
if (!$this->properties) {
return [];
}
$description = [];
$description['heavySearch'] =
[
'property' => 'heavy',
'type' => 'bool',
'required' => false,
'swagger' => [
'description' => 'Search for heavy foos',
'name' => 'Heavey Search',
'type' => 'bool',
],
];
return $description;
}
protected function filterProperty(
string $property,
$value,
QueryBuilder $queryBuilder,
QueryNameGeneratorInterface $queryNameGenerator,
string $resourceClass,
string $operationName = null
): void {
if ('heavySearch' !== $property) {
return;
}
if ($value === true) {
$queryBuilder
->andWhere('o.weigth > 40');
}
else {
$queryBuilder
->andWhere('o.weight <= 40');
}
}
}
Run Code Online (Sandbox Code Playgroud)
还没有实际测试过,只是在这里即时编写,但基本想法是正确的。您需要根据自己的情况进行调整,并且您将拥有一个甚至可以在 Open Api 文档中找到的自定义过滤器。
| 归档时间: |
|
| 查看次数: |
986 次 |
| 最近记录: |