-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModelQuery.php
More file actions
810 lines (637 loc) · 21.4 KB
/
Copy pathModelQuery.php
File metadata and controls
810 lines (637 loc) · 21.4 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<?php
declare(strict_types=1);
namespace Zero\Lib\Model;
use Closure;
use InvalidArgumentException;
use Zero\Lib\Database;
use Zero\Lib\DB\DBML;
use Zero\Lib\DB\DBMLExpression;
use Zero\Lib\Model as BaseModel;
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;
use Zero\Lib\Support\Paginator;
/**
* Model-aware wrapper around DBML providing hydrated results.
*/
class ModelQuery
{
protected bool $usesSoftDeletes = false;
protected string $deletedAtColumn = 'deleted_at';
protected bool $includeTrashed = false;
protected bool $onlyTrashed = false;
protected ?string $connection = null;
/** @var array<string, Closure|null> */
protected array $eagerLoads = [];
/** @var array<string, string> relation => alias */
protected array $relationCounts = [];
public function __construct(
protected string $modelClass,
protected DBML $builder
) {
/** @var BaseModel $model */
$model = new $this->modelClass();
$this->usesSoftDeletes = $model->usesSoftDeletes();
$this->deletedAtColumn = $model->getDeletedAtColumn();
$this->connection = $model->getConnectionName();
}
/**
* Execute the callback with this query's connection active on the stack.
*/
protected function runOnConnection(callable $callback): mixed
{
if ($this->connection === null) {
return $callback();
}
return Database::withConnection($this->connection, $callback);
}
public function __clone(): void
{
$this->builder = clone $this->builder;
}
/**
* Proxy builder calls while maintaining fluency.
*/
public function __call(string $name, array $arguments): mixed
{
$result = $this->builder->{$name}(...$arguments);
if ($result instanceof DBML) {
$this->builder = $result;
return $this;
}
return $result;
}
public function with(array|string $relations): self
{
foreach ($this->normalizeEagerRelations($relations) as $name => $constraint) {
$this->eagerLoads[$name] = $constraint;
}
return $this;
}
public function withCount(array|string $relations): self
{
foreach ($this->normalizeCountRelations($relations) as $name => $alias) {
$this->relationCounts[$name] = $alias;
}
return $this;
}
public function whereHas(string $relation, ?Closure $callback = null): self
{
return $this->addWhereHas($relation, $callback, false, 'AND');
}
public function orWhereHas(string $relation, ?Closure $callback = null): self
{
return $this->addWhereHas($relation, $callback, false, 'OR');
}
public function whereDoesntHave(string $relation, ?Closure $callback = null): self
{
return $this->addWhereHas($relation, $callback, true, 'AND');
}
public function orWhereDoesntHave(string $relation, ?Closure $callback = null): self
{
return $this->addWhereHas($relation, $callback, true, 'OR');
}
public function withTrashed(): self
{
if (! $this->usesSoftDeletes) {
return $this;
}
$this->includeTrashed = true;
$this->onlyTrashed = false;
return $this;
}
public function onlyTrashed(): self
{
if (! $this->usesSoftDeletes) {
return $this;
}
$this->includeTrashed = true;
$this->onlyTrashed = true;
return $this;
}
public function withoutTrashed(): self
{
if (! $this->usesSoftDeletes) {
return $this;
}
$this->includeTrashed = false;
$this->onlyTrashed = false;
return $this;
}
/**
* Execute the query and hydrate an array of models.
*
* @return BaseModel[]
*/
public function get(array|string|DBMLExpression $columns = []): array
{
$records = $this->runOnConnection(fn () => $this->preparedBuilder()->get($columns));
$models = array_map(fn (array $attributes) => $this->newModel($attributes, true), $records);
return $this->hydrateModels($models);
}
/**
* Fetch the first result or null.
*/
public function first(array|string|DBMLExpression $columns = []): ?BaseModel
{
$record = $this->runOnConnection(fn () => $this->preparedBuilder()->first($columns));
if ($record === null) {
return null;
}
return $this->hydrateModel($this->newModel($record, true));
}
/**
* Update the first matching model or create a new instance with the given values.
*/
public function updateOrCreate(array $attributes, array $values = []): BaseModel
{
$record = $this->runOnConnection(fn () => $this->preparedBuilder()->updateOrCreate($attributes, $values));
/** @var BaseModel $model */
$model = $this->hydrateModel($this->newModel($record, true));
return $model;
}
/**
* Retrieve the first matching model or create a new instance.
*/
public function findOrCreate(array $attributes, array $values = []): BaseModel
{
$record = $this->runOnConnection(fn () => $this->preparedBuilder()->findOrCreate($attributes, $values));
/** @var BaseModel $model */
$model = $this->hydrateModel($this->newModel($record, true));
return $model;
}
/**
* Retrieve a model by its primary key.
*/
public function find(mixed $id, array|string|DBMLExpression $columns = []): ?BaseModel
{
$clone = clone $this;
$clone->builder = $clone->builder->where($clone->primaryKey(), $id)->limit(1);
return $clone->first($columns);
}
/**
* Return the underlying DBML builder instance with applied scopes.
*/
public function toBase(): DBML
{
return $this->preparedBuilder();
}
/**
* Retrieve the compiled SQL string for the current query.
*/
public function toSql(): string
{
return $this->preparedBuilder()->toSql();
}
/**
* Retrieve the parameter bindings for the current query.
*/
public function getBindings(): array
{
return $this->preparedBuilder()->getBindings();
}
/**
* Count the total results for the current query.
*/
public function count(string $column = '*'): int
{
return $this->runOnConnection(fn () => $this->preparedBuilder()->count($column));
}
/**
* Paginate the model results.
*/
public function paginate(int $perPage = 15, int $page = 1): Paginator
{
$paginator = $this->runOnConnection(fn () => $this->preparedBuilder()->paginate($perPage, $page));
$items = array_map(fn (array $attributes) => $this->newModel($attributes, true), $paginator->items());
$items = $this->hydrateModels($items);
return new Paginator($items, $paginator->total(), $paginator->perPage(), $paginator->currentPage());
}
/**
* Simple pagination without executing a count query.
*/
public function simplePaginate(int $perPage = 15, int $page = 1): Paginator
{
$paginator = $this->runOnConnection(fn () => $this->preparedBuilder()->simplePaginate($perPage, $page));
$items = array_map(fn (array $attributes) => $this->newModel($attributes, true), $paginator->items());
$items = $this->hydrateModels($items);
return new Paginator($items, $paginator->total(), $paginator->perPage(), $paginator->currentPage());
}
/**
* Determine whether any results exist for the query.
*/
public function exists(): bool
{
return $this->runOnConnection(fn () => $this->preparedBuilder()->exists());
}
/**
* Retrieve a list of column values.
*/
public function pluck(string $column, ?string $key = null): array
{
return $this->runOnConnection(fn () => $this->preparedBuilder()->pluck($column, $key));
}
/**
* Retrieve a single column value from the first row.
*/
public function value(string $column): mixed
{
return $this->runOnConnection(fn () => $this->preparedBuilder()->value($column));
}
/**
* Delete the records matching the current query constraints.
*/
public function delete(): int
{
if (! $this->usesSoftDeletes) {
return $this->runOnConnection(fn () => $this->preparedBuilder()->delete());
}
$deleted = 0;
foreach ($this->get() as $model) {
if ($model->delete()) {
$deleted++;
}
}
return $deleted;
}
/**
* Force delete records ignoring soft delete semantics.
*/
public function forceDelete(): int
{
if (! $this->usesSoftDeletes) {
return $this->runOnConnection(fn () => $this->preparedBuilder()->delete());
}
$deleted = 0;
$clone = clone $this;
$clone->withTrashed();
foreach ($clone->get() as $model) {
if ($model->forceDelete()) {
$deleted++;
}
}
return $deleted;
}
/**
* Hydrate a new model instance with the given attributes.
*/
protected function newModel(array $attributes, bool $exists): BaseModel
{
/** @var BaseModel $model */
$model = new $this->modelClass($attributes, $exists);
return $model;
}
protected function newModelInstance(): BaseModel
{
/** @var BaseModel $model */
$model = new $this->modelClass();
return $model;
}
protected function primaryKey(): string
{
$model = new $this->modelClass();
return $model->getPrimaryKey();
}
/**
* @param array<string, mixed>|string $relations
* @return array<string, Closure|null>
*/
protected function normalizeEagerRelations(array|string $relations): array
{
if (is_string($relations)) {
$relations = [$relations];
}
$normalized = [];
foreach ($relations as $key => $value) {
if (is_int($key)) {
$relation = trim((string) $value);
$constraint = null;
} else {
$relation = trim((string) $key);
$constraint = $value instanceof Closure ? $value : null;
}
if ($relation === '') {
continue;
}
$normalized[$relation] = $constraint;
}
return $normalized;
}
/**
* @param array<int|string, mixed>|string $relations
* @return array<string, string>
*/
protected function normalizeCountRelations(array|string $relations): array
{
if (is_string($relations)) {
$relations = [$relations];
}
$normalized = [];
foreach ($relations as $key => $value) {
if (is_int($key)) {
$expression = trim((string) $value);
if ($expression === '') {
continue;
}
[$relation, $alias] = $this->parseCountExpression($expression);
} else {
$relation = trim((string) $key);
if ($relation === '') {
continue;
}
$alias = is_string($value) && $value !== ''
? trim($value)
: $this->guessCountAlias($relation);
}
if ($relation === '') {
continue;
}
if ($alias === '') {
$alias = $this->guessCountAlias($relation);
}
$normalized[$relation] = $alias;
}
return $normalized;
}
/**
* @return array{0: string, 1: string}
*/
protected function parseCountExpression(string $expression): array
{
$expression = trim($expression);
if ($expression === '') {
return ['', ''];
}
if (stripos($expression, ' as ') !== false) {
[$name, $alias] = preg_split('/\s+as\s+/i', $expression, 2);
$name = trim((string) ($name ?? ''));
$alias = trim((string) ($alias ?? ''));
if ($alias === '') {
$alias = $this->guessCountAlias($name);
}
return [$name, $alias];
}
return [$expression, $this->guessCountAlias($expression)];
}
protected function guessCountAlias(string $relation): string
{
$relation = trim($relation);
if ($relation === '') {
return '';
}
return str_replace('.', '_', $relation) . '_count';
}
protected function addWhereHas(string $relation, ?Closure $callback, bool $not, string $boolean): self
{
[$name, $nested] = $this->parseRelationSegments($relation);
$model = $this->newModelInstance();
if (!method_exists($model, $name)) {
throw new InvalidArgumentException(sprintf(
'Relation [%s] is not defined on model [%s].',
$name,
$this->modelClass
));
}
$relationInstance = $model->{$name}();
if (! $relationInstance instanceof Relation) {
throw new InvalidArgumentException(sprintf(
'Method [%s] on model [%s] must return a relation instance.',
$name,
$this->modelClass
));
}
if ($nested !== null) {
$nestedCallback = function (ModelQuery $query) use ($nested, $callback): void {
$query->whereHas($nested, $callback);
};
} else {
$nestedCallback = $callback;
}
$subQuery = $this->buildRelationExistenceQuery($relationInstance, $nestedCallback);
if ($not) {
$this->builder = $this->builder->whereNotExists($subQuery, $boolean);
} else {
$this->builder = $this->builder->whereExists($subQuery, $boolean);
}
return $this;
}
/**
* @return array{0: string, 1: ?string}
*/
protected function parseRelationSegments(string $relation): array
{
$relation = trim($relation);
if ($relation === '') {
throw new InvalidArgumentException('Relation name cannot be empty.');
}
if (!str_contains($relation, '.')) {
return [$relation, null];
}
$segments = explode('.', $relation, 2);
return [$segments[0], $segments[1] ?? null];
}
protected function buildRelationExistenceQuery(Relation $relation, ?Closure $callback): DBML
{
$relatedQuery = $relation->newExistenceQuery();
if ($callback !== null) {
$callback($relatedQuery);
}
$builder = $relatedQuery->toBase();
$builder->select(DBML::raw('1'));
if ($relation instanceof HasMany || $relation instanceof HasOne) {
$parentColumn = $this->qualifyColumn($relation->getLocalKeyName());
$relatedColumn = $this->qualifyRelationColumn($relation->getRelated(), $relation->getForeignKeyName());
$builder->whereRaw(sprintf('%s = %s', $relatedColumn, $parentColumn));
return $builder;
}
if ($relation instanceof BelongsTo) {
$parentColumn = $this->qualifyColumn($relation->getForeignKeyName());
$relatedColumn = $this->qualifyRelationColumn($relation->getRelated(), $relation->getOwnerKeyName());
$builder->whereRaw(sprintf('%s = %s', $relatedColumn, $parentColumn));
return $builder;
}
if ($relation instanceof BelongsToMany) {
$parentColumn = $this->qualifyColumn($relation->getParentKeyName());
$pivotForeign = $relation->getPivotTable() . '.' . $relation->getForeignPivotKeyName();
$builder->whereRaw(sprintf('%s = %s', $pivotForeign, $parentColumn));
return $builder;
}
throw new InvalidArgumentException(sprintf(
'Relation type [%s] is not supported for whereHas queries.',
$relation::class
));
}
protected function qualifyColumn(string $column): string
{
$column = trim($column);
if ($column === '') {
throw new InvalidArgumentException('Column name cannot be empty.');
}
if (str_contains($column, '.')) {
return $column;
}
$table = $this->newModelInstance()->getTable();
return $table . '.' . $column;
}
protected function qualifyRelationColumn(BaseModel $model, string $column): string
{
$column = trim($column);
if ($column === '') {
throw new InvalidArgumentException('Column name cannot be empty.');
}
if (str_contains($column, '.')) {
return $column;
}
return $model->getTable() . '.' . $column;
}
/**
* @param BaseModel[] $models
* @return BaseModel[]
*/
protected function hydrateModels(array $models): array
{
if ($models === []) {
return $models;
}
$this->loadRelations($models);
$this->appendRelationCounts($models);
return $models;
}
protected function hydrateModel(?BaseModel $model): ?BaseModel
{
if ($model === null) {
return null;
}
$this->loadRelations([$model]);
$this->appendRelationCounts([$model]);
return $model;
}
/**
* @param BaseModel[] $models
*/
protected function loadRelations(array $models): void
{
if ($this->eagerLoads === []) {
return;
}
foreach ($this->eagerLoads as $relation => $constraint) {
foreach ($models as $model) {
if (! $model instanceof BaseModel) {
continue;
}
$this->loadRelation($model, $relation, $constraint);
}
}
}
/**
* @param BaseModel[] $models
*/
protected function appendRelationCounts(array $models): void
{
if ($this->relationCounts === []) {
return;
}
foreach ($this->relationCounts as $relation => $alias) {
$alias = $alias === '' ? $this->guessCountAlias($relation) : $alias;
foreach ($models as $model) {
if (! $model instanceof BaseModel) {
continue;
}
$count = $this->resolveRelationCount($model, $relation);
$model->{$alias} = $count;
}
}
}
protected function loadRelation(BaseModel $model, string $relation, ?Closure $constraint = null): void
{
$relation = trim($relation);
if ($relation === '') {
return;
}
$segments = explode('.', $relation);
$name = array_shift($segments);
if ($name === null || $name === '') {
return;
}
$results = null;
if ($model->relationLoaded($name)) {
$results = $model->getRelation($name);
} elseif (method_exists($model, $name)) {
$relationInstance = $model->{$name}();
if ($relationInstance instanceof Relation) {
if ($constraint instanceof Closure) {
$constraint($relationInstance->getQuery());
}
$results = $relationInstance->getResults();
} else {
$results = $relationInstance;
}
$model->setRelation($name, $results);
}
if ($segments === []) {
return;
}
if ($results instanceof BaseModel) {
$this->loadRelation($results, implode('.', $segments), null);
return;
}
if (is_iterable($results)) {
$next = implode('.', $segments);
foreach ($results as $related) {
if ($related instanceof BaseModel) {
$this->loadRelation($related, $next, null);
}
}
}
}
protected function resolveRelationCount(BaseModel $model, string $relation): int
{
$relation = trim($relation);
if ($relation === '') {
return 0;
}
$name = explode('.', $relation)[0];
if ($name === '') {
return 0;
}
if (! $model->relationLoaded($name)) {
$this->loadRelation($model, $name, null);
}
$value = $model->getRelation($name);
if ($value instanceof BaseModel) {
return 1;
}
if ($value === null) {
return 0;
}
if (is_array($value)) {
return count($value);
}
if ($value instanceof \Countable) {
return count($value);
}
if ($value instanceof \Traversable) {
return iterator_count($value);
}
return (int) $value;
}
/**
* Clone the underlying builder and apply soft delete constraints.
*/
protected function preparedBuilder(): DBML
{
$builder = clone $this->builder;
if (! $this->usesSoftDeletes) {
return $builder;
}
if ($this->onlyTrashed) {
return $builder->whereNotNull($this->deletedAtColumn);
}
if ($this->includeTrashed) {
return $builder;
}
return $builder->whereNull($this->deletedAtColumn);
}
}