Skip to content

Commit

Permalink
Add NotEmptyFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Nov 18, 2020
1 parent b4215aa commit f8f9835
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
2 changes: 2 additions & 0 deletions docs/reference/filter_field_definition.rst
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ Empty
}
}

This filter has an additional option ``inverse`` in order to be used as a ``NotEmptyFilter``.

Advanced usage
--------------

Expand Down
16 changes: 8 additions & 8 deletions src/Filter/EmptyFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,18 @@ public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $value
return;
}

if (BooleanType::TYPE_YES === (int) $value['value']) {
$isYes = BooleanType::TYPE_YES === (int) $value['value'];
$isNo = BooleanType::TYPE_NO === (int) $value['value'];

if (!$this->getOption('inverse') && $isYes || $this->getOption('inverse') && $isNo) {
$this->applyWhere(
$queryBuilder,
$queryBuilder
->expr()
->isNull(sprintf('%s.%s', $alias, $field))
$queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $field))
);
} elseif (BooleanType::TYPE_NO === (int) $value['value']) {
} elseif (!$this->getOption('inverse') && $isNo || $this->getOption('inverse') && $isYes) {
$this->applyWhere(
$queryBuilder,
$queryBuilder
->expr()
->isNotNull(sprintf('%s.%s', $alias, $field))
$queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field))
);
}
}
Expand All @@ -54,6 +53,7 @@ public function getDefaultOptions()
'field_type' => BooleanType::class,
'operator_type' => HiddenType::class,
'operator_options' => [],
'inverse' => false,
];
}

Expand Down
9 changes: 6 additions & 3 deletions tests/Filter/EmptyFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,12 @@ public function testEmpty(): void
/**
* @dataProvider valueDataProvider
*/
public function testValue(int $value, string $expectedQuery): void
public function testValue(bool $inverse, int $value, string $expectedQuery): void
{
$filter = new EmptyFilter();
$filter->initialize('field_name', [
'field_options' => ['class' => 'FooBar'],
'inverse' => $inverse,
]);

$builder = new ProxyQuery(new QueryBuilder());
Expand All @@ -68,8 +69,10 @@ public function testRenderSettings(): void
public function valueDataProvider(): array
{
return [
[BooleanType::TYPE_YES, 'alias.field IS NULL'],
[BooleanType::TYPE_NO, 'alias.field IS NOT NULL'],
[false, BooleanType::TYPE_YES, 'alias.field IS NULL'],
[false, BooleanType::TYPE_NO, 'alias.field IS NOT NULL'],
[true, BooleanType::TYPE_YES, 'alias.field IS NOT NULL'],
[true, BooleanType::TYPE_NO, 'alias.field IS NULL'],
];
}
}

0 comments on commit f8f9835

Please sign in to comment.