1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidFilterQuery; |
7
|
|
|
use Spatie\QueryBuilder\Filter; |
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
|
|
|
return $this; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function addFiltersToQuery(Collection $filters) |
33
|
|
|
{ |
34
|
|
|
$filters->each(function ($value, $property) { |
35
|
|
|
$filter = $this->findFilter($property); |
36
|
|
|
|
37
|
|
|
$filter->filter($this, $value); |
38
|
|
|
}); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
protected function findFilter(string $property): ?Filter |
42
|
|
|
{ |
43
|
|
|
return $this->allowedFilters |
44
|
|
|
->first(function (Filter $filter) use ($property) { |
45
|
|
|
return $filter->isForProperty($property); |
46
|
|
|
}); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function guardAgainstUnknownFilters() |
50
|
|
|
{ |
51
|
|
|
$filterNames = $this->request->filters()->keys(); |
52
|
|
|
|
53
|
|
|
$allowedFilterNames = $this->allowedFilters->map->getProperty(); |
54
|
|
|
|
55
|
|
|
$diff = $filterNames->diff($allowedFilterNames); |
56
|
|
|
|
57
|
|
|
if ($diff->count()) { |
58
|
|
|
throw InvalidFilterQuery::filtersNotAllowed($diff, $allowedFilterNames); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
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: