-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInteractsWithRelations.php
More file actions
581 lines (466 loc) · 15 KB
/
Copy pathInteractsWithRelations.php
File metadata and controls
581 lines (466 loc) · 15 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
<?php
declare(strict_types=1);
namespace Zero\Lib\Model\Concerns;
use RuntimeException;
use Zero\Lib\Database;
use Zero\Lib\DB\DBML;
use Zero\Lib\Model as BaseModel;
use Zero\Lib\Model\ModelQuery;
use Zero\Lib\Model\Relation;
use Zero\Lib\Model\Relations\BelongsTo;
use Zero\Lib\Model\Relations\BelongsToMany;
use Zero\Lib\Model\Relations\HasMany;
use Zero\Lib\Model\Relations\HasOne;
trait InteractsWithRelations
{
/**
* Start a new model query builder instance.
*/
public function newQuery(): ModelQuery
{
return $this->newModelBuilder($this->newBaseQuery());
}
/**
* Create a builder tied to the model class around the supplied DBML builder.
*/
protected function newModelBuilder(DBML $query): ModelQuery
{
return new ModelQuery(static::class, $query);
}
/**
* Create a base DBML query for the model's table.
*/
protected function newBaseQuery(): DBML
{
return DBML::table($this->getTable());
}
/**
* Define a has-one relationship.
*/
protected function hasOne(string $related, ?string $foreignKey = null, ?string $localKey = null): HasOne
{
$instance = $this->newRelatedInstance($related);
$foreignKey ??= $this->guessHasForeignKey();
$localKey ??= $this->getPrimaryKey();
$localValue = $this->getAttribute($localKey);
$baseQuery = $instance->newQuery();
$query = clone $baseQuery;
if ($localValue !== null) {
$query->where($foreignKey, $localValue);
} else {
$query->whereRaw('1 = 0');
}
$query->limit(1);
return new HasOne($query, $baseQuery, $this, $instance, $foreignKey, $localKey, $localValue);
}
/**
* Define a has-many relationship.
*/
protected function hasMany(string $related, ?string $foreignKey = null, ?string $localKey = null): HasMany
{
$instance = $this->newRelatedInstance($related);
$foreignKey ??= $this->guessHasForeignKey();
$localKey ??= $this->getPrimaryKey();
$localValue = $this->getAttribute($localKey);
$baseQuery = $instance->newQuery();
$query = clone $baseQuery;
if ($localValue !== null) {
$query->where($foreignKey, $localValue);
} else {
$query->whereRaw('1 = 0');
}
return new HasMany($query, $baseQuery, $this, $instance, $foreignKey, $localKey, $localValue);
}
/**
* Define a belongs-to relationship.
*/
protected function belongsTo(string $related, ?string $foreignKey = null, ?string $ownerKey = null): BelongsTo
{
$instance = $this->newRelatedInstance($related);
$foreignKey ??= $this->guessBelongsToForeignKey($related);
$ownerKey ??= $instance->getPrimaryKey();
$foreignValue = $this->getAttribute($foreignKey);
$baseQuery = $instance->newQuery();
$query = clone $baseQuery;
if ($foreignValue !== null) {
$query->where($ownerKey, $foreignValue);
} else {
$query->whereRaw('1 = 0');
}
$query->limit(1);
$relationName = $this->guessRelationName();
return new BelongsTo($query, $baseQuery, $this, $instance, $foreignKey, $ownerKey, $foreignValue, $relationName);
}
/**
* Define a many-to-many relationship.
*/
protected function belongsToMany(
string $related,
?string $table = null,
?string $foreignPivotKey = null,
?string $relatedPivotKey = null,
?string $parentKey = null,
?string $relatedKey = null
): BelongsToMany {
$instance = $this->newRelatedInstance($related);
$relationName = $this->guessRelationName();
$table ??= $this->guessBelongsToManyPivotTable($instance);
$foreignPivotKey ??= $this->guessBelongsToManyForeignKey();
$relatedPivotKey ??= $instance->guessBelongsToManyForeignKey();
$parentKey ??= $this->getPrimaryKey();
$relatedKey ??= $instance->getPrimaryKey();
$parentValue = $this->getAttribute($parentKey);
$baseQuery = $instance->newQuery()
->select($instance->getTable() . '.*')
->join(
$table,
$instance->getTable() . '.' . $relatedKey,
'=',
$table . '.' . $relatedPivotKey
);
$query = clone $baseQuery;
if ($parentValue !== null) {
$query->where($table . '.' . $foreignPivotKey, $parentValue);
} else {
$query->whereRaw('1 = 0');
}
return new BelongsToMany(
$query,
$baseQuery,
$this,
$instance,
$table,
$foreignPivotKey,
$relatedPivotKey,
$parentKey,
$relatedKey,
$parentValue,
$relationName
);
}
/**
* Instantiate a related model instance.
*/
protected function newRelatedInstance(string $related): BaseModel
{
/** @var BaseModel $instance */
$instance = new $related();
return $instance;
}
/**
* Resolve the database connection name for the model.
*/
public function getConnectionName(): ?string
{
return $this->connection ?? null;
}
/**
* Execute the callback with this model's connection active on the stack.
*/
public function runOnConnection(callable $callback): mixed
{
$name = $this->getConnectionName();
if ($name === null) {
return $callback();
}
return Database::withConnection($name, $callback);
}
/**
* Resolve the table name, defaulting to a snake_cased plural of the class.
*/
public function getTable(): string
{
if ($this->table !== null) {
return $this->table;
}
return $this->table = $this->guessTableName();
}
/**
* Determine if the given attribute is mass assignable.
*/
protected function isFillable(string $key): bool
{
if ($this->fillable === []) {
return true;
}
return in_array($key, $this->fillable, true);
}
/**
* Persist a new record for the model.
*/
protected function performInsert(): bool
{
$this->fireHook('beforeCreate');
$this->fireHook('beforeSave');
$this->ensureUuidKey();
$attributes = $this->attributes;
$this->applyTimestampsForInsert($attributes);
$id = $this->runOnConnection(fn () => $this->newBaseQuery()->insert($attributes));
$this->attributes = array_merge($this->attributes, $attributes);
if ($this->incrementing && $this->primaryKey && ! isset($this->attributes[$this->primaryKey])) {
$this->attributes[$this->primaryKey] = $id;
}
$this->exists = true;
$this->syncOriginal();
$this->fireHook('afterCreate');
$this->fireHook('afterSave');
return true;
}
/**
* Update the database record with dirty attributes.
*/
protected function performUpdate(): bool
{
$dirty = $this->getDirty();
if ($dirty === []) {
return true;
}
$this->fireHook('beforeUpdate');
$this->fireHook('beforeSave');
$this->applyTimestampsForUpdate($dirty);
if (array_key_exists($this->primaryKey, $dirty)) {
unset($dirty[$this->primaryKey]);
}
if ($dirty === []) {
$this->fireHook('afterUpdate');
$this->fireHook('afterSave');
return true;
}
$key = $this->getKey();
if ($key === null) {
throw new RuntimeException('Cannot update a model without a primary key value.');
}
$affected = $this->runOnConnection(fn () => $this->newBaseQuery()
->where($this->getPrimaryKey(), $key)
->update($dirty));
if ($affected) {
$this->forceFill($dirty);
$this->syncOriginal();
$this->fireHook('afterUpdate');
$this->fireHook('afterSave');
}
return (bool) $affected;
}
/**
* Perform the soft delete update.
*/
protected function performSoftDelete(): bool
{
$key = $this->getKey();
if ($key === null) {
throw new RuntimeException('Cannot delete a model without a primary key value.');
}
$timestamp = $this->freshTimestampString();
$columns = [
$this->getDeletedAtColumn() => $timestamp,
];
if ($this->usesTimestamps()) {
$columns[$this->updatedAtColumn] = $timestamp;
}
$this->fireHook('beforeDelete');
$deleted = $this->runOnConnection(fn () => $this->newBaseQuery()
->where($this->getPrimaryKey(), $key)
->update($columns));
if ($deleted) {
$this->forceFill($columns);
$this->fireHook('afterDelete');
$this->syncOriginal();
}
return (bool) $deleted;
}
/**
* Perform a hard delete against the underlying table.
*/
protected function performHardDelete(): bool
{
$key = $this->getKey();
if ($key === null) {
throw new RuntimeException('Cannot delete a model without a primary key value.');
}
$this->fireHook('beforeDelete');
$deleted = $this->runOnConnection(fn () => $this->newBaseQuery()
->where($this->getPrimaryKey(), $key)
->delete());
if ($deleted) {
$this->exists = false;
if ($this->usesSoftDeletes()) {
$this->attributes[$this->getDeletedAtColumn()] = null;
}
$this->fireHook('afterDelete');
$this->syncOriginal();
}
return (bool) $deleted;
}
/**
* Apply timestamp columns when inserting rows.
*/
protected function applyTimestampsForInsert(array &$attributes): void
{
if (! $this->usesTimestamps()) {
return;
}
$timestamp = $this->freshTimestampString();
$attributes[$this->createdAtColumn] = $attributes[$this->createdAtColumn] ?? $timestamp;
$attributes[$this->updatedAtColumn] = $attributes[$this->updatedAtColumn] ?? $timestamp;
}
/**
* Apply timestamp columns when updating rows.
*/
protected function applyTimestampsForUpdate(array &$attributes): void
{
if (! $this->usesTimestamps()) {
return;
}
$attributes[$this->updatedAtColumn] = $this->freshTimestampString();
}
/**
* Determine whether timestamps are enabled for the model.
*/
protected function usesTimestamps(): bool
{
return $this->timestamps;
}
/**
* Generate a timestamp string for persistence.
*/
protected function freshTimestampString(): string
{
return date('Y-m-d H:i:s');
}
/**
* Gather the attributes that have been modified from their original values.
*
* @return array<string, mixed>
*/
protected function getDirty(): array
{
$dirty = [];
foreach ($this->attributes as $key => $value) {
if (! array_key_exists($key, $this->original) || $value !== $this->original[$key]) {
$dirty[$key] = $value;
}
}
return $dirty;
}
/**
* Snapshot the current attributes as the original state.
*/
protected function syncOriginal(): void
{
$this->original = $this->attributes;
}
/**
* Load a relationship value, caching the result on the model.
*/
protected function getRelationValue(string $key): mixed
{
if ($this->relationLoaded($key)) {
return $this->relations[$key];
}
if (! method_exists($this, $key)) {
return null;
}
$relation = $this->{$key}();
if ($relation instanceof Relation) {
$results = $relation->getResults();
$this->setRelation($key, $results);
return $results;
}
return $relation;
}
/**
* Derive a table name from the class name.
*/
protected function guessTableName(): string
{
$base = $this->classBaseName();
$snake = $this->snakeCase($base);
if (! str_ends_with($snake, 's')) {
$snake .= 's';
}
return $snake;
}
/**
* Retrieve the class base name without namespaces.
*/
protected function classBaseName(): string
{
$class = static::class;
if (($pos = strrpos($class, '\\')) !== false) {
return substr($class, $pos + 1);
}
return $class;
}
/**
* Convert a string to snake_case.
*/
protected function snakeCase(string $value): string
{
$snake = strtolower((string) preg_replace('/(?<!^)[A-Z]/', '_$0', $value));
return str_replace(' ', '_', $snake);
}
/**
* Determine the name of the relationship method that invoked a relation helper.
*/
protected function guessRelationName(): ?string
{
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($trace as $frame) {
$method = $frame['function'] ?? null;
$class = $frame['class'] ?? null;
if (!is_string($method) || $method === '__get') {
continue;
}
if ($class === self::class) {
continue;
}
return $method;
}
return null;
}
/**
* Guess the foreign key name for a belongsTo relationship.
*/
protected function guessBelongsToForeignKey(string $related): string
{
$relationName = $this->guessRelationName();
if ($relationName) {
return $this->snakeCase($relationName) . '_id';
}
$base = (new $related())->classBaseName();
return $this->snakeCase($base) . '_id';
}
/**
* Guess the foreign key name for has-one or has-many relationships.
*/
protected function guessHasForeignKey(): string
{
return $this->snakeCase($this->classBaseName()) . '_id';
}
/**
* Determine the default pivot table name for a many-to-many relationship.
*/
protected function guessBelongsToManyPivotTable(BaseModel $related): string
{
$segments = [
$this->pivotSegment(),
$related->pivotSegment(),
];
sort($segments, SORT_STRING);
if (isset($segments[1])) {
$segments[1] = $this->pluralizeTableName($segments[1]);
}
return implode('_', $segments);
}
protected function pivotSegment(): string
{
return $this->singularTableName($this->getTable());
}
/**
* Guess the foreign key column name for a many-to-many pivot table.
*/
protected function guessBelongsToManyForeignKey(): string
{
return $this->snakeCase($this->classBaseName()) . '_id';
}
}