Repository navigation
Expand file tree
/
Copy pathCollection.php
More file actions
executable file
·736 lines (625 loc) · 19.8 KB
/
Copy pathCollection.php
File metadata and controls
executable file
·736 lines (625 loc) · 19.8 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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Database\Model;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection as BaseCollection;
use Hyperf\Collection\Enumerable;
use Hyperf\Contract\Arrayable;
use Hyperf\Contract\CompressInterface;
use Hyperf\Contract\UnCompressInterface;
use Hyperf\Database\Model\Relations\Relation;
use Hyperf\Stringable\Str;
use RuntimeException;
use function Hyperf\Collection\head;
use function Hyperf\Support\value;
/**
* @template TKey of array-key
* @template TModel of \Hyperf\Database\Model\Model
*
* @extends BaseCollection<TKey, TModel>
*/
class Collection extends BaseCollection implements CompressInterface
{
/**
* Find a model in the collection by key.
*
* @template TFindDefault
*
* @param mixed $key
* @param TFindDefault $default
* @return ($key is array ? static : TFindDefault|TModel)
*/
public function find($key, $default = null)
{
if ($key instanceof Model) {
$key = $key->getKey();
}
if ($key instanceof Arrayable) {
$key = $key->toArray();
}
if (is_array($key)) {
if ($this->isEmpty()) {
return new static();
}
return $this->whereIn($this->first()->getKeyName(), $key);
}
return Arr::first($this->items, function ($model) use ($key) {
return $model->getKey() === $key;
}, $default);
}
/**
* Find a model in the collection by key or throw an exception.
*
* @return ($key is array ? static : TModel)
*
* @throws ModelNotFoundException
*/
public function findOrFail(mixed $key)
{
$result = $this->find($key);
if (is_array($key) && count($result) === count(array_unique($key))) {
return $result;
}
if (! is_array($key) && ! is_null($result)) {
return $result;
}
$exception = new ModelNotFoundException();
if (! $model = head($this->items)) {
throw $exception;
}
$ids = is_array($key) ? array_diff($key, $result->modelKeys()) : $key;
$exception->setModel(get_class($model), $ids);
throw $exception;
}
/**
* Load a set of relationships onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function load($relations)
{
if ($this->isNotEmpty()) {
if (is_string($relations)) {
$relations = func_get_args();
}
$query = $this->first()->newQueryWithoutRelationships()->with($relations);
$this->items = $query->eagerLoadRelations($this->items);
}
return $this;
}
/**
* Load a set of aggregations over relationship's column onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadAggregate(array|string $relations, string $column, ?string $function = null): static
{
if ($this->isEmpty()) {
return $this;
}
$models = $this->first()->newModelQuery()
->whereKey($this->modelKeys())
->select($this->first()->getKeyName())
->withAggregate($relations, $column, $function)
->get()
->keyBy($this->first()->getKeyName());
$attributes = Arr::except(
array_keys($models->first()->getAttributes()),
$models->first()->getKeyName()
);
$this->each(function ($model) use ($models, $attributes) {
$extraAttributes = Arr::only($models->get($model->getKey())->getAttributes(), $attributes);
$model->forceFill($extraAttributes)
->syncOriginalAttributes($attributes)
->mergeCasts($models->get($model->getKey())->getCasts());
});
return $this;
}
/**
* Load a set of relationship's max column values onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadMax(array|string $relations, string $column): static
{
return $this->loadAggregate($relations, $column, 'max');
}
/**
* Load a set of relationship's min column values onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadMin(array|string $relations, string $column): static
{
return $this->loadAggregate($relations, $column, 'min');
}
/**
* Load a set of relationship's column summations onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadSum(array|string $relations, string $column): static
{
return $this->loadAggregate($relations, $column, 'sum');
}
/**
* Load a set of relationship's average column values onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadAvg(array|string $relations, string $column): static
{
return $this->loadAggregate($relations, $column, 'avg');
}
/**
* Load a set of relationship counts onto the collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadCount($relations)
{
if ($this->isEmpty()) {
return $this;
}
$models = $this->first()->newModelQuery()
->whereKey($this->modelKeys())
->select($this->first()->getKeyName())
->withCount(...func_get_args())
->get();
$attributes = Arr::except(
array_keys($models->first()->getAttributes()),
$models->first()->getKeyName()
);
$models->each(function ($model) use ($attributes) {
$this->find($model->getKey())->forceFill(
Arr::only($model->getAttributes(), $attributes)
)->syncOriginalAttributes($attributes);
});
return $this;
}
/**
* Load a set of relationships onto the collection if they are not already eager loaded.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadMissing($relations)
{
if (is_string($relations)) {
$relations = func_get_args();
}
foreach ($relations as $key => $value) {
if (is_numeric($key)) {
$key = $value;
}
$segments = explode('.', explode(':', $key)[0]);
if (Str::contains($key, ':')) {
$segments[count($segments) - 1] .= ':' . explode(':', $key)[1];
}
$path = array_combine($segments, $segments);
if (is_callable($value)) {
$path[end($segments)] = $value;
}
$this->loadMissingRelation($this, $path);
}
return $this;
}
/**
* Load a set of relationships onto the mixed relationship collection.
*
* @param string $relation
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadMorph($relation, $relations)
{
$this->pluck($relation)
->filter()
->groupBy(function ($model) {
return get_class($model);
})
->filter(function ($models, $className) use ($relations) {
return Arr::has($relations, $className);
})
->each(function ($models, $className) use ($relations) {
$className::with($relations[$className])
->eagerLoadRelations($models->all());
});
return $this;
}
/**
* Load a set of relationship counts onto the mixed relationship collection.
*
* @param array<array-key, array|(callable(Relation<*, *, *>): mixed)|string>|string $relations
* @return $this
*/
public function loadMorphCount(string $relation, array $relations)
{
$this->pluck($relation)
->filter()
->groupBy(fn ($model) => get_class($model))
->each(fn ($models, $className) => static::make($models)->loadCount($relations[$className] ?? []));
return $this;
}
/**
* Add an item to the collection.
*
* @param TModel $item
* @return $this
*/
public function add($item)
{
$this->items[] = $item;
return $this;
}
/**
* Determine if a key exists in the collection.
*
* @param (callable(TModel, TKey): bool)|string|TModel $key
* @param mixed $operator
* @param mixed $value
*/
public function contains($key, $operator = null, $value = null): bool
{
if (func_num_args() > 1 || $this->useAsCallable($key)) {
return parent::contains(...func_get_args());
}
if ($key instanceof Model) {
return parent::contains(function ($model) use ($key) {
return $model->is($key);
});
}
return parent::contains(function ($model) use ($key) {
return $model->getKey() == $key;
});
}
/**
* Get the array of primary keys.
*
* @return array<int, array-key>
*/
public function modelKeys()
{
return array_map(function ($model) {
return $model->getKey();
}, $this->items);
}
/**
* Merge the collection with the given items.
*
* @param iterable<array-key, TModel> $items
*/
public function merge($items): static
{
$dictionary = $this->getDictionary();
foreach ($items as $item) {
$dictionary[$item->getKey()] = $item;
}
return new static(array_values($dictionary));
}
/**
* Run a map over each of the items.
*
* @template TMapValue
*
* @param callable(TModel, TKey): TMapValue $callback
* @return (TMapValue is Model ? static<TKey, TMapValue> : BaseCollection<TKey, TMapValue>)
*/
public function map(callable $callback): Enumerable
{
$result = parent::map($callback);
return $result->contains(function ($item) {
return ! $item instanceof Model;
}) ? $result->toBase() : $result;
}
/**
* Reload a fresh model instance from the database for all the entities.
*
* @param array<array-key, string>|string $with
* @return static
*/
public function fresh($with = [])
{
if ($this->isEmpty()) {
return new static();
}
$model = $this->first();
$freshModels = $model->newQueryWithoutScopes()
->with(is_string($with) ? func_get_args() : $with)
->whereIn($model->getKeyName(), $this->modelKeys())
->get()
->getDictionary();
return $this->map(function ($model) use ($freshModels) {
return $model->exists && isset($freshModels[$model->getKey()])
? $freshModels[$model->getKey()] : null;
});
}
/**
* Diff the collection with the given items.
*
* @param iterable<array-key, TModel> $items
*/
public function diff($items): static
{
$diff = new static();
$dictionary = $this->getDictionary($items);
foreach ($this->items as $item) {
if (! isset($dictionary[$item->getKey()])) {
$diff->add($item);
}
}
return $diff;
}
/**
* Intersect the collection with the given items.
*
* @param iterable<array-key, TModel> $items
*/
public function intersect(mixed $items): static
{
$intersect = new static();
$dictionary = $this->getDictionary($items);
foreach ($this->items as $item) {
if (isset($dictionary[$item->getKey()])) {
$intersect->add($item);
}
}
return $intersect;
}
/**
* Return only unique items from the collection.
*
* @param null|(callable(TModel, int): mixed)|string $key
* @return static<int, TModel>
*/
public function unique(mixed $key = null, bool $strict = false): static
{
if (! is_null($key)) {
return parent::unique($key, $strict);
}
return new static(array_values($this->getDictionary()));
}
/**
* Returns only the models from the collection with the specified keys.
*
* @param null|array<array-key, mixed> $keys
* @return static<int, TModel>
*/
public function only($keys): static
{
if (is_null($keys)) {
return new static($this->items);
}
$dictionary = Arr::only($this->getDictionary(), $keys);
return new static(array_values($dictionary));
}
/**
* Returns only the columns from the collection with the specified keys.
*
* @param null|array|TKey $keys
* @return BaseCollection<int, mixed>
*/
public function columns($keys)
{
if (is_null($keys)) {
return new BaseCollection([]);
}
$result = [];
$isSingleColumn = is_string($keys);
foreach ($this->items as $item) {
if ($isSingleColumn) {
$value = $item->{$keys} ?? null;
$result[] = $value instanceof Arrayable ? $value->toArray() : $value;
} else {
$result[] = value(static function () use ($item, $keys) {
$res = [];
foreach ($keys as $key) {
$value = $item->{$key} ?? null;
$res[$key] = $value instanceof Arrayable ? $value->toArray() : $value;
}
return $res;
});
}
}
return new BaseCollection($result);
}
/**
* Returns all models in the collection except the models with specified keys.
*
* @param null|array<array-key, mixed> $keys
* @return static<int, TModel>
*/
public function except($keys): static
{
if (is_null($keys)) {
return new static($this->items);
}
$dictionary = Arr::except($this->getDictionary(), $keys);
return new static(array_values($dictionary));
}
/**
* Make the given, typically visible, attributes hidden across the entire collection.
*
* @param array<array-key, string>|string $attributes
* @return $this
*/
public function makeHidden($attributes)
{
return $this->each->addHidden($attributes);
}
/**
* Make the given, typically hidden, attributes visible across the entire collection.
*
* @param array<array-key, string>|string $attributes
* @return $this
*/
public function makeVisible($attributes)
{
return $this->each->makeVisible($attributes);
}
/**
* Set the visible attributes across the entire collection.
*/
public function setVisible(array $visible): static
{
return $this->each->setVisible($visible);
}
/**
* Set the hidden attributes across the entire collection.
*/
public function setHidden(array $hidden): static
{
return $this->each->setHidden($hidden);
}
/**
* Append an attribute across the entire collection.
*
* @param array|string $attributes
* @return $this
*/
public function append($attributes)
{
return $this->each->append($attributes);
}
/**
* Get a dictionary keyed by primary keys.
*
* @param null|iterable<array-key, TModel> $items
* @return array<array-key, TModel>
*/
public function getDictionary($items = null)
{
$items = is_null($items) ? $this->items : $items;
$dictionary = [];
foreach ($items as $value) {
$dictionary[$value->getKey()] = $value;
}
return $dictionary;
}
/**
* The following methods are intercepted to always return base collections.
* @param mixed $value
*/
/**
* Get an array with the values of a given key.
*
* @param array<array-key, string>|string $value
* @return BaseCollection<array-key, mixed>
*/
public function pluck(array|string $value, ?string $key = null): Enumerable
{
return $this->toBase()->pluck($value, $key);
}
/**
* Get the keys of the collection items.
*
* @return BaseCollection<int, int>
*/
public function keys(): Enumerable
{
return $this->toBase()->keys();
}
/**
* Zip the collection together with one or more arrays.
*
* @template TZipValue
*
* @param Arrayable<array-key, TZipValue>|iterable<array-key, TZipValue> ...$items
* @return BaseCollection<int, BaseCollection<int, TModel|TZipValue>>
*/
public function zip($items): Enumerable
{
return call_user_func_array([$this->toBase(), 'zip'], func_get_args());
}
/**
* Collapse the collection of items into a single array.
*
* @return BaseCollection<int, mixed>
*/
public function collapse(): Enumerable
{
return $this->toBase()->collapse();
}
/**
* Get a flattened array of the items in the collection.
*
* @param int $depth
* @return BaseCollection<int, mixed>
*/
public function flatten($depth = INF): Enumerable
{
return $this->toBase()->flatten($depth);
}
/**
* Flip the items in the collection.
*
* @return BaseCollection<TModel, TKey>
*/
public function flip(): Enumerable
{
return $this->toBase()->flip();
}
/**
* Pad collection to the specified length with a value.
*
* @template TPadValue
*
* @param TPadValue $value
* @return BaseCollection<int, TModel|TPadValue>
*/
public function pad(int $size, $value): Enumerable
{
return $this->toBase()->pad($size, $value);
}
public function compress(): UnCompressInterface
{
if ($this->isEmpty()) {
return new CollectionMeta(null);
}
$class = get_class($this->first());
$this->each(function ($model) use ($class) {
if (get_class($model) !== $class) {
throw new RuntimeException('Collections with multiple model types is not supported.');
}
});
$keys = array_keys($this->getDictionary());
return new CollectionMeta($class, $keys);
}
/**
* Load a relationship path if it is not already eager loaded.
*/
protected function loadMissingRelation(Collection $models, array $path)
{
$relation = array_splice($path, 0, 1);
$name = explode(':', key($relation))[0];
if (is_string(reset($relation))) {
$relation = reset($relation);
}
$models->filter(function ($model) use ($name) {
return ! is_null($model) && ! $model->relationLoaded($name);
})->load($relation);
if (empty($path)) {
return;
}
$models = $models->pluck($name);
if ($models->first() instanceof Enumerable) {
$models = $models->collapse();
}
$this->loadMissingRelation(new static($models), $path);
}
}