Skip to content

Commit

Permalink
Added the ability to enable filters to work with empty values (#200)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
james-waring and Eric Tucker authored May 7, 2024
1 parent acbfbe0 commit 4790962
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/ModelFilter.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ abstract class ModelFilter
*/
protected $blacklist = [];

/**
* Filter out empty input so filter methods won't be called with empty values (strings, arrays, null).
*
* @var array
*/
protected $allowedEmptyFilters = false;

/**
* Array of input to filter.
*
Expand Down Expand Up @@ -93,8 +100,9 @@ abstract class ModelFilter
public function __construct($query, array $input = [], $relationsEnabled = true)
{
$this->query = $query;
$this->input = $this->removeEmptyInput($input);
$this->input = $this->allowedEmptyFilters ? $input : $this->removeEmptyInput($input);
$this->relationsEnabled = $relationsEnabled;

$this->registerMacros();
}

Expand Down
21 changes: 21 additions & 0 deletions tests/ModelFilterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,27 @@ public function testBlacklistAddingAndRemoving()
$this->assertFalse($this->filter->methodIsBlacklisted($method));
}

public function testAllowedEmptyFilter()
{
$emptyInput = [
'empty_array' => [],
'null_value' => null,
'empty_string' => '',
];

$filter = new class($this->builder, $emptyInput) extends ModelFilter
{
protected $allowedEmptyFilters = true;
};

$this->assertEquals($filter->input(), $emptyInput);

$filter = new class($this->builder, $emptyInput) extends ModelFilter {
};

$this->assertEquals($filter->input(), []);
}

public function testParentClassMethodsCantBeCalledByInput()
{
$badMethod = 'whitelistMethod';
Expand Down

0 comments on commit 4790962

Please sign in to comment.