1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Support\Str; |
7
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidIncludeQuery; |
8
|
|
|
|
9
|
|
|
trait AddsIncludesToQuery |
10
|
|
|
{ |
11
|
|
|
/** @var \Illuminate\Support\Collection */ |
12
|
|
|
protected $allowedIncludes; |
13
|
|
|
|
14
|
|
|
public function allowedIncludes($includes): self |
15
|
|
|
{ |
16
|
|
|
$includes = is_array($includes) ? $includes : func_get_args(); |
17
|
|
|
|
18
|
|
|
$this->allowedIncludes = collect($includes) |
19
|
|
|
->flatMap(function ($include) { |
20
|
|
|
return collect(explode('.', $include)) |
21
|
|
|
->reduce(function ($collection, $include) { |
22
|
|
|
if ($collection->isEmpty()) { |
23
|
|
|
return $collection->push($include); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
return $collection->push("{$collection->last()}.{$include}"); |
27
|
|
|
}, collect()); |
28
|
|
|
}); |
29
|
|
|
|
30
|
|
|
$this->guardAgainstUnknownIncludes(); |
31
|
|
|
|
32
|
|
|
$this->addIncludesToQuery($this->request->includes()); |
|
|
|
|
33
|
|
|
|
34
|
|
|
return $this; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
protected function addIncludesToQuery(Collection $includes) |
38
|
|
|
{ |
39
|
|
|
$includes |
40
|
|
|
->map([Str::class, 'camel']) |
41
|
|
|
->map(function (string $include) { |
42
|
|
|
return collect(explode('.', $include)); |
43
|
|
|
}) |
44
|
|
|
->flatMap(function (Collection $relatedTables) { |
45
|
|
|
return $relatedTables |
46
|
|
|
->mapWithKeys(function ($table, $key) use ($relatedTables) { |
47
|
|
|
$fields = $this->getFieldsForIncludedTable(Str::snake($table)); |
|
|
|
|
48
|
|
|
|
49
|
|
|
$fullRelationName = $relatedTables->slice(0, $key + 1)->implode('.'); |
50
|
|
|
|
51
|
|
|
if (empty($fields)) { |
52
|
|
|
return [$fullRelationName]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return [$fullRelationName => function ($query) use ($fields) { |
56
|
|
|
$query->select($fields); |
57
|
|
|
}]; |
58
|
|
|
}); |
59
|
|
|
}) |
60
|
|
|
->pipe(function (Collection $withs) { |
61
|
|
|
$this->with($withs->all()); |
|
|
|
|
62
|
|
|
}); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
protected function guardAgainstUnknownIncludes() |
66
|
|
|
{ |
67
|
|
|
$includes = $this->request->includes(); |
68
|
|
|
|
69
|
|
|
$diff = $includes->diff($this->allowedIncludes); |
70
|
|
|
|
71
|
|
|
if ($diff->count()) { |
72
|
|
|
throw InvalidIncludeQuery::includesNotAllowed($diff, $this->allowedIncludes); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
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: