1 | <?php |
||
23 | class QueryBuilder implements ArrayAccess |
||
24 | { |
||
25 | use FiltersQuery, |
||
26 | SortsQuery, |
||
27 | AddsIncludesToQuery, |
||
28 | AddsFieldsToQuery, |
||
29 | AppendsAttributesToResults, |
||
30 | ForwardsCalls; |
||
31 | |||
32 | /** @var QueryBuilderRequest */ |
||
33 | protected $request; |
||
34 | |||
35 | /** @var EloquentBuilder|Relation */ |
||
36 | protected $subject; |
||
37 | |||
38 | public function __construct($subject, ?Request $request = null) |
||
39 | { |
||
40 | $this->initializeSubject($subject) |
||
41 | ->initializeRequest($request ?? app(Request::class)); |
||
42 | } |
||
43 | |||
44 | protected function initializeSubject($subject): self |
||
45 | { |
||
46 | throw_unless( |
||
47 | $subject instanceof EloquentBuilder || $subject instanceof Relation, |
||
48 | InvalidSubject::make($subject) |
||
49 | ); |
||
50 | |||
51 | $this->subject = $subject; |
||
52 | |||
53 | return $this; |
||
54 | } |
||
55 | |||
56 | protected function initializeRequest(?Request $request = null): self |
||
57 | { |
||
58 | $this->request = $request |
||
59 | ? QueryBuilderRequest::fromRequest($request) |
||
60 | : app(QueryBuilderRequest::class); |
||
61 | |||
62 | return $this; |
||
63 | } |
||
64 | |||
65 | public function getEloquentBuilder(): EloquentBuilder |
||
66 | { |
||
67 | if ($this->subject instanceof EloquentBuilder) { |
||
68 | return $this->subject; |
||
69 | } |
||
70 | |||
71 | if ($this->subject instanceof Relation) { |
||
72 | return $this->subject->getQuery(); |
||
73 | } |
||
74 | |||
75 | throw InvalidSubject::make($this->subject); |
||
76 | } |
||
77 | |||
78 | public function getSubject() |
||
79 | { |
||
80 | return $this->subject; |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * @param EloquentBuilder|Relation|string $subject |
||
85 | * @param Request|null $request |
||
86 | * @return static |
||
87 | */ |
||
88 | public static function for($subject, ?Request $request = null): self |
||
96 | |||
97 | public function __call($name, $arguments) |
||
98 | { |
||
99 | $result = $this->forwardCallTo($this->subject, $name, $arguments); |
||
100 | |||
101 | if ($result === $this->subject) { |
||
115 | |||
116 | public function __get($name) |
||
120 | |||
121 | public function __set($name, $value) |
||
125 | |||
126 | public function offsetExists($offset) |
||
130 | |||
131 | public function offsetGet($offset) |
||
135 | |||
136 | public function offsetSet($offset, $value) |
||
140 | |||
141 | public function offsetUnset($offset) |
||
145 | } |
||
146 |