Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Repositories/Eloquent/EloquentRepository.php
7460 views
1
<?php
2
3
namespace Pterodactyl\Repositories\Eloquent;
4
5
use Illuminate\Http\Request;
6
use Webmozart\Assert\Assert;
7
use Illuminate\Support\Collection;
8
use Illuminate\Database\Eloquent\Model;
9
use Pterodactyl\Repositories\Repository;
10
use Illuminate\Database\Eloquent\Builder;
11
use Illuminate\Database\Query\Expression;
12
use Illuminate\Database\Eloquent\ModelNotFoundException;
13
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
14
use Pterodactyl\Contracts\Repository\RepositoryInterface;
15
use Pterodactyl\Exceptions\Model\DataValidationException;
16
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
17
18
abstract class EloquentRepository extends Repository implements RepositoryInterface
19
{
20
protected bool $useRequestFilters = false;
21
22
/**
23
* Determines if the repository function should use filters off the request object
24
* present when returning results. This allows repository methods to be called in API
25
* context's such that we can pass through ?filter[name]=Dane&sort=desc for example.
26
*/
27
public function usingRequestFilters(bool $usingFilters = true): self
28
{
29
$this->useRequestFilters = $usingFilters;
30
31
return $this;
32
}
33
34
/**
35
* Returns the request instance.
36
*/
37
protected function request(): Request
38
{
39
return $this->app->make(Request::class);
40
}
41
42
/**
43
* Paginate the response data based on the page para.
44
*/
45
protected function paginate(Builder $instance, int $default = 50): LengthAwarePaginator
46
{
47
if (!$this->useRequestFilters) {
48
return $instance->paginate($default);
49
}
50
51
return $instance->paginate($this->request()->query('per_page', $default));
52
}
53
54
/**
55
* Return an instance of the eloquent model bound to this
56
* repository instance.
57
*/
58
public function getModel(): Model
59
{
60
return $this->model;
61
}
62
63
/**
64
* Return an instance of the builder to use for this repository.
65
*/
66
public function getBuilder(): Builder
67
{
68
return $this->getModel()->newQuery();
69
}
70
71
/**
72
* Create a new record in the database and return the associated model.
73
*
74
* @throws DataValidationException
75
*/
76
public function create(array $fields, bool $validate = true, bool $force = false): Model|bool
77
{
78
$instance = $this->getBuilder()->newModelInstance();
79
($force) ? $instance->forceFill($fields) : $instance->fill($fields);
80
81
if (!$validate) {
82
$saved = $instance->skipValidation()->save();
83
} else {
84
if (!$saved = $instance->save()) {
85
throw new DataValidationException($instance->getValidator(), $instance);
86
}
87
}
88
89
return ($this->withFresh) ? $instance->fresh() : $saved;
90
}
91
92
/**
93
* Find a model that has the specific ID passed.
94
*
95
* @throws RecordNotFoundException
96
*/
97
public function find(int $id): Model
98
{
99
try {
100
return $this->getBuilder()->findOrFail($id, $this->getColumns());
101
} catch (ModelNotFoundException) {
102
throw new RecordNotFoundException();
103
}
104
}
105
106
/**
107
* Find a model matching an array of where clauses.
108
*/
109
public function findWhere(array $fields): Collection
110
{
111
return $this->getBuilder()->where($fields)->get($this->getColumns());
112
}
113
114
/**
115
* Find and return the first matching instance for the given fields.
116
*
117
* @throws RecordNotFoundException
118
*/
119
public function findFirstWhere(array $fields): Model
120
{
121
try {
122
return $this->getBuilder()->where($fields)->firstOrFail($this->getColumns());
123
} catch (ModelNotFoundException) {
124
throw new RecordNotFoundException();
125
}
126
}
127
128
/**
129
* Return a count of records matching the passed arguments.
130
*/
131
public function findCountWhere(array $fields): int
132
{
133
return $this->getBuilder()->where($fields)->count($this->getColumns());
134
}
135
136
/**
137
* Delete a given record from the database.
138
*/
139
public function delete(int $id, bool $destroy = false): int
140
{
141
return $this->deleteWhere(['id' => $id], $destroy);
142
}
143
144
/**
145
* Delete records matching the given attributes.
146
*/
147
public function deleteWhere(array $attributes, bool $force = false): int
148
{
149
$instance = $this->getBuilder()->where($attributes);
150
151
return ($force) ? $instance->forceDelete() : $instance->delete();
152
}
153
154
/**
155
* Update a given ID with the passed array of fields.
156
*
157
* @throws DataValidationException
158
* @throws RecordNotFoundException
159
*/
160
public function update(int $id, array $fields, bool $validate = true, bool $force = false): Model|bool
161
{
162
try {
163
$instance = $this->getBuilder()->where('id', $id)->firstOrFail();
164
} catch (ModelNotFoundException) {
165
throw new RecordNotFoundException();
166
}
167
168
($force) ? $instance->forceFill($fields) : $instance->fill($fields);
169
170
if (!$validate) {
171
$saved = $instance->skipValidation()->save();
172
} else {
173
if (!$saved = $instance->save()) {
174
throw new DataValidationException($instance->getValidator(), $instance);
175
}
176
}
177
178
return ($this->withFresh) ? $instance->fresh() : $saved;
179
}
180
181
/**
182
* Update a model using the attributes passed.
183
*/
184
public function updateWhere(array $attributes, array $values): int
185
{
186
return $this->getBuilder()->where($attributes)->update($values);
187
}
188
189
/**
190
* Perform a mass update where matching records are updated using whereIn.
191
* This does not perform any model data validation.
192
*/
193
public function updateWhereIn(string $column, array $values, array $fields): int
194
{
195
Assert::notEmpty($column, 'First argument passed to updateWhereIn must be a non-empty string.');
196
197
return $this->getBuilder()->whereIn($column, $values)->update($fields);
198
}
199
200
/**
201
* Update a record if it exists in the database, otherwise create it.
202
*
203
* @throws DataValidationException
204
* @throws RecordNotFoundException
205
*/
206
public function updateOrCreate(array $where, array $fields, bool $validate = true, bool $force = false): Model|bool
207
{
208
foreach ($where as $item) {
209
Assert::true(is_scalar($item) || is_null($item), 'First argument passed to updateOrCreate should be an array of scalar or null values, received an array value of %s.');
210
}
211
212
try {
213
$instance = $this->setColumns('id')->findFirstWhere($where);
214
} catch (RecordNotFoundException) {
215
return $this->create(array_merge($where, $fields), $validate, $force);
216
}
217
218
return $this->update($instance->id, $fields, $validate, $force);
219
}
220
221
/**
222
* Return all records associated with the given model.
223
*
224
* @deprecated Just use the model
225
*/
226
public function all(): Collection
227
{
228
return $this->getBuilder()->get($this->getColumns());
229
}
230
231
/**
232
* Return a paginated result set using a search term if set on the repository.
233
*/
234
public function paginated(int $perPage): LengthAwarePaginator
235
{
236
return $this->getBuilder()->paginate($perPage, $this->getColumns());
237
}
238
239
/**
240
* Insert a single or multiple records into the database at once skipping
241
* validation and mass assignment checking.
242
*/
243
public function insert(array $data): bool
244
{
245
return $this->getBuilder()->insert($data);
246
}
247
248
/**
249
* Insert multiple records into the database and ignore duplicates.
250
*/
251
public function insertIgnore(array $values): bool
252
{
253
if (empty($values)) {
254
return true;
255
}
256
257
foreach ($values as $key => $value) {
258
ksort($value);
259
$values[$key] = $value;
260
}
261
262
$bindings = array_values(array_filter(array_flatten($values, 1), function ($binding) {
263
return !$binding instanceof Expression;
264
}));
265
266
$grammar = $this->getBuilder()->toBase()->getGrammar();
267
$table = $grammar->wrapTable($this->getModel()->getTable());
268
$columns = $grammar->columnize(array_keys(reset($values)));
269
270
$parameters = collect($values)->map(function ($record) use ($grammar) {
271
return sprintf('(%s)', $grammar->parameterize($record));
272
})->implode(', ');
273
274
$statement = "insert ignore into $table ($columns) values $parameters";
275
276
return $this->getBuilder()->getConnection()->statement($statement, $bindings);
277
}
278
279
/**
280
* Get the amount of entries in the database.
281
*
282
* @deprecated just use the count method off a model
283
*/
284
public function count(): int
285
{
286
return $this->getBuilder()->count();
287
}
288
}
289
290