From 47909625325da7c4328e3870b9c90f3bf11782b9 Mon Sep 17 00:00:00 2001 From: James Waring Date: Tue, 7 May 2024 19:47:53 +0100 Subject: [PATCH] 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 --- src/ModelFilter.php | 10 +++++++++- tests/ModelFilterTest.php | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/ModelFilter.php b/src/ModelFilter.php index 29473b7..84eef37 100644 --- a/src/ModelFilter.php +++ b/src/ModelFilter.php @@ -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. * @@ -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(); } diff --git a/tests/ModelFilterTest.php b/tests/ModelFilterTest.php index 237dc97..163d1b2 100644 --- a/tests/ModelFilterTest.php +++ b/tests/ModelFilterTest.php @@ -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';