Skip to content

Commit 4790962

Browse files
james-waringEric Tucker
and
Eric Tucker
authored
Added the ability to enable filters to work with empty values (#200)
* Added the ability to enable filters to work with empty values * update tests and filter before input is set instead of adding methods --------- Co-authored-by: Eric Tucker <[email protected] Eric Tucker>
1 parent acbfbe0 commit 4790962

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/ModelFilter.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ abstract class ModelFilter
4141
*/
4242
protected $blacklist = [];
4343

44+
/**
45+
* Filter out empty input so filter methods won't be called with empty values (strings, arrays, null).
46+
*
47+
* @var array
48+
*/
49+
protected $allowedEmptyFilters = false;
50+
4451
/**
4552
* Array of input to filter.
4653
*
@@ -93,8 +100,9 @@ abstract class ModelFilter
93100
public function __construct($query, array $input = [], $relationsEnabled = true)
94101
{
95102
$this->query = $query;
96-
$this->input = $this->removeEmptyInput($input);
103+
$this->input = $this->allowedEmptyFilters ? $input : $this->removeEmptyInput($input);
97104
$this->relationsEnabled = $relationsEnabled;
105+
98106
$this->registerMacros();
99107
}
100108

tests/ModelFilterTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,27 @@ public function testBlacklistAddingAndRemoving()
288288
$this->assertFalse($this->filter->methodIsBlacklisted($method));
289289
}
290290

291+
public function testAllowedEmptyFilter()
292+
{
293+
$emptyInput = [
294+
'empty_array' => [],
295+
'null_value' => null,
296+
'empty_string' => '',
297+
];
298+
299+
$filter = new class($this->builder, $emptyInput) extends ModelFilter
300+
{
301+
protected $allowedEmptyFilters = true;
302+
};
303+
304+
$this->assertEquals($filter->input(), $emptyInput);
305+
306+
$filter = new class($this->builder, $emptyInput) extends ModelFilter {
307+
};
308+
309+
$this->assertEquals($filter->input(), []);
310+
}
311+
291312
public function testParentClassMethodsCantBeCalledByInput()
292313
{
293314
$badMethod = 'whitelistMethod';

0 commit comments

Comments
 (0)