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