1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Spatie\QueryBuilder\Filter; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidFilterQuery; |
8
|
|
|
|
9
|
|
|
trait FiltersQuery |
10
|
|
|
{ |
11
|
|
|
/** @var \Illuminate\Support\Collection */ |
12
|
|
|
protected $allowedFilters; |
13
|
|
|
|
14
|
|
|
public function allowedFilters($filters): self |
15
|
|
|
{ |
16
|
|
|
$filters = is_array($filters) ? $filters : func_get_args(); |
17
|
|
|
$this->allowedFilters = collect($filters)->map(function ($filter) { |
18
|
|
|
if ($filter instanceof Filter) { |
19
|
|
|
return $filter; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
return Filter::partial($filter); |
23
|
|
|
}); |
24
|
|
|
|
25
|
|
|
$this->guardAgainstUnknownFilters(); |
26
|
|
|
|
27
|
|
|
$this->addFiltersToQuery($this->request->filters()); |
|
|
|
|
28
|
|
|
|
29
|
|
|
$this->addDefaultFiltersToQuery($this->allowedFilters); |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function addFiltersToQuery(Collection $filters) |
35
|
|
|
{ |
36
|
|
|
$filters->each(function ($value, $property) { |
37
|
|
|
$filter = $this->findFilter($property); |
38
|
|
|
|
39
|
|
|
$filter->filter($this, $value); |
40
|
|
|
}); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
protected function addDefaultFiltersToQuery(Collection $filters) |
44
|
|
|
{ |
45
|
|
|
$filters->each(function ($value) { |
46
|
|
|
$filter = $this->findFilter($value->getProperty()); |
47
|
|
|
|
48
|
|
|
if (! $filter->defaultSet()) { |
49
|
|
|
return; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (! $this->request->filters()->has($filter->getProperty())) { |
53
|
|
|
$filter->filter($this, $filter->getDefault()); |
54
|
|
|
} |
55
|
|
|
}); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function findFilter(string $property): ?Filter |
59
|
|
|
{ |
60
|
|
|
return $this->allowedFilters |
61
|
|
|
->first(function (Filter $filter) use ($property) { |
62
|
|
|
return $filter->isForProperty($property); |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function guardAgainstUnknownFilters() |
67
|
|
|
{ |
68
|
|
|
$filterNames = $this->request->filters()->keys(); |
69
|
|
|
|
70
|
|
|
$allowedFilterNames = $this->allowedFilters->map->getProperty(); |
71
|
|
|
|
72
|
|
|
$diff = $filterNames->diff($allowedFilterNames); |
73
|
|
|
|
74
|
|
|
if ($diff->count()) { |
75
|
|
|
throw InvalidFilterQuery::filtersNotAllowed($diff, $allowedFilterNames); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: