1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Support\Str; |
7
|
|
|
use Spatie\QueryBuilder\AllowedInclude; |
8
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidIncludeQuery; |
9
|
|
|
use Spatie\QueryBuilder\Includes\IncludeInterface; |
10
|
|
|
|
11
|
|
|
trait AddsIncludesToQuery |
12
|
|
|
{ |
13
|
|
|
/** @var \Illuminate\Support\Collection */ |
14
|
|
|
protected $allowedIncludes; |
15
|
|
|
|
16
|
|
|
public function allowedIncludes($includes): self |
17
|
|
|
{ |
18
|
|
|
$includes = is_array($includes) ? $includes : func_get_args(); |
19
|
|
|
|
20
|
|
|
$this->allowedIncludes = collect($includes) |
21
|
|
|
->flatMap(function ($include): Collection { |
22
|
|
|
if ($include instanceof IncludeInterface) { |
23
|
|
|
return collect([$include]); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
if (Str::endsWith($include, config('query-builder.count_suffix'))) { |
27
|
|
|
return AllowedInclude::count($include); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return AllowedInclude::relationship($include); |
31
|
|
|
}) |
32
|
|
|
->unique(function (AllowedInclude $allowedInclude) { |
33
|
|
|
return $allowedInclude->getName(); |
34
|
|
|
}); |
35
|
|
|
|
36
|
|
|
$this->ensureAllIncludesExist(); |
37
|
|
|
|
38
|
|
|
$this->addIncludesToQuery($this->request->includes()); |
|
|
|
|
39
|
|
|
|
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
protected function addIncludesToQuery(Collection $includes) |
44
|
|
|
{ |
45
|
|
|
$includes->each(function ($include) { |
46
|
|
|
$include = $this->findInclude($include); |
47
|
|
|
|
48
|
|
|
$include->include($this); |
49
|
|
|
}); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
protected function findInclude(string $include): ?AllowedInclude |
53
|
|
|
{ |
54
|
|
|
return $this->allowedIncludes |
55
|
|
|
->first(function (AllowedInclude $included) use ($include) { |
56
|
|
|
return $included->isForInclude($include); |
57
|
|
|
}); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
protected function ensureAllIncludesExist() |
61
|
|
|
{ |
62
|
|
|
$includes = $this->request->includes(); |
63
|
|
|
|
64
|
|
|
$allowedIncludeNames = $this->allowedIncludes->map(function (AllowedInclude $allowedInclude) { |
65
|
|
|
return $allowedInclude->getName(); |
66
|
|
|
}); |
67
|
|
|
|
68
|
|
|
$diff = $includes->diff($allowedIncludeNames); |
69
|
|
|
|
70
|
|
|
if ($diff->count()) { |
71
|
|
|
throw InvalidIncludeQuery::includesNotAllowed($diff, $allowedIncludeNames); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
// TODO: Check for non-existing relationships? |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
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: