-
Notifications
You must be signed in to change notification settings - Fork 379
/
Model.php
304 lines (241 loc) · 7.77 KB
/
Model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Models;
use App\Exceptions\ModelNotSavedException;
use App\Libraries\MorphMap;
use App\Libraries\Transactions\AfterCommit;
use App\Libraries\Transactions\AfterRollback;
use App\Libraries\TransactionStateManager;
use App\Scopes\MacroableModelScope;
use App\Traits\Validatable;
use Exception;
use Illuminate\Database\ClassMorphViolationException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model as BaseModel;
abstract class Model extends BaseModel
{
use HasFactory, Traits\FasterAttributes, Validatable;
const MAX_FIELD_LENGTHS = [];
protected $connection = 'mysql';
protected $guarded = [];
protected $macros;
protected $primaryKeys;
public static function booted()
{
static::addGlobalScope(new MacroableModelScope());
}
public function getForeignKey()
{
if ($this->primaryKey === null || $this->primaryKey === 'id') {
return parent::getForeignKey();
}
return $this->primaryKey;
}
public function getKey()
{
return $this->getRawAttribute($this->primaryKey);
}
public function getMacros()
{
static $baseMacros = [
'getWithHasMore',
'last',
'realCount',
];
return array_merge($this->macros ?? [], $baseMacros);
}
public function getMorphClass()
{
$className = static::class;
$ret = MorphMap::getType($className);
if ($ret !== null) {
return $ret;
}
throw new ClassMorphViolationException($this);
}
/**
* Locks the current model for update with `select for update`.
*
* @return $this
*/
public function lockSelf()
{
return $this->lockForUpdate()->find($this->getKey());
}
public function macroGetWithHasMore()
{
return function ($query) {
$limit = $query->getQuery()->limit;
if ($limit === null) {
throw new Exception('"getWithHasMore" was called on query without "limit" specified');
}
$moreLimit = $limit + 1;
$result = $query->limit($moreLimit)->get();
$hasMore = $result->count() === $moreLimit;
if ($hasMore) {
$result->pop();
}
return [$result, $hasMore];
};
}
public function macroLast()
{
return function ($baseQuery, $column = null) {
$query = clone $baseQuery;
return $query->orderBy($column ?? $this->getKeyName(), 'DESC')->first();
};
}
public function macroRealCount()
{
return function ($baseQuery) {
$query = clone $baseQuery;
$query->unorder();
$query->getQuery()->offset = null;
$query->limit(null);
return min($query->count(), $GLOBALS['cfg']['osu']['pagination']['max_count']);
};
}
public function refresh()
{
if (method_exists($this, 'resetMemoized')) {
$this->resetMemoized();
}
return parent::refresh();
}
public function scopeReorderBy($query, $field, $order)
{
return $query->unorder()->orderBy($field, $order);
}
public function scopeOrderByField($query, $field, $ids)
{
$size = count($ids);
if ($size === 0) {
return;
}
$bind = implode(',', array_fill(0, $size, '?'));
$string = "FIELD({$field}, {$bind})";
$values = array_map('strval', $ids);
$query->orderByRaw($string, $values);
}
public function scopeNone($query)
{
$query->whereRaw('false');
}
public function scopeUnorder($query)
{
$query->getQuery()->orders = null;
return $query;
}
public function scopeWithPresent($query, $column)
{
$query->whereNotNull($column)->where($column, '<>', '');
}
/**
* Just like decrement but only works on saved instance instead of falling back to entire model
*/
public function decrementInstance()
{
if (!$this->exists) {
return false;
}
return $this->decrement(...func_get_args());
}
public function delete()
{
return $this->runAfterCommitWrapper(function () {
return parent::delete();
});
}
/**
* Just like increment but only works on saved instance instead of falling back to entire model
*/
public function incrementInstance()
{
if (!$this->exists) {
return false;
}
return $this->increment(...func_get_args());
}
public function save(array $options = [])
{
return $this->runAfterCommitWrapper(function () use ($options) {
return parent::save($options);
});
}
public function saveOrExplode($options = [])
{
return $this->getConnection()->transaction(function () use ($options) {
$result = $this->save($options);
if ($result === false) {
$errors = $this->validationErrors();
$message = $errors->isEmpty() ? 'failed saving model' : $errors->toSentence();
throw new ModelNotSavedException($message);
}
return $result;
});
}
public function dbName()
{
$connection = $this->connection ?? $GLOBALS['cfg']['database']['default'];
return $GLOBALS['cfg']['database']['connections'][$connection]['database'];
}
public function tableName(bool $includeDbPrefix = false)
{
return ($includeDbPrefix ? $this->dbName().'.' : '').$this->getTable();
}
// Allows save/update/delete to work with composite primary keys.
// Note this doesn't fix 'find' method and a bunch of other laravel things
// which rely on getKeyName and getKey (and they themselves are broken as well).
protected function setKeysForSaveQuery($query)
{
if (isset($this->primaryKeys)) {
foreach ($this->primaryKeys as $key) {
$query->where([$key => $this->original[$key] ?? null]);
}
return $query;
}
return parent::setKeysForSaveQuery($query);
}
// same deal with setKeysForSaveQuery but for select query
protected function setKeysForSelectQuery($query)
{
return $this->setKeysForSaveQuery($query);
}
protected function validateDbFieldLength(int $limit, string $dbField, ?string $checkField = null): void
{
if ($this->isDirty($dbField)) {
$this->validateFieldLength($limit, $dbField, $checkField);
}
}
protected function validateDbFieldLengths(): void
{
foreach (static::MAX_FIELD_LENGTHS as $field => $limit) {
$this->validateDbFieldLength($limit, $field, $field);
}
}
protected function validationErrorsTranslationPrefix(): string
{
return '';
}
private function enlistCallbacks($model, $connection)
{
$transaction = resolve(TransactionStateManager::class)->current($connection);
if ($model instanceof AfterCommit) {
$transaction->addCommittable($model);
}
if ($model instanceof AfterRollback) {
$transaction->addRollbackable($model);
}
return $transaction;
}
private function runAfterCommitWrapper(callable $fn)
{
$transaction = $this->enlistCallbacks($this, $this->connection);
$result = $fn();
if ($this instanceof AfterCommit && $transaction->isReal() === false) {
$transaction->commit();
}
return $result;
}
}