Skip to content

Commit ac87d61

Browse files
committed
refactoring cleanFilters
1 parent 97683e6 commit ac87d61

File tree

2 files changed

+52
-9
lines changed

2 files changed

+52
-9
lines changed

src/DataTableComponent.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ public function __construct($id = null)
150150
*/
151151
public function getRowsQueryProperty(): Builder
152152
{
153-
//$this->cleanFilters();
153+
$this->cleanFilters();
154154

155155
return $this->applySorting($this->query());
156156
}

src/Traits/WithFilters.php

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Rappasoft\LaravelLivewireTables\Traits;
44

5+
use Rappasoft\LaravelLivewireTables\Views\Filter;
6+
57
/**
68
* Trait WithFilters.
79
*/
@@ -41,22 +43,63 @@ public function resetAll(): void
4143
$this->resetBulk();
4244
}
4345

46+
/**
47+
* Define filters
48+
*
49+
* @return Filter[]
50+
*/
4451
public function filters(): array
4552
{
4653
return [];
4754
}
4855

56+
/**
57+
* Cleans $filter property of any values that don't exist
58+
* in the filter() definition.
59+
*/
4960
public function cleanFilters(): void
5061
{
51-
foreach ($this->filters() as $key => $filter) {
52-
if (
53-
$filter->isSelect() &&
54-
$this->hasFilter($key) &&
55-
! in_array($this->getFilter($key), $this->getFilterOptions($key), true)
56-
) {
57-
$this->removeFilter($key);
62+
// grab the filter definitions
63+
$filterDefinitions = $this->filters();
64+
65+
// filter $filters values
66+
$this->filters = array_filter($this->filters, function($filterValue, $filterName) use($filterDefinitions) {
67+
68+
// ignore search
69+
if ($filterName === 'search') {
70+
return true;
5871
}
59-
}
72+
73+
// filter out any keys that weren't defined as a filter
74+
if (!isset($filterDefinitions[$filterName])) {
75+
return false;
76+
}
77+
78+
// ignore null values
79+
if (is_null($filterValue)) {
80+
return true;
81+
}
82+
83+
// handle Select filters
84+
if ($filterDefinitions[$filterName]->isSelect()) {
85+
86+
foreach ($filterDefinitions[$filterName]->options() as $optionValue => $optionLabel) {
87+
88+
// if the option is an integer, typecast filter value
89+
if (is_int($optionValue) && $optionValue === (int)$filterValue) {
90+
return true;
91+
// strict check the value
92+
} elseif ($optionValue === $filterValue) {
93+
return true;
94+
}
95+
96+
}
97+
98+
}
99+
100+
return false;
101+
102+
}, ARRAY_FILTER_USE_BOTH);
60103
}
61104

62105
public function filtersView(): ?string

0 commit comments

Comments
 (0)