|
2 | 2 |
|
3 | 3 | namespace Rappasoft\LaravelLivewireTables\Traits;
|
4 | 4 |
|
| 5 | +use Rappasoft\LaravelLivewireTables\Views\Filter; |
| 6 | + |
5 | 7 | /**
|
6 | 8 | * Trait WithFilters.
|
7 | 9 | */
|
@@ -41,22 +43,63 @@ public function resetAll(): void
|
41 | 43 | $this->resetBulk();
|
42 | 44 | }
|
43 | 45 |
|
| 46 | + /** |
| 47 | + * Define filters |
| 48 | + * |
| 49 | + * @return Filter[] |
| 50 | + */ |
44 | 51 | public function filters(): array
|
45 | 52 | {
|
46 | 53 | return [];
|
47 | 54 | }
|
48 | 55 |
|
| 56 | + /** |
| 57 | + * Cleans $filter property of any values that don't exist |
| 58 | + * in the filter() definition. |
| 59 | + */ |
49 | 60 | public function cleanFilters(): void
|
50 | 61 | {
|
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; |
58 | 71 | }
|
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); |
60 | 103 | }
|
61 | 104 |
|
62 | 105 | public function filtersView(): ?string
|
|
0 commit comments