1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use Spatie\QueryBuilder\Exceptions\InvalidAppendQuery; |
9
|
|
|
|
10
|
|
|
trait AppendsAttributesToResults |
11
|
|
|
{ |
12
|
|
|
/** @var \Illuminate\Support\Collection */ |
13
|
|
|
protected $allowedAppends; |
14
|
|
|
|
15
|
|
|
public function allowedAppends($appends): self |
16
|
|
|
{ |
17
|
|
|
$appends = is_array($appends) ? $appends : func_get_args(); |
18
|
|
|
|
19
|
|
|
$this->allowedAppends = collect($appends); |
20
|
|
|
|
21
|
|
|
$this->ensureAllAppendsExist(); |
22
|
|
|
|
23
|
|
|
return $this; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
protected function addAppendsToResults(Collection $results) |
27
|
|
|
{ |
28
|
|
|
$appends = $this->request->appends(); |
|
|
|
|
29
|
|
|
return $results->each(function($item) use($appends) { |
30
|
|
|
$appends->each(function($append) use($item) { |
31
|
|
|
if(Str::contains($append, '.')) { |
32
|
|
|
$nestedAppends = collect(explode('.', $append)); |
33
|
|
|
$relation = $nestedAppends->shift(); |
34
|
|
|
|
35
|
|
|
$this->appendLoop($item, $relation, $nestedAppends); |
36
|
|
|
} else { |
37
|
|
|
$item->append($append); |
38
|
|
|
} |
39
|
|
|
}); |
40
|
|
|
}); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
private function appendLoop($item, string $relation, Collection $nestedAppends) { |
44
|
|
|
if($item->relationLoaded($relation)) { |
45
|
|
|
if($nestedAppends->count() === 1) { |
46
|
|
|
$sub = $nestedAppends->first(); |
47
|
|
|
if($item->$relation instanceof \Illuminate\Database\Eloquent\Collection) { |
48
|
|
|
$item->$relation->each(function($model) use($sub) { |
49
|
|
|
$model->append($sub); |
50
|
|
|
}); |
51
|
|
|
} else { |
52
|
|
|
$item->$relation->append($sub); |
53
|
|
|
} |
54
|
|
|
} else { |
55
|
|
|
$sub = $nestedAppends->shift(); |
56
|
|
|
$this->appendLoop($item->$relation, $sub, $nestedAppends); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected function ensureAllAppendsExist() { |
62
|
|
|
$appends = $this->request->appends(); |
63
|
|
|
|
64
|
|
|
$diff = $appends->diff($this->allowedAppends); |
65
|
|
|
|
66
|
|
|
if ($diff->count()) { |
67
|
|
|
throw InvalidAppendQuery::appendsNotAllowed($diff, $this->allowedAppends); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
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: