Created
August 23, 2021 17:38
-
-
Save wizhippo/5c6f2c6fd56f81283387d357fcd2a918 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\EasyAdmin\Filter; | |
use Doctrine\ORM\Query\Expr\Orx; | |
use Doctrine\ORM\QueryBuilder; | |
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Filter\FilterInterface; | |
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto; | |
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto; | |
use EasyCorp\Bundle\EasyAdminBundle\Dto\FilterDataDto; | |
use EasyCorp\Bundle\EasyAdminBundle\Filter\FilterTrait; | |
use EasyCorp\Bundle\EasyAdminBundle\Form\Filter\Type\ComparisonFilterType; | |
use EasyCorp\Bundle\EasyAdminBundle\Form\Type\ComparisonType; | |
use Symfony\Component\Form\Extension\Core\Type\TextType; | |
class EmbeddedEntityPropertyFilter implements FilterInterface | |
{ | |
use FilterTrait; | |
public static function new(string $propertyName, $label = null): self | |
{ | |
return (new self()) | |
->setFilterFqcn(__CLASS__) | |
->setProperty($propertyName) | |
->setLabel($label) | |
->setFormType(ComparisonFilterType::class) | |
->setFormTypeOption('value_type', TextType::class) | |
->setFormTypeOption('translation_domain', 'EasyAdminBundle') | |
; | |
} | |
public function apply(QueryBuilder $queryBuilder, FilterDataDto $filterDataDto, ?FieldDto $fieldDto, EntityDto $entityDto): void | |
{ | |
$alias = $filterDataDto->getEntityAlias(); | |
$property = $filterDataDto->getProperty(); | |
$property = str_replace(':', '.', $property); | |
$comparison = $filterDataDto->getComparison(); | |
$parameterName = $filterDataDto->getParameterName(); | |
$parameterName = str_replace(':', '_', $parameterName); | |
$value = $filterDataDto->getValue(); | |
if (null === $value) { | |
$queryBuilder->andWhere(sprintf('%s.%s %s', $alias, $property, $comparison)); | |
} else { | |
$orX = new Orx(); | |
$orX->add(sprintf('%s.%s %s (:%s)', $alias, $property, $comparison, $parameterName)); | |
if (ComparisonType::NEQ === $comparison) { | |
$orX->add(sprintf('%s.%s IS NULL', $alias, $property)); | |
} | |
$queryBuilder->andWhere($orX) | |
->setParameter($parameterName, $value) | |
; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment