Automatically apply all filters of a compound filter using reflection.

This commit is contained in:
Jan Böhmer 2022-08-18 00:17:07 +02:00
parent f8562f9622
commit 798eb4c1bc
2 changed files with 48 additions and 5 deletions

View file

@ -0,0 +1,44 @@
<?php
namespace App\DataTables\Filters;
use Doctrine\ORM\QueryBuilder;
trait CompoundFilterTrait
{
/**
* Find all child filters that are contained in this filter using reflection.
* A map is returned to the form "property_name" => $filter_object
* @return FilterInterface[]
*/
protected function findAllChildFilters(): array
{
$filters = [];
$reflection = new \ReflectionClass($this);
foreach ($reflection->getProperties() as $property) {
$value = $property->getValue($this);
//We only want filters (objects implementing FilterInterface)
if($value instanceof FilterInterface) {
$filters[$property->getName()] = $value;
}
}
return $filters;
}
/**
* Applies all children filters that are declared as property of this filter using reflection.
* @param QueryBuilder $queryBuilder
* @return void
*/
protected function applyAllChildFilters(QueryBuilder $queryBuilder): void
{
//Retrieve all child filters and apply them
$filters = $this->findAllChildFilters();
foreach ($filters as $filter) {
$filter->apply($queryBuilder);
}
}
}

View file

@ -9,6 +9,9 @@ use Doctrine\ORM\QueryBuilder;
class PartFilter implements FilterInterface
{
use CompoundFilterTrait;
/** @var TextConstraint */
protected $name;
@ -66,10 +69,6 @@ class PartFilter implements FilterInterface
public function apply(QueryBuilder $queryBuilder): void
{
$this->favorite->apply($queryBuilder);
$this->needsReview->apply($queryBuilder);
$this->mass->apply($queryBuilder);
$this->name->apply($queryBuilder);
$this->description->apply($queryBuilder);
$this->applyAllChildFilters($queryBuilder);
}
}