Debian Codegraph @

lib/3rdParty/composer/illuminate/collections/Collection.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use ArrayAccess;
6 use ArrayIterator;
7 use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
8 use Illuminate\Support\Traits\EnumeratesValues;
9 use Illuminate\Support\Traits\Macroable;
10 use Illuminate\Support\Traits\TransformsToResourceCollection;
11 use InvalidArgumentException;
12 use stdClass;
13 use Traversable;
14
15 /**
16 * @template TKey of array-key
17 *
18 * @template-covariant TValue
19 *
20 * @implements \ArrayAccess<TKey, TValue>
21 * @implements \Illuminate\Support\Enumerable<TKey, TValue>
22 */
23 class Collection implements ArrayAccess, CanBeEscapedWhenCastToString, Enumerable
24 {
25 /**
26 * @use \Illuminate\Support\Traits\EnumeratesValues<TKey, TValue>
27 */
28 use EnumeratesValues, Macroable, TransformsToResourceCollection;
29
30 /**
31 * The items contained in the collection.
32 *
33 * @var array<TKey, TValue>
34 */
35 protected $items = [];
36
37 /**
38 * Create a new collection.
39 *
40 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue>|null $items
41 */
42 public function __construct($items = [])
43 {
44 $this->items = $this->getArrayableItems($items);
45 }
46
47 /**
48 * Create a collection with the given range.
49 *
50 * @param int $from
51 * @param int $to
52 * @param int $step
53 * @return static<int, int>
54 */
55 public static function range($from, $to, $step = 1)
56 {
57 return new static(range($from, $to, $step));
58 }
59
60 /**
61 * Get all of the items in the collection.
62 *
63 * @return array<TKey, TValue>
64 */
65 public function all()
66 {
67 return $this->items;
68 }
69
70 /**
71 * Get a lazy collection for the items in this collection.
72 *
73 * @return \Illuminate\Support\LazyCollection<TKey, TValue>
74 */
75 public function lazy()
76 {
77 return new LazyCollection($this->items);
78 }
79
80 /**
81 * Get the median of a given key.
82 *
83 * @param string|array<array-key, string>|null $key
84 * @return float|int|null
85 */
86 public function median($key = null)
87 {
88 $values = (isset($key) ? $this->pluck($key) : $this)
89 ->reject(fn ($item) => is_null($item))
90 ->sort()->values();
91
92 $count = $values->count();
93
94 if ($count === 0) {
95 return;
96 }
97
98 $middle = intdiv($count, 2);
99
100 if ($count % 2) {
101 return $values->get($middle);
102 }
103
104 return (new static([
105 $values->get($middle - 1), $values->get($middle),
106 ]))->average();
107 }
108
109 /**
110 * Get the mode of a given key.
111 *
112 * @param string|array<array-key, string>|null $key
113 * @return array<int, float|int>|null
114 */
115 public function mode($key = null)
116 {
117 if ($this->count() === 0) {
118 return;
119 }
120
121 $collection = isset($key) ? $this->pluck($key) : $this;
122
123 $counts = new static;
124
125 $collection->each(fn ($value) => $counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1);
126
127 $sorted = $counts->sort();
128
129 $highestValue = $sorted->last();
130
131 return $sorted->filter(fn ($value) => $value == $highestValue)
132 ->sort()->keys()->all();
133 }
134
135 /**
136 * Collapse the collection of items into a single array.
137 *
138 * @return static<int, mixed>
139 */
140 public function collapse()
141 {
142 return new static(Arr::collapse($this->items));
143 }
144
145 /**
146 * Collapse the collection of items into a single array while preserving its keys.
147 *
148 * @return static<mixed, mixed>
149 */
150 public function collapseWithKeys()
151 {
152 if (! $this->items) {
153 return new static;
154 }
155
156 $results = [];
157
158 foreach ($this->items as $key => $values) {
159 if ($values instanceof Collection) {
160 $values = $values->all();
161 } elseif (! is_array($values)) {
162 continue;
163 }
164
165 $results[$key] = $values;
166 }
167
168 if (! $results) {
169 return new static;
170 }
171
172 return new static(array_replace(...$results));
173 }
174
175 /**
176 * Determine if an item exists in the collection.
177 *
178 * @param (callable(TValue, TKey): bool)|TValue|string $key
179 * @param mixed $operator
180 * @param mixed $value
181 * @return bool
182 */
183 public function contains($key, $operator = null, $value = null)
184 {
185 if (func_num_args() === 1) {
186 if ($this->useAsCallable($key)) {
187 return array_any($this->items, $key);
188 }
189
190 return in_array($key, $this->items);
191 }
192
193 return $this->contains($this->operatorForWhere(...func_get_args()));
194 }
195
196 /**
197 * Determine if an item exists, using strict comparison.
198 *
199 * @param (callable(TValue): bool)|TValue|array-key $key
200 * @param TValue|null $value
201 * @return bool
202 */
203 public function containsStrict($key, $value = null)
204 {
205 if (func_num_args() === 2) {
206 return $this->contains(fn ($item) => data_get($item, $key) === $value);
207 }
208
209 if ($this->useAsCallable($key)) {
210 return ! is_null($this->first($key));
211 }
212
213 return in_array($key, $this->items, true);
214 }
215
216 /**
217 * Determine if an item is not contained in the collection.
218 *
219 * @param mixed $key
220 * @param mixed $operator
221 * @param mixed $value
222 * @return bool
223 */
224 public function doesntContain($key, $operator = null, $value = null)
225 {
226 return ! $this->contains(...func_get_args());
227 }
228
229 /**
230 * Determine if an item is not contained in the enumerable, using strict comparison.
231 *
232 * @param mixed $key
233 * @param mixed $operator
234 * @param mixed $value
235 * @return bool
236 */
237 public function doesntContainStrict($key, $operator = null, $value = null)
238 {
239 return ! $this->containsStrict(...func_get_args());
240 }
241
242 /**
243 * Cross join with the given lists, returning all possible permutations.
244 *
245 * @template TCrossJoinKey
246 * @template TCrossJoinValue
247 *
248 * @param \Illuminate\Contracts\Support\Arrayable<TCrossJoinKey, TCrossJoinValue>|iterable<TCrossJoinKey, TCrossJoinValue> ...$lists
249 * @return static<int, array<int, TValue|TCrossJoinValue>>
250 */
251 public function crossJoin(...$lists)
252 {
253 return new static(Arr::crossJoin(
254 $this->items, ...array_map($this->getArrayableItems(...), $lists)
255 ));
256 }
257
258 /**
259 * Get the items in the collection that are not present in the given items.
260 *
261 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
262 * @return static
263 */
264 public function diff($items)
265 {
266 return new static(array_diff($this->items, $this->getArrayableItems($items)));
267 }
268
269 /**
270 * Get the items in the collection that are not present in the given items, using the callback.
271 *
272 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
273 * @param callable(TValue, TValue): int $callback
274 * @return static
275 */
276 public function diffUsing($items, callable $callback)
277 {
278 return new static(array_udiff($this->items, $this->getArrayableItems($items), $callback));
279 }
280
281 /**
282 * Get the items in the collection whose keys and values are not present in the given items.
283 *
284 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
285 * @return static
286 */
287 public function diffAssoc($items)
288 {
289 return new static(array_diff_assoc($this->items, $this->getArrayableItems($items)));
290 }
291
292 /**
293 * Get the items in the collection whose keys and values are not present in the given items, using the callback.
294 *
295 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
296 * @param callable(TKey, TKey): int $callback
297 * @return static
298 */
299 public function diffAssocUsing($items, callable $callback)
300 {
301 return new static(array_diff_uassoc($this->items, $this->getArrayableItems($items), $callback));
302 }
303
304 /**
305 * Get the items in the collection whose keys are not present in the given items.
306 *
307 * @param \Illuminate\Contracts\Support\Arrayable<TKey, mixed>|iterable<TKey, mixed> $items
308 * @return static
309 */
310 public function diffKeys($items)
311 {
312 return new static(array_diff_key($this->items, $this->getArrayableItems($items)));
313 }
314
315 /**
316 * Get the items in the collection whose keys are not present in the given items, using the callback.
317 *
318 * @param \Illuminate\Contracts\Support\Arrayable<TKey, mixed>|iterable<TKey, mixed> $items
319 * @param callable(TKey, TKey): int $callback
320 * @return static
321 */
322 public function diffKeysUsing($items, callable $callback)
323 {
324 return new static(array_diff_ukey($this->items, $this->getArrayableItems($items), $callback));
325 }
326
327 /**
328 * Retrieve duplicate items from the collection.
329 *
330 * @template TMapValue
331 *
332 * @param (callable(TValue): TMapValue)|string|null $callback
333 * @param bool $strict
334 * @return static
335 */
336 public function duplicates($callback = null, $strict = false)
337 {
338 $items = $this->map($this->valueRetriever($callback));
339
340 $uniqueItems = $items->unique(null, $strict);
341
342 $compare = $this->duplicateComparator($strict);
343
344 $duplicates = new static;
345
346 foreach ($items as $key => $value) {
347 if ($uniqueItems->isNotEmpty() && $compare($value, $uniqueItems->first())) {
348 $uniqueItems->shift();
349 } else {
350 $duplicates[$key] = $value;
351 }
352 }
353
354 return $duplicates;
355 }
356
357 /**
358 * Retrieve duplicate items from the collection using strict comparison.
359 *
360 * @template TMapValue
361 *
362 * @param (callable(TValue): TMapValue)|string|null $callback
363 * @return static
364 */
365 public function duplicatesStrict($callback = null)
366 {
367 return $this->duplicates($callback, true);
368 }
369
370 /**
371 * Get the comparison function to detect duplicates.
372 *
373 * @param bool $strict
374 * @return callable(TValue, TValue): bool
375 */
376 protected function duplicateComparator($strict)
377 {
378 if ($strict) {
379 return fn ($a, $b) => $a === $b;
380 }
381
382 return fn ($a, $b) => $a == $b;
383 }
384
385 /**
386 * Get all items except for those with the specified keys.
387 *
388 * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string $keys
389 * @return static
390 */
391 public function except($keys)
392 {
393 if (is_null($keys)) {
394 return new static($this->items);
395 }
396
397 if ($keys instanceof Enumerable) {
398 $keys = $keys->all();
399 } elseif (! is_array($keys)) {
400 $keys = func_get_args();
401 }
402
403 return new static(Arr::except($this->items, $keys));
404 }
405
406 /**
407 * Run a filter over each of the items.
408 *
409 * @param (callable(TValue, TKey): bool)|null $callback
410 * @return static
411 */
412 public function filter(?callable $callback = null)
413 {
414 if ($callback) {
415 return new static(Arr::where($this->items, $callback));
416 }
417
418 return new static(array_filter($this->items));
419 }
420
421 /**
422 * Get the first item from the collection passing the given truth test.
423 *
424 * @template TFirstDefault
425 *
426 * @param (callable(TValue, TKey): bool)|null $callback
427 * @param TFirstDefault|(\Closure(): TFirstDefault) $default
428 * @return TValue|TFirstDefault
429 */
430 public function first(?callable $callback = null, $default = null)
431 {
432 return Arr::first($this->items, $callback, $default);
433 }
434
435 /**
436 * Get a flattened array of the items in the collection.
437 *
438 * @param int $depth
439 * @return static<int, mixed>
440 */
441 public function flatten($depth = INF)
442 {
443 return new static(Arr::flatten($this->items, $depth));
444 }
445
446 /**
447 * Flip the items in the collection.
448 *
449 * @return static<TValue, TKey>
450 */
451 public function flip()
452 {
453 return new static(array_flip($this->items));
454 }
455
456 /**
457 * Remove an item from the collection by key.
458 *
459 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TKey>|TKey $keys
460 * @return $this
461 */
462 public function forget($keys)
463 {
464 foreach ($this->getArrayableItems($keys) as $key) {
465 $this->offsetUnset($key);
466 }
467
468 return $this;
469 }
470
471 /**
472 * Get an item from the collection by key.
473 *
474 * @template TGetDefault
475 *
476 * @param TKey|null $key
477 * @param TGetDefault|(\Closure(): TGetDefault) $default
478 * @return TValue|TGetDefault
479 */
480 public function get($key, $default = null)
481 {
482 $key ??= '';
483
484 if (array_key_exists($key, $this->items)) {
485 return $this->items[$key];
486 }
487
488 return value($default);
489 }
490
491 /**
492 * Get an item from the collection by key or add it to collection if it does not exist.
493 *
494 * @template TGetOrPutValue
495 *
496 * @param mixed $key
497 * @param TGetOrPutValue|(\Closure(): TGetOrPutValue) $value
498 * @return TValue|TGetOrPutValue
499 */
500 public function getOrPut($key, $value)
501 {
502 if (array_key_exists($key ?? '', $this->items)) {
503 return $this->items[$key ?? ''];
504 }
505
506 $this->offsetSet($key, $value = value($value));
507
508 return $value;
509 }
510
511 /**
512 * Group an associative array by a field or using a callback.
513 *
514 * @template TGroupKey of array-key|\UnitEnum|\Stringable
515 *
516 * @param (callable(TValue, TKey): TGroupKey)|array|string $groupBy
517 * @param bool $preserveKeys
518 * @return static<
519 * ($groupBy is (array|string)
520 * ? array-key
521 * : (TGroupKey is \UnitEnum ? array-key : (TGroupKey is \Stringable ? string : TGroupKey))),
522 * static<($preserveKeys is true ? TKey : int), ($groupBy is array ? mixed : TValue)>
523 * >
524 */
525 public function groupBy($groupBy, $preserveKeys = false)
526 {
527 if (! $this->useAsCallable($groupBy) && is_array($groupBy)) {
528 $nextGroups = $groupBy;
529
530 $groupBy = array_shift($nextGroups);
531 }
532
533 $groupBy = $this->valueRetriever($groupBy);
534
535 $results = [];
536
537 foreach ($this->items as $key => $value) {
538 $groupKeys = $groupBy($value, $key);
539
540 if (! is_array($groupKeys)) {
541 $groupKeys = [$groupKeys];
542 }
543
544 foreach ($groupKeys as $groupKey) {
545 $groupKey = match (true) {
546 is_bool($groupKey) => (int) $groupKey,
547 $groupKey instanceof \UnitEnum => enum_value($groupKey),
548 $groupKey instanceof \Stringable, is_null($groupKey) => (string) $groupKey,
549 default => $groupKey,
550 };
551
552 if (! array_key_exists($groupKey, $results)) {
553 $results[$groupKey] = new static;
554 }
555
556 $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value);
557 }
558 }
559
560 $result = new static($results);
561
562 if (! empty($nextGroups)) {
563 return $result->map->groupBy($nextGroups, $preserveKeys);
564 }
565
566 return $result;
567 }
568
569 /**
570 * Key an associative array by a field or using a callback.
571 *
572 * @template TNewKey of array-key|\UnitEnum
573 *
574 * @param (callable(TValue, TKey): TNewKey)|array|string $keyBy
575 * @return static<($keyBy is (array|string) ? array-key : (TNewKey is \UnitEnum ? array-key : TNewKey)), TValue>
576 */
577 public function keyBy($keyBy)
578 {
579 $keyBy = $this->valueRetriever($keyBy);
580
581 $results = [];
582
583 foreach ($this->items as $key => $item) {
584 $resolvedKey = $keyBy($item, $key);
585
586 if ($resolvedKey instanceof \UnitEnum) {
587 $resolvedKey = enum_value($resolvedKey);
588 }
589
590 if (is_object($resolvedKey)) {
591 $resolvedKey = (string) $resolvedKey;
592 }
593
594 $results[$resolvedKey] = $item;
595 }
596
597 return new static($results);
598 }
599
600 /**
601 * Determine if an item exists in the collection by key.
602 *
603 * @param TKey|array<array-key, TKey> $key
604 * @return bool
605 */
606 public function has($key)
607 {
608 $keys = is_array($key) ? $key : func_get_args();
609
610 return array_all($keys, fn ($key) => array_key_exists($key ?? '', $this->items));
611 }
612
613 /**
614 * Determine if any of the keys exist in the collection.
615 *
616 * @param TKey|array<array-key, TKey> $key
617 * @return bool
618 */
619 public function hasAny($key)
620 {
621 if ($this->isEmpty()) {
622 return false;
623 }
624
625 $keys = is_array($key) ? $key : func_get_args();
626
627 return array_any($keys, fn ($key) => array_key_exists($key ?? '', $this->items));
628 }
629
630 /**
631 * Concatenate values of a given key as a string.
632 *
633 * @param (callable(TValue, TKey): mixed)|string|null $value
634 * @param string|null $glue
635 * @return string
636 */
637 public function implode($value, $glue = null)
638 {
639 if ($this->useAsCallable($value)) {
640 return implode($glue ?? '', $this->map($value)->all());
641 }
642
643 $first = $this->first();
644
645 if (is_array($first) || (is_object($first) && ! $first instanceof Stringable)) {
646 return implode($glue ?? '', $this->pluck($value)->all());
647 }
648
649 return implode($value ?? '', $this->items);
650 }
651
652 /**
653 * Intersect the collection with the given items.
654 *
655 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
656 * @return static
657 */
658 public function intersect($items)
659 {
660 return new static(array_intersect($this->items, $this->getArrayableItems($items)));
661 }
662
663 /**
664 * Intersect the collection with the given items, using the callback.
665 *
666 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
667 * @param callable(TValue, TValue): int $callback
668 * @return static
669 */
670 public function intersectUsing($items, callable $callback)
671 {
672 return new static(array_uintersect($this->items, $this->getArrayableItems($items), $callback));
673 }
674
675 /**
676 * Intersect the collection with the given items with additional index check.
677 *
678 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
679 * @return static
680 */
681 public function intersectAssoc($items)
682 {
683 return new static(array_intersect_assoc($this->items, $this->getArrayableItems($items)));
684 }
685
686 /**
687 * Intersect the collection with the given items with additional index check, using the callback.
688 *
689 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TValue>|iterable<array-key, TValue> $items
690 * @param callable(TValue, TValue): int $callback
691 * @return static
692 */
693 public function intersectAssocUsing($items, callable $callback)
694 {
695 return new static(array_intersect_uassoc($this->items, $this->getArrayableItems($items), $callback));
696 }
697
698 /**
699 * Intersect the collection with the given items by key.
700 *
701 * @param \Illuminate\Contracts\Support\Arrayable<TKey, mixed>|iterable<TKey, mixed> $items
702 * @return static
703 */
704 public function intersectByKeys($items)
705 {
706 return new static(array_intersect_key(
707 $this->items, $this->getArrayableItems($items)
708 ));
709 }
710
711 /**
712 * Determine if the collection is empty or not.
713 *
714 * @phpstan-assert-if-true null $this->first()
715 * @phpstan-assert-if-true null $this->last()
716 *
717 * @phpstan-assert-if-false TValue $this->first()
718 * @phpstan-assert-if-false TValue $this->last()
719 *
720 * @return bool
721 */
722 public function isEmpty()
723 {
724 return empty($this->items);
725 }
726
727 /**
728 * Determine if the collection contains exactly one item. If a callback is provided, determine if exactly one item matches the condition.
729 *
730 * @param (callable(TValue, TKey): bool)|null $callback
731 * @return bool
732 *
733 * @deprecated 12.49.0 Use the `hasSole()` method instead.
734 */
735 public function containsOneItem(?callable $callback = null): bool
736 {
737 return $this->hasSole($callback);
738 }
739
740 /**
741 * Determine if the collection contains multiple items.
742 *
743 * @param (callable(TValue, TKey): bool)|null $callback
744 * @return bool
745 *
746 * @deprecated 12.50.0 Use the `hasMany()` method instead.
747 */
748 public function containsManyItems(?callable $callback = null): bool
749 {
750 return $this->hasMany($callback);
751 }
752
753 /**
754 * Join all items from the collection using a string. The final items can use a separate glue string.
755 *
756 * @param string $glue
757 * @param string $finalGlue
758 * @return TValue|string
759 */
760 public function join($glue, $finalGlue = '')
761 {
762 if ($finalGlue === '') {
763 return $this->implode($glue);
764 }
765
766 $count = $this->count();
767
768 if ($count === 0) {
769 return '';
770 }
771
772 if ($count === 1) {
773 return $this->last();
774 }
775
776 $collection = new static($this->items);
777
778 $finalItem = $collection->pop();
779
780 return $collection->implode($glue).$finalGlue.$finalItem;
781 }
782
783 /**
784 * Get the keys of the collection items.
785 *
786 * @return static<int, TKey>
787 */
788 public function keys()
789 {
790 return new static(array_keys($this->items));
791 }
792
793 /**
794 * Get the last item from the collection.
795 *
796 * @template TLastDefault
797 *
798 * @param (callable(TValue, TKey): bool)|null $callback
799 * @param TLastDefault|(\Closure(): TLastDefault) $default
800 * @return TValue|TLastDefault
801 */
802 public function last(?callable $callback = null, $default = null)
803 {
804 return Arr::last($this->items, $callback, $default);
805 }
806
807 /**
808 * Get the values of a given key.
809 *
810 * @param \Closure|string|int|array<array-key, string>|null $value
811 * @param \Closure|string|null $key
812 * @return static<array-key, mixed>
813 */
814 public function pluck($value, $key = null)
815 {
816 return new static(Arr::pluck($this->items, $value, $key));
817 }
818
819 /**
820 * Run a map over each of the items.
821 *
822 * @template TMapValue
823 *
824 * @param callable(TValue, TKey): TMapValue $callback
825 * @return static<TKey, TMapValue>
826 */
827 public function map(callable $callback)
828 {
829 return new static(Arr::map($this->items, $callback));
830 }
831
832 /**
833 * Run a dictionary map over the items.
834 *
835 * The callback should return an associative array with a single key/value pair.
836 *
837 * @template TMapToDictionaryKey of array-key
838 * @template TMapToDictionaryValue
839 *
840 * @param callable(TValue, TKey): array<TMapToDictionaryKey, TMapToDictionaryValue> $callback
841 * @return static<TMapToDictionaryKey, array<int, TMapToDictionaryValue>>
842 */
843 public function mapToDictionary(callable $callback)
844 {
845 $dictionary = [];
846
847 foreach ($this->items as $key => $item) {
848 $pair = $callback($item, $key);
849
850 $key = key($pair);
851
852 $value = reset($pair);
853
854 if (! isset($dictionary[$key])) {
855 $dictionary[$key] = [];
856 }
857
858 $dictionary[$key][] = $value;
859 }
860
861 return new static($dictionary);
862 }
863
864 /**
865 * Run an associative map over each of the items.
866 *
867 * The callback should return an associative array with a single key/value pair.
868 *
869 * @template TMapWithKeysKey of array-key
870 * @template TMapWithKeysValue
871 *
872 * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
873 * @return static<TMapWithKeysKey, TMapWithKeysValue>
874 */
875 public function mapWithKeys(callable $callback)
876 {
877 return new static(Arr::mapWithKeys($this->items, $callback));
878 }
879
880 /**
881 * Merge the collection with the given items.
882 *
883 * @template TMergeValue
884 *
885 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TMergeValue>|iterable<TKey, TMergeValue> $items
886 * @return static<TKey, TValue|TMergeValue>
887 */
888 public function merge($items)
889 {
890 return new static(array_merge($this->items, $this->getArrayableItems($items)));
891 }
892
893 /**
894 * Recursively merge the collection with the given items.
895 *
896 * @template TMergeRecursiveValue
897 *
898 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TMergeRecursiveValue>|iterable<TKey, TMergeRecursiveValue> $items
899 * @return static<TKey, TValue|TMergeRecursiveValue>
900 */
901 public function mergeRecursive($items)
902 {
903 return new static(array_merge_recursive($this->items, $this->getArrayableItems($items)));
904 }
905
906 /**
907 * Multiply the items in the collection by the multiplier.
908 *
909 * @param int $multiplier
910 * @return static
911 */
912 public function multiply(int $multiplier)
913 {
914 $new = new static;
915
916 for ($i = 0; $i < $multiplier; $i++) {
917 $new->push(...$this->items);
918 }
919
920 return $new;
921 }
922
923 /**
924 * Create a collection by using this collection for keys and another for its values.
925 *
926 * @template TCombineValue
927 *
928 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TCombineValue>|iterable<array-key, TCombineValue> $values
929 * @return static<TValue, TCombineValue>
930 */
931 public function combine($values)
932 {
933 return new static(array_combine($this->all(), $this->getArrayableItems($values)));
934 }
935
936 /**
937 * Union the collection with the given items.
938 *
939 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
940 * @return static
941 */
942 public function union($items)
943 {
944 return new static($this->items + $this->getArrayableItems($items));
945 }
946
947 /**
948 * Create a new collection consisting of every n-th element.
949 *
950 * @param int $step
951 * @param int $offset
952 * @return ($step is positive-int ? static : never)
953 *
954 * @throws \InvalidArgumentException
955 */
956 public function nth($step, $offset = 0)
957 {
958 if ($step < 1) {
959 throw new InvalidArgumentException('Step value must be at least 1.');
960 }
961
962 $new = [];
963
964 $position = 0;
965
966 foreach ($this->slice($offset)->items as $item) {
967 if ($position % $step === 0) {
968 $new[] = $item;
969 }
970
971 $position++;
972 }
973
974 return new static($new);
975 }
976
977 /**
978 * Get the items with the specified keys.
979 *
980 * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string|null $keys
981 * @return static
982 */
983 public function only($keys)
984 {
985 if (is_null($keys)) {
986 return new static($this->items);
987 }
988
989 if ($keys instanceof Enumerable) {
990 $keys = $keys->all();
991 }
992
993 $keys = is_array($keys) ? $keys : func_get_args();
994
995 return new static(Arr::only($this->items, $keys));
996 }
997
998 /**
999 * Select specific values from the items within the collection.
1000 *
1001 * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string|null $keys
1002 * @return static
1003 */
1004 public function select($keys)
1005 {
1006 if (is_null($keys)) {
1007 return new static($this->items);
1008 }
1009
1010 if ($keys instanceof Enumerable) {
1011 $keys = $keys->all();
1012 }
1013
1014 $keys = is_array($keys) ? $keys : func_get_args();
1015
1016 return new static(Arr::select($this->items, $keys));
1017 }
1018
1019 /**
1020 * Get and remove the last N items from the collection.
1021 *
1022 * @param int $count
1023 * @return ($count is 1 ? TValue|null : static<int, TValue>)
1024 */
1025 public function pop($count = 1)
1026 {
1027 if ($count < 1) {
1028 return new static;
1029 }
1030
1031 if ($count === 1) {
1032 return array_pop($this->items);
1033 }
1034
1035 if ($this->isEmpty()) {
1036 return new static;
1037 }
1038
1039 $results = [];
1040
1041 $collectionCount = $this->count();
1042
1043 foreach (range(1, min($count, $collectionCount)) as $item) {
1044 $results[] = array_pop($this->items);
1045 }
1046
1047 return new static($results);
1048 }
1049
1050 /**
1051 * Push an item onto the beginning of the collection.
1052 *
1053 * @param TValue $value
1054 * @param TKey $key
1055 * @return $this
1056 */
1057 public function prepend($value, $key = null)
1058 {
1059 $this->items = Arr::prepend($this->items, ...(func_num_args() > 1 ? func_get_args() : [$value]));
1060
1061 return $this;
1062 }
1063
1064 /**
1065 * Push one or more items onto the end of the collection.
1066 *
1067 * @param TValue ...$values
1068 * @return $this
1069 */
1070 public function push(...$values)
1071 {
1072 foreach ($values as $value) {
1073 $this->items[] = $value;
1074 }
1075
1076 return $this;
1077 }
1078
1079 /**
1080 * Prepend one or more items to the beginning of the collection.
1081 *
1082 * @param TValue ...$values
1083 * @return $this
1084 */
1085 public function unshift(...$values)
1086 {
1087 array_unshift($this->items, ...$values);
1088
1089 return $this;
1090 }
1091
1092 /**
1093 * Push all of the given items onto the collection.
1094 *
1095 * @template TConcatKey of array-key
1096 * @template TConcatValue
1097 *
1098 * @param iterable<TConcatKey, TConcatValue> $source
1099 * @return static<TKey|TConcatKey, TValue|TConcatValue>
1100 */
1101 public function concat($source)
1102 {
1103 $result = new static($this);
1104
1105 foreach ($source as $item) {
1106 $result->push($item);
1107 }
1108
1109 return $result;
1110 }
1111
1112 /**
1113 * Get and remove an item from the collection.
1114 *
1115 * @template TPullDefault
1116 *
1117 * @param TKey $key
1118 * @param TPullDefault|(\Closure(): TPullDefault) $default
1119 * @return TValue|TPullDefault
1120 */
1121 public function pull($key, $default = null)
1122 {
1123 return Arr::pull($this->items, $key, $default);
1124 }
1125
1126 /**
1127 * Put an item in the collection by key.
1128 *
1129 * @param TKey $key
1130 * @param TValue $value
1131 * @return $this
1132 */
1133 public function put($key, $value)
1134 {
1135 $this->offsetSet($key, $value);
1136
1137 return $this;
1138 }
1139
1140 /**
1141 * Get one or a specified number of items randomly from the collection.
1142 *
1143 * @param (callable(self<TKey, TValue>): int)|int|null $number
1144 * @param bool $preserveKeys
1145 * @return ($number is null ? TValue : static<int, TValue>)
1146 *
1147 * @throws \InvalidArgumentException
1148 */
1149 public function random($number = null, $preserveKeys = false)
1150 {
1151 if (is_null($number)) {
1152 return Arr::random($this->items);
1153 }
1154
1155 if (is_callable($number)) {
1156 return new static(Arr::random($this->items, $number($this), $preserveKeys));
1157 }
1158
1159 return new static(Arr::random($this->items, $number, $preserveKeys));
1160 }
1161
1162 /**
1163 * Replace the collection items with the given items.
1164 *
1165 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
1166 * @return static
1167 */
1168 public function replace($items)
1169 {
1170 return new static(array_replace($this->items, $this->getArrayableItems($items)));
1171 }
1172
1173 /**
1174 * Recursively replace the collection items with the given items.
1175 *
1176 * @param \Illuminate\Contracts\Support\Arrayable<TKey, TValue>|iterable<TKey, TValue> $items
1177 * @return static
1178 */
1179 public function replaceRecursive($items)
1180 {
1181 return new static(array_replace_recursive($this->items, $this->getArrayableItems($items)));
1182 }
1183
1184 /**
1185 * Reverse items order.
1186 *
1187 * @return static
1188 */
1189 public function reverse()
1190 {
1191 return new static(array_reverse($this->items, true));
1192 }
1193
1194 /**
1195 * Search the collection for a given value and return the corresponding key if successful.
1196 *
1197 * @param TValue|(callable(TValue,TKey): bool) $value
1198 * @param bool $strict
1199 * @return TKey|false
1200 */
1201 public function search($value, $strict = false)
1202 {
1203 if (! $this->useAsCallable($value)) {
1204 return array_search($value, $this->items, $strict);
1205 }
1206
1207 return array_find_key($this->items, $value) ?? false;
1208 }
1209
1210 /**
1211 * Get the item before the given item.
1212 *
1213 * @param TValue|(callable(TValue,TKey): bool) $value
1214 * @param bool $strict
1215 * @return TValue|null
1216 */
1217 public function before($value, $strict = false)
1218 {
1219 $key = $this->search($value, $strict);
1220
1221 if ($key === false) {
1222 return null;
1223 }
1224
1225 $position = ($keys = $this->keys())->search($key);
1226
1227 if ($position === 0) {
1228 return null;
1229 }
1230
1231 return $this->get($keys->get($position - 1));
1232 }
1233
1234 /**
1235 * Get the item after the given item.
1236 *
1237 * @param TValue|(callable(TValue,TKey): bool) $value
1238 * @param bool $strict
1239 * @return TValue|null
1240 */
1241 public function after($value, $strict = false)
1242 {
1243 $key = $this->search($value, $strict);
1244
1245 if ($key === false) {
1246 return null;
1247 }
1248
1249 $position = ($keys = $this->keys())->search($key);
1250
1251 if ($position === $keys->count() - 1) {
1252 return null;
1253 }
1254
1255 return $this->get($keys->get($position + 1));
1256 }
1257
1258 /**
1259 * Get and remove the first N items from the collection.
1260 *
1261 * @param int<0, max> $count
1262 * @return ($count is 1 ? TValue|null : static<int, TValue>)
1263 *
1264 * @throws \InvalidArgumentException
1265 */
1266 public function shift($count = 1)
1267 {
1268 if ($count < 0) {
1269 throw new InvalidArgumentException('Number of shifted items may not be less than zero.');
1270 }
1271
1272 if ($this->isEmpty()) {
1273 return null;
1274 }
1275
1276 if ($count === 0) {
1277 return new static;
1278 }
1279
1280 if ($count === 1) {
1281 return array_shift($this->items);
1282 }
1283
1284 $results = [];
1285
1286 $collectionCount = $this->count();
1287
1288 foreach (range(1, min($count, $collectionCount)) as $item) {
1289 $results[] = array_shift($this->items);
1290 }
1291
1292 return new static($results);
1293 }
1294
1295 /**
1296 * Shuffle the items in the collection.
1297 *
1298 * @return static
1299 */
1300 public function shuffle()
1301 {
1302 return new static(Arr::shuffle($this->items));
1303 }
1304
1305 /**
1306 * Create chunks representing a "sliding window" view of the items in the collection.
1307 *
1308 * @param positive-int $size
1309 * @param positive-int $step
1310 * @return static<int, static>
1311 *
1312 * @throws \InvalidArgumentException
1313 */
1314 public function sliding($size = 2, $step = 1)
1315 {
1316 if ($size < 1) {
1317 throw new InvalidArgumentException('Size value must be at least 1.');
1318 } elseif ($step < 1) {
1319 throw new InvalidArgumentException('Step value must be at least 1.');
1320 }
1321
1322 $chunks = floor(($this->count() - $size) / $step) + 1;
1323
1324 return static::times($chunks, fn ($number) => $this->slice(($number - 1) * $step, $size));
1325 }
1326
1327 /**
1328 * Skip the first {$count} items.
1329 *
1330 * @param int $count
1331 * @return static
1332 */
1333 public function skip($count)
1334 {
1335 return $this->slice($count);
1336 }
1337
1338 /**
1339 * Skip items in the collection until the given condition is met.
1340 *
1341 * @param TValue|callable(TValue,TKey): bool $value
1342 * @return static
1343 */
1344 public function skipUntil($value)
1345 {
1346 return new static($this->lazy()->skipUntil($value)->all());
1347 }
1348
1349 /**
1350 * Skip items in the collection while the given condition is met.
1351 *
1352 * @param TValue|callable(TValue,TKey): bool $value
1353 * @return static
1354 */
1355 public function skipWhile($value)
1356 {
1357 return new static($this->lazy()->skipWhile($value)->all());
1358 }
1359
1360 /**
1361 * Slice the underlying collection array.
1362 *
1363 * @param int $offset
1364 * @param int|null $length
1365 * @return static
1366 */
1367 public function slice($offset, $length = null)
1368 {
1369 return new static(array_slice($this->items, $offset, $length, true));
1370 }
1371
1372 /**
1373 * Split a collection into a certain number of groups.
1374 *
1375 * @param int $numberOfGroups
1376 * @return ($numberOfGroups is positive-int ? static<int, static> : never)
1377 *
1378 * @throws \InvalidArgumentException
1379 */
1380 public function split($numberOfGroups)
1381 {
1382 if ($numberOfGroups < 1) {
1383 throw new InvalidArgumentException('Number of groups must be at least 1.');
1384 }
1385
1386 if ($this->isEmpty()) {
1387 return new static;
1388 }
1389
1390 $groups = new static;
1391
1392 $groupSize = floor($this->count() / $numberOfGroups);
1393
1394 $remain = $this->count() % $numberOfGroups;
1395
1396 $start = 0;
1397
1398 for ($i = 0; $i < $numberOfGroups; $i++) {
1399 $size = $groupSize;
1400
1401 if ($i < $remain) {
1402 $size++;
1403 }
1404
1405 if ($size) {
1406 $groups->push(new static(array_slice($this->items, $start, $size)));
1407
1408 $start += $size;
1409 }
1410 }
1411
1412 return $groups;
1413 }
1414
1415 /**
1416 * Split a collection into a certain number of groups, and fill the first groups completely.
1417 *
1418 * @param int $numberOfGroups
1419 * @return ($numberOfGroups is positive-int ? static<int, static> : never)
1420 *
1421 * @throws \InvalidArgumentException
1422 */
1423 public function splitIn($numberOfGroups)
1424 {
1425 if ($numberOfGroups < 1) {
1426 throw new InvalidArgumentException('Number of groups must be at least 1.');
1427 }
1428
1429 return $this->chunk((int) ceil($this->count() / $numberOfGroups));
1430 }
1431
1432 /**
1433 * Get the first item in the collection, but only if exactly one item exists. Otherwise, throw an exception.
1434 *
1435 * @param (callable(TValue, TKey): bool)|string|null $key
1436 * @param mixed $operator
1437 * @param mixed $value
1438 * @return TValue
1439 *
1440 * @throws \Illuminate\Support\ItemNotFoundException
1441 * @throws \Illuminate\Support\MultipleItemsFoundException
1442 */
1443 public function sole($key = null, $operator = null, $value = null)
1444 {
1445 $filter = func_num_args() > 1
1446 ? $this->operatorForWhere(...func_get_args())
1447 : $key;
1448
1449 $items = $this->unless($filter == null)->filter($filter);
1450
1451 $count = $items->count();
1452
1453 if ($count === 0) {
1454 throw new ItemNotFoundException;
1455 }
1456
1457 if ($count > 1) {
1458 throw new MultipleItemsFoundException($count);
1459 }
1460
1461 return $items->first();
1462 }
1463
1464 /**
1465 * Determine if the collection contains a single item, optionally matching the given criteria.
1466 *
1467 * @param (callable(TValue, TKey): bool)|string|null $key
1468 * @param mixed $operator
1469 * @param mixed $value
1470 * @return bool
1471 */
1472 public function hasSole($key = null, $operator = null, $value = null): bool
1473 {
1474 $filter = func_num_args() > 1
1475 ? $this->operatorForWhere(...func_get_args())
1476 : $key;
1477
1478 return $this
1479 ->unless($filter == null)
1480 ->filter($filter)
1481 ->count() === 1;
1482 }
1483
1484 /**
1485 * Get the first item in the collection but throw an exception if no matching items exist.
1486 *
1487 * @param (callable(TValue, TKey): bool)|string $key
1488 * @param mixed $operator
1489 * @param mixed $value
1490 * @return TValue
1491 *
1492 * @throws \Illuminate\Support\ItemNotFoundException
1493 */
1494 public function firstOrFail($key = null, $operator = null, $value = null)
1495 {
1496 $filter = func_num_args() > 1
1497 ? $this->operatorForWhere(...func_get_args())
1498 : $key;
1499
1500 $placeholder = new stdClass();
1501
1502 $item = $this->first($filter, $placeholder);
1503
1504 if ($item === $placeholder) {
1505 throw new ItemNotFoundException;
1506 }
1507
1508 return $item;
1509 }
1510
1511 /**
1512 * Chunk the collection into chunks of the given size.
1513 *
1514 * @param int $size
1515 * @param bool $preserveKeys
1516 * @return ($preserveKeys is true ? static<int, static> : static<int, static<int, TValue>>)
1517 */
1518 public function chunk($size, $preserveKeys = true)
1519 {
1520 if ($size <= 0) {
1521 return new static;
1522 }
1523
1524 $chunks = [];
1525
1526 foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
1527 $chunks[] = new static($chunk);
1528 }
1529
1530 return new static($chunks);
1531 }
1532
1533 /**
1534 * Chunk the collection into chunks with a callback.
1535 *
1536 * @param callable(TValue, TKey, static<TKey, TValue>): bool $callback
1537 * @return static<int, static<TKey, TValue>>
1538 */
1539 public function chunkWhile(callable $callback)
1540 {
1541 return new static(
1542 $this->lazy()->chunkWhile($callback)->mapInto(static::class)
1543 );
1544 }
1545
1546 /**
1547 * Sort through each item with a callback.
1548 *
1549 * @param (callable(TValue, TValue): int)|null|int $callback
1550 * @return static
1551 */
1552 public function sort($callback = null)
1553 {
1554 $items = $this->items;
1555
1556 $callback && is_callable($callback)
1557 ? uasort($items, $callback)
1558 : asort($items, $callback ?? SORT_REGULAR);
1559
1560 return new static($items);
1561 }
1562
1563 /**
1564 * Sort items in descending order.
1565 *
1566 * @param int $options
1567 * @return static
1568 */
1569 public function sortDesc($options = SORT_REGULAR)
1570 {
1571 $items = $this->items;
1572
1573 arsort($items, $options);
1574
1575 return new static($items);
1576 }
1577
1578 /**
1579 * Sort the collection using the given callback.
1580 *
1581 * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}>|(callable(TValue, TKey): mixed)|string $callback
1582 * @param int $options
1583 * @param bool $descending
1584 * @return static
1585 */
1586 public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
1587 {
1588 if (is_array($callback) && ! is_callable($callback)) {
1589 return $this->sortByMany($callback, $options);
1590 }
1591
1592 $results = [];
1593
1594 $callback = $this->valueRetriever($callback);
1595
1596 // First we will loop through the items and get the comparator from a callback
1597 // function which we were given. Then, we will sort the returned values and
1598 // grab all the corresponding values for the sorted keys from this array.
1599 foreach ($this->items as $key => $value) {
1600 $results[$key] = $callback($value, $key);
1601 }
1602
1603 $descending ? arsort($results, $options)
1604 : asort($results, $options);
1605
1606 // Once we have sorted all of the keys in the array, we will loop through them
1607 // and grab the corresponding model so we can set the underlying items list
1608 // to the sorted version. Then we'll just return the collection instance.
1609 foreach (array_keys($results) as $key) {
1610 $results[$key] = $this->items[$key];
1611 }
1612
1613 return new static($results);
1614 }
1615
1616 /**
1617 * Sort the collection using multiple comparisons.
1618 *
1619 * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}> $comparisons
1620 * @param int $options
1621 * @return static
1622 */
1623 protected function sortByMany(array $comparisons = [], int $options = SORT_REGULAR)
1624 {
1625 $items = $this->items;
1626
1627 uasort($items, function ($a, $b) use ($comparisons, $options) {
1628 foreach ($comparisons as $comparison) {
1629 $comparison = Arr::wrap($comparison);
1630
1631 $prop = $comparison[0];
1632
1633 $ascending = Arr::get($comparison, 1, true) === true ||
1634 Arr::get($comparison, 1, true) === 'asc';
1635
1636 if (! is_string($prop) && is_callable($prop)) {
1637 $result = $prop($a, $b);
1638 } else {
1639 $values = [data_get($a, $prop), data_get($b, $prop)];
1640
1641 if (! $ascending) {
1642 $values = array_reverse($values);
1643 }
1644
1645 if (($options & SORT_FLAG_CASE) === SORT_FLAG_CASE) {
1646 if (($options & SORT_NATURAL) === SORT_NATURAL) {
1647 $result = strnatcasecmp($values[0], $values[1]);
1648 } else {
1649 $result = strcasecmp($values[0], $values[1]);
1650 }
1651 } else {
1652 $result = match ($options) {
1653 SORT_NUMERIC => (int) $values[0] <=> (int) $values[1],
1654 SORT_STRING => strcmp($values[0], $values[1]),
1655 SORT_NATURAL => strnatcmp((string) $values[0], (string) $values[1]),
1656 SORT_LOCALE_STRING => strcoll($values[0], $values[1]),
1657 default => $values[0] <=> $values[1],
1658 };
1659 }
1660 }
1661
1662 if ($result === 0) {
1663 continue;
1664 }
1665
1666 return $result;
1667 }
1668 });
1669
1670 return new static($items);
1671 }
1672
1673 /**
1674 * Sort the collection in descending order using the given callback.
1675 *
1676 * @param array<array-key, (callable(TValue, TValue): mixed)|(callable(TValue, TKey): mixed)|string|array{string, string}>|(callable(TValue, TKey): mixed)|string $callback
1677 * @param int $options
1678 * @return static
1679 */
1680 public function sortByDesc($callback, $options = SORT_REGULAR)
1681 {
1682 if (is_array($callback) && ! is_callable($callback)) {
1683 foreach ($callback as $index => $key) {
1684 $comparison = Arr::wrap($key);
1685
1686 $comparison[1] = 'desc';
1687
1688 $callback[$index] = $comparison;
1689 }
1690 }
1691
1692 return $this->sortBy($callback, $options, true);
1693 }
1694
1695 /**
1696 * Sort the collection keys.
1697 *
1698 * @param int $options
1699 * @param bool $descending
1700 * @return static
1701 */
1702 public function sortKeys($options = SORT_REGULAR, $descending = false)
1703 {
1704 $items = $this->items;
1705
1706 $descending ? krsort($items, $options) : ksort($items, $options);
1707
1708 return new static($items);
1709 }
1710
1711 /**
1712 * Sort the collection keys in descending order.
1713 *
1714 * @param int $options
1715 * @return static
1716 */
1717 public function sortKeysDesc($options = SORT_REGULAR)
1718 {
1719 return $this->sortKeys($options, true);
1720 }
1721
1722 /**
1723 * Sort the collection keys using a callback.
1724 *
1725 * @param callable(TKey, TKey): int $callback
1726 * @return static
1727 */
1728 public function sortKeysUsing(callable $callback)
1729 {
1730 $items = $this->items;
1731
1732 uksort($items, $callback);
1733
1734 return new static($items);
1735 }
1736
1737 /**
1738 * Splice a portion of the underlying collection array.
1739 *
1740 * @param int $offset
1741 * @param int|null $length
1742 * @param array<array-key, TValue> $replacement
1743 * @return static
1744 */
1745 public function splice($offset, $length = null, $replacement = [])
1746 {
1747 if (func_num_args() === 1) {
1748 return new static(array_splice($this->items, $offset));
1749 }
1750
1751 return new static(array_splice($this->items, $offset, $length, $this->getArrayableItems($replacement)));
1752 }
1753
1754 /**
1755 * Take the first or last {$limit} items.
1756 *
1757 * @param int $limit
1758 * @return static
1759 */
1760 public function take($limit)
1761 {
1762 if ($limit < 0) {
1763 return $this->slice($limit, abs($limit));
1764 }
1765
1766 return $this->slice(0, $limit);
1767 }
1768
1769 /**
1770 * Take items in the collection until the given condition is met.
1771 *
1772 * @param TValue|callable(TValue,TKey): bool $value
1773 * @return static
1774 */
1775 public function takeUntil($value)
1776 {
1777 return new static($this->lazy()->takeUntil($value)->all());
1778 }
1779
1780 /**
1781 * Take items in the collection while the given condition is met.
1782 *
1783 * @param TValue|callable(TValue,TKey): bool $value
1784 * @return static
1785 */
1786 public function takeWhile($value)
1787 {
1788 return new static($this->lazy()->takeWhile($value)->all());
1789 }
1790
1791 /**
1792 * Transform each item in the collection using a callback.
1793 *
1794 * @template TMapValue
1795 *
1796 * @param callable(TValue, TKey): TMapValue $callback
1797 * @return $this
1798 *
1799 * @phpstan-this-out static<TKey, TMapValue>
1800 */
1801 public function transform(callable $callback)
1802 {
1803 $this->items = $this->map($callback)->all();
1804
1805 return $this;
1806 }
1807
1808 /**
1809 * Flatten a multi-dimensional associative array with dots.
1810 *
1811 * @param int $depth
1812 * @return static
1813 */
1814 public function dot($depth = INF)
1815 {
1816 return new static(Arr::dot($this->all(), '', $depth));
1817 }
1818
1819 /**
1820 * Convert a flatten "dot" notation array into an expanded array.
1821 *
1822 * @return static
1823 */
1824 public function undot()
1825 {
1826 return new static(Arr::undot($this->all()));
1827 }
1828
1829 /**
1830 * Return only unique items from the collection array.
1831 *
1832 * @param (callable(TValue, TKey): mixed)|string|null $key
1833 * @param bool $strict
1834 * @return static
1835 */
1836 public function unique($key = null, $strict = false)
1837 {
1838 if (is_null($key) && $strict === false) {
1839 return new static(array_unique($this->items, SORT_REGULAR));
1840 }
1841
1842 $callback = $this->valueRetriever($key);
1843
1844 $exists = [];
1845
1846 return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
1847 if (in_array($id = $callback($item, $key), $exists, $strict)) {
1848 return true;
1849 }
1850
1851 $exists[] = $id;
1852 });
1853 }
1854
1855 /**
1856 * Reset the keys on the underlying array.
1857 *
1858 * @return static<int, TValue>
1859 */
1860 public function values()
1861 {
1862 return new static(array_values($this->items));
1863 }
1864
1865 /**
1866 * Zip the collection together with one or more arrays.
1867 *
1868 * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]);
1869 * => [[1, 4], [2, 5], [3, 6]]
1870 *
1871 * @template TZipValue
1872 *
1873 * @param \Illuminate\Contracts\Support\Arrayable<array-key, TZipValue>|iterable<array-key, TZipValue> ...$items
1874 * @return static<int, static<int, TValue|TZipValue>>
1875 */
1876 public function zip($items)
1877 {
1878 $arrayableItems = array_map(fn ($items) => $this->getArrayableItems($items), func_get_args());
1879
1880 $params = array_merge([fn () => new static(func_get_args()), $this->items], $arrayableItems);
1881
1882 return new static(array_map(...$params));
1883 }
1884
1885 /**
1886 * Pad collection to the specified length with a value.
1887 *
1888 * @template TPadValue
1889 *
1890 * @param int $size
1891 * @param TPadValue $value
1892 * @return static<int, TValue|TPadValue>
1893 */
1894 public function pad($size, $value)
1895 {
1896 return new static(array_pad($this->items, $size, $value));
1897 }
1898
1899 /**
1900 * Get an iterator for the items.
1901 *
1902 * @return \ArrayIterator<TKey, TValue>
1903 */
1904 public function getIterator(): Traversable
1905 {
1906 return new ArrayIterator($this->items);
1907 }
1908
1909 /**
1910 * Count the number of items in the collection.
1911 *
1912 * @return int<0, max>
1913 */
1914 public function count(): int
1915 {
1916 return count($this->items);
1917 }
1918
1919 /**
1920 * Count the number of items in the collection by a field or using a callback.
1921 *
1922 * @param (callable(TValue, TKey): (array-key|\UnitEnum))|string|null $countBy
1923 * @return static<array-key, int>
1924 */
1925 public function countBy($countBy = null)
1926 {
1927 return new static($this->lazy()->countBy($countBy)->all());
1928 }
1929
1930 /**
1931 * Add an item to the collection.
1932 *
1933 * @param TValue $item
1934 * @return $this
1935 */
1936 public function add($item)
1937 {
1938 $this->items[] = $item;
1939
1940 return $this;
1941 }
1942
1943 /**
1944 * Get a base Support collection instance from this collection.
1945 *
1946 * @return \Illuminate\Support\Collection<TKey, TValue>
1947 */
1948 public function toBase()
1949 {
1950 return new self($this);
1951 }
1952
1953 /**
1954 * Determine if an item exists at an offset.
1955 *
1956 * @param TKey $key
1957 * @return bool
1958 */
1959 public function offsetExists($key): bool
1960 {
1961 return isset($this->items[$key]);
1962 }
1963
1964 /**
1965 * Get an item at a given offset.
1966 *
1967 * @param TKey $key
1968 * @return TValue
1969 */
1970 public function offsetGet($key): mixed
1971 {
1972 return $this->items[$key];
1973 }
1974
1975 /**
1976 * Set the item at a given offset.
1977 *
1978 * @param TKey|null $key
1979 * @param TValue $value
1980 * @return void
1981 */
1982 public function offsetSet($key, $value): void
1983 {
1984 if (is_null($key)) {
1985 $this->items[] = $value;
1986 } else {
1987 $this->items[$key] = $value;
1988 }
1989 }
1990
1991 /**
1992 * Unset the item at a given offset.
1993 *
1994 * @param TKey $key
1995 * @return void
1996 */
1997 public function offsetUnset($key): void
1998 {
1999 unset($this->items[$key]);
2000 }
2001 }