From 8f37186d26a715958b55b1b6629ed1b544b5053e Mon Sep 17 00:00:00 2001 From: Patrick Robrecht Date: Wed, 18 Oct 2023 10:21:08 +0200 Subject: [PATCH 1/2] Unset default if the AllowedFilter::default method is called multiple times --- src/AllowedFilter.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/AllowedFilter.php b/src/AllowedFilter.php index cddf759b..8d9617d5 100644 --- a/src/AllowedFilter.php +++ b/src/AllowedFilter.php @@ -153,6 +153,7 @@ public function default($value): self $this->default = $value; if (is_null($value)) { + $this->unsetDefault(); $this->nullable(true); } @@ -176,6 +177,14 @@ public function nullable(bool $nullable = true): self return $this; } + public function unsetDefault(): self + { + $this->hasDefault = false; + unset($this->default); + + return $this; + } + protected function resolveValueForFiltering($value) { if (is_array($value)) { From c28b916ec4117d931128d2882de84cd68b7d9f9f Mon Sep 17 00:00:00 2001 From: Patrick Robrecht Date: Mon, 11 Dec 2023 20:04:17 +0100 Subject: [PATCH 2/2] Remove unsetDefault() from default(), add tests --- src/AllowedFilter.php | 1 - tests/FilterTest.php | 22 ++++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/AllowedFilter.php b/src/AllowedFilter.php index 8d9617d5..801f2f74 100644 --- a/src/AllowedFilter.php +++ b/src/AllowedFilter.php @@ -153,7 +153,6 @@ public function default($value): self $this->default = $value; if (is_null($value)) { - $this->unsetDefault(); $this->nullable(true); } diff --git a/tests/FilterTest.php b/tests/FilterTest.php index fed233ef..c9f9f0c1 100644 --- a/tests/FilterTest.php +++ b/tests/FilterTest.php @@ -562,6 +562,28 @@ public function __invoke(Builder $query, $value, string $property): Builder expect($models->count())->toEqual(1); }); +it('should filter by query parameters if a default value is set and unset afterwards', function () { + TestModel::create(['name' => 'John Doe']); + + $filterWithDefault = AllowedFilter::exact('name')->default('some default value'); + $models = createQueryFromFilterRequest([ + 'name' => 'John Doe', + ]) + ->allowedFilters($filterWithDefault->unsetDefault()) + ->get(); + + expect($models->count())->toEqual(1); +}); + +it('should not filter at all if a default value is set and unset afterwards', function () { + $filterWithDefault = AllowedFilter::exact('name')->default('some default value'); + $models = createQueryFromFilterRequest([]) + ->allowedFilters($filterWithDefault->unsetDefault()) + ->get(); + + expect($models->count())->toEqual(5); +}); + it('should apply a filter with a multi-dimensional array value', function () { TestModel::create(['name' => 'John Doe']);