1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Spatie\QueryBuilder\Search; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidSearchQuery; |
8
|
|
|
|
9
|
|
|
trait SearchesQuery |
10
|
|
|
{ |
11
|
|
|
/** @var \Illuminate\Support\Collection */ |
12
|
|
|
protected $allowedSearches; |
13
|
|
|
|
14
|
|
|
public function allowedSearches($searches): self |
15
|
|
|
{ |
16
|
|
|
$searches = is_array($searches) ? $searches : func_get_args(); |
17
|
|
|
$this->allowedSearches = collect($searches)->map(function ($search) { |
18
|
|
|
if ($search instanceof Search) { |
19
|
|
|
return $search; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
return Search::resolver($search); |
23
|
|
|
}); |
24
|
|
|
|
25
|
|
|
$this->guardAgainstUnknownSearches(); |
26
|
|
|
|
27
|
|
|
$this->addSearchesToQuery($this->request->searches()); |
|
|
|
|
28
|
|
|
|
29
|
|
|
return $this; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
protected function addSearchesToQuery(Collection $searches) |
33
|
|
|
{ |
34
|
|
|
$searchParameter = config('query-builder.parameters.search'); |
35
|
|
|
|
36
|
|
|
$searches->each(function ($item, $modifier) use ($searchParameter) { |
37
|
|
|
$modifier = preg_replace(sprintf('/^%s\:?/', $searchParameter), '', $modifier, 1); |
38
|
|
|
collect($item)->each(function($value, $property) use ($modifier) { |
39
|
|
|
if (is_string($property)) { |
40
|
|
|
$search = $this->findSearch($property); |
41
|
|
|
|
42
|
|
|
$search->search($this, $value, $modifier); |
43
|
|
|
} else { |
44
|
|
|
$this->allowedSearches->each(function($search) use ($value, $modifier) { |
45
|
|
|
$search->search($this, $value, $modifier); |
46
|
|
|
}); |
47
|
|
|
} |
48
|
|
|
}); |
49
|
|
|
}); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function findSearch(string $property): ?Search |
53
|
|
|
{ |
54
|
|
|
return $this->allowedSearches |
55
|
|
|
->first(function (Search $search) use ($property) { |
56
|
|
|
return $search->isForProperty($property); |
57
|
|
|
}); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
protected function guardAgainstUnknownSearches() |
61
|
|
|
{ |
62
|
|
|
$searchNames = $this->request->searches() |
63
|
|
|
->filter(function($item) { |
64
|
|
|
return is_array($item); |
65
|
|
|
}) |
66
|
|
|
->mapWithKeys(function($item) { |
67
|
|
|
return $item; |
68
|
|
|
})->keys(); |
69
|
|
|
|
70
|
|
|
$allowedSearchNames = $this->allowedSearches->map->getProperty(); |
71
|
|
|
|
72
|
|
|
$diff = $searchNames->diff($allowedSearchNames); |
73
|
|
|
|
74
|
|
|
if ($diff->count()) { |
75
|
|
|
throw InvalidSearchQuery::searchesNotAllowed($diff, $allowedSearchNames); |
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: