Debian Codegraph @

lib/3rdParty/composer/illuminate/collections/Traits/EnumeratesValues.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support\Traits;
4
5 use BackedEnum;
6 use CachingIterator;
7 use Closure;
8 use Exception;
9 use Illuminate\Contracts\Support\Arrayable;
10 use Illuminate\Contracts\Support\Jsonable;
11 use Illuminate\Support\Arr;
12 use Illuminate\Support\Collection;
13 use Illuminate\Support\Enumerable;
14 use Illuminate\Support\HigherOrderCollectionProxy;
15 use JsonSerializable;
16 use UnexpectedValueException;
17 use UnitEnum;
18
19 use function Illuminate\Support\enum_value;
20
21 /**
22 * @template TKey of array-key
23 *
24 * @template-covariant TValue
25 *
26 * @property-read HigherOrderCollectionProxy<TKey, TValue> $average
27 * @property-read HigherOrderCollectionProxy<TKey, TValue> $avg
28 * @property-read HigherOrderCollectionProxy<TKey, TValue> $contains
29 * @property-read HigherOrderCollectionProxy<TKey, TValue> $doesntContain
30 * @property-read HigherOrderCollectionProxy<TKey, TValue> $each
31 * @property-read HigherOrderCollectionProxy<TKey, TValue> $every
32 * @property-read HigherOrderCollectionProxy<TKey, TValue> $filter
33 * @property-read HigherOrderCollectionProxy<TKey, TValue> $first
34 * @property-read HigherOrderCollectionProxy<TKey, TValue> $flatMap
35 * @property-read HigherOrderCollectionProxy<TKey, TValue> $groupBy
36 * @property-read HigherOrderCollectionProxy<TKey, TValue> $hasMany
37 * @property-read HigherOrderCollectionProxy<TKey, TValue> $hasSole
38 * @property-read HigherOrderCollectionProxy<TKey, TValue> $keyBy
39 * @property-read HigherOrderCollectionProxy<TKey, TValue> $last
40 * @property-read HigherOrderCollectionProxy<TKey, TValue> $map
41 * @property-read HigherOrderCollectionProxy<TKey, TValue> $max
42 * @property-read HigherOrderCollectionProxy<TKey, TValue> $min
43 * @property-read HigherOrderCollectionProxy<TKey, TValue> $partition
44 * @property-read HigherOrderCollectionProxy<TKey, TValue> $percentage
45 * @property-read HigherOrderCollectionProxy<TKey, TValue> $reject
46 * @property-read HigherOrderCollectionProxy<TKey, TValue> $skipUntil
47 * @property-read HigherOrderCollectionProxy<TKey, TValue> $skipWhile
48 * @property-read HigherOrderCollectionProxy<TKey, TValue> $some
49 * @property-read HigherOrderCollectionProxy<TKey, TValue> $sortBy
50 * @property-read HigherOrderCollectionProxy<TKey, TValue> $sortByDesc
51 * @property-read HigherOrderCollectionProxy<TKey, TValue> $sum
52 * @property-read HigherOrderCollectionProxy<TKey, TValue> $takeUntil
53 * @property-read HigherOrderCollectionProxy<TKey, TValue> $takeWhile
54 * @property-read HigherOrderCollectionProxy<TKey, TValue> $unique
55 * @property-read HigherOrderCollectionProxy<TKey, TValue> $unless
56 * @property-read HigherOrderCollectionProxy<TKey, TValue> $until
57 * @property-read HigherOrderCollectionProxy<TKey, TValue> $when
58 */
59 trait EnumeratesValues
60 {
61 use Conditionable;
62
63 /**
64 * Indicates that the object's string representation should be escaped when __toString is invoked.
65 *
66 * @var bool
67 */
68 protected $escapeWhenCastingToString = false;
69
70 /**
71 * The methods that can be proxied.
72 *
73 * @var array<int, string>
74 */
75 protected static $proxies = [
76 'average',
77 'avg',
78 'contains',
79 'doesntContain',
80 'each',
81 'every',
82 'filter',
83 'first',
84 'flatMap',
85 'groupBy',
86 'hasMany',
87 'hasSole',
88 'keyBy',
89 'last',
90 'map',
91 'max',
92 'min',
93 'partition',
94 'percentage',
95 'reject',
96 'skipUntil',
97 'skipWhile',
98 'some',
99 'sortBy',
100 'sortByDesc',
101 'sum',
102 'takeUntil',
103 'takeWhile',
104 'unique',
105 'unless',
106 'until',
107 'when',
108 ];
109
110 /**
111 * Create a new collection instance if the value isn't one already.
112 *
113 * @template TMakeKey of array-key
114 * @template TMakeValue
115 *
116 * @param \Illuminate\Contracts\Support\Arrayable<TMakeKey, TMakeValue>|iterable<TMakeKey, TMakeValue>|null $items
117 * @return static<TMakeKey, TMakeValue>
118 */
119 public static function make($items = [])
120 {
121 return new static($items);
122 }
123
124 /**
125 * Wrap the given value in a collection if applicable.
126 *
127 * @template TWrapValue
128 *
129 * @param iterable<array-key, TWrapValue>|TWrapValue $value
130 * @return static<array-key, TWrapValue>
131 */
132 public static function wrap($value)
133 {
134 return $value instanceof Enumerable
135 ? new static($value)
136 : new static(Arr::wrap($value));
137 }
138
139 /**
140 * Get the underlying items from the given collection if applicable.
141 *
142 * @template TUnwrapKey of array-key
143 * @template TUnwrapValue
144 *
145 * @param array<TUnwrapKey, TUnwrapValue>|static<TUnwrapKey, TUnwrapValue> $value
146 * @return array<TUnwrapKey, TUnwrapValue>
147 */
148 public static function unwrap($value)
149 {
150 return $value instanceof Enumerable ? $value->all() : $value;
151 }
152
153 /**
154 * Create a new instance with no items.
155 *
156 * @return static
157 */
158 public static function empty()
159 {
160 return new static([]);
161 }
162
163 /**
164 * Create a new collection by invoking the callback a given amount of times.
165 *
166 * @template TTimesValue
167 *
168 * @param int $number
169 * @param (callable(int): TTimesValue)|null $callback
170 * @return static<int, TTimesValue>
171 */
172 public static function times($number, ?callable $callback = null)
173 {
174 if ($number < 1) {
175 return new static;
176 }
177
178 return static::range(1, $number)
179 ->unless($callback == null)
180 ->map($callback);
181 }
182
183 /**
184 * Create a new collection by decoding a JSON string.
185 *
186 * @param string $json
187 * @param int $depth
188 * @param int $flags
189 * @return static<TKey, TValue>
190 */
191 public static function fromJson($json, $depth = 512, $flags = 0)
192 {
193 return new static(json_decode($json, true, $depth, $flags));
194 }
195
196 /**
197 * Get the average value of a given key.
198 *
199 * @param (callable(TValue): float|int)|string|null $callback
200 * @return float|int|null
201 */
202 public function avg($callback = null)
203 {
204 $callback = $this->valueRetriever($callback);
205
206 $reduced = $this->reduce(static function (&$reduce, $value) use ($callback) {
207 if (! is_null($resolved = $callback($value))) {
208 $reduce[0] += $resolved;
209 $reduce[1]++;
210 }
211
212 return $reduce;
213 }, [0, 0]);
214
215 return $reduced[1] ? $reduced[0] / $reduced[1] : null;
216 }
217
218 /**
219 * Alias for the "avg" method.
220 *
221 * @param (callable(TValue): float|int)|string|null $callback
222 * @return float|int|null
223 */
224 public function average($callback = null)
225 {
226 return $this->avg($callback);
227 }
228
229 /**
230 * Alias for the "contains" method.
231 *
232 * @param (callable(TValue, TKey): bool)|TValue|string $key
233 * @param mixed $operator
234 * @param mixed $value
235 * @return bool
236 */
237 public function some($key, $operator = null, $value = null)
238 {
239 return $this->contains(...func_get_args());
240 }
241
242 /**
243 * Dump the given arguments and terminate execution.
244 *
245 * @param mixed ...$args
246 * @return never
247 */
248 public function dd(...$args)
249 {
250 dd($this->all(), ...$args);
251 }
252
253 /**
254 * Dump the items.
255 *
256 * @param mixed ...$args
257 * @return $this
258 */
259 public function dump(...$args)
260 {
261 dump($this->all(), ...$args);
262
263 return $this;
264 }
265
266 /**
267 * Execute a callback over each item.
268 *
269 * @param callable(TValue, TKey): mixed $callback
270 * @return $this
271 */
272 public function each(callable $callback)
273 {
274 foreach ($this as $key => $item) {
275 if ($callback($item, $key) === false) {
276 break;
277 }
278 }
279
280 return $this;
281 }
282
283 /**
284 * Execute a callback over each nested chunk of items.
285 *
286 * @param callable(...mixed): mixed $callback
287 * @return static
288 */
289 public function eachSpread(callable $callback)
290 {
291 return $this->each(function ($chunk, $key) use ($callback) {
292 $chunk[] = $key;
293
294 return $callback(...$chunk);
295 });
296 }
297
298 /**
299 * Determine if all items pass the given truth test.
300 *
301 * @param (callable(TValue, TKey): bool)|TValue|string $key
302 * @param mixed $operator
303 * @param mixed $value
304 * @return bool
305 */
306 public function every($key, $operator = null, $value = null)
307 {
308 if (func_num_args() === 1) {
309 $callback = $this->valueRetriever($key);
310
311 foreach ($this as $k => $v) {
312 if (! $callback($v, $k)) {
313 return false;
314 }
315 }
316
317 return true;
318 }
319
320 return $this->every($this->operatorForWhere(...func_get_args()));
321 }
322
323 /**
324 * Get the first item by the given key value pair.
325 *
326 * @param callable|string $key
327 * @param mixed $operator
328 * @param mixed $value
329 * @return TValue|null
330 */
331 public function firstWhere($key, $operator = null, $value = null)
332 {
333 return $this->first($this->operatorForWhere(...func_get_args()));
334 }
335
336 /**
337 * Determine if the collection contains multiple items, optionally matching the given criteria.
338 *
339 * @param (callable(TValue, TKey): bool)|string|null $key
340 * @param mixed $operator
341 * @param mixed $value
342 * @return bool
343 */
344 public function hasMany($key = null, $operator = null, $value = null): bool
345 {
346 $filter = func_num_args() > 1
347 ? $this->operatorForWhere(...func_get_args())
348 : $key;
349
350 return $this
351 ->unless($filter == null)
352 ->filter($filter)
353 ->take(2)
354 ->count() === 2;
355 }
356
357 /**
358 * Get a single key's value from the first matching item in the collection.
359 *
360 * @template TValueDefault
361 *
362 * @param string $key
363 * @param TValueDefault|(\Closure(): TValueDefault) $default
364 * @return TValue|TValueDefault
365 */
366 public function value($key, $default = null)
367 {
368 $value = $this->first(function ($target) use ($key) {
369 return data_has($target, $key);
370 });
371
372 return data_get($value, $key, $default);
373 }
374
375 /**
376 * Ensure that every item in the collection is of the expected type.
377 *
378 * @template TEnsureOfType
379 *
380 * @param class-string<TEnsureOfType>|array<array-key, class-string<TEnsureOfType>>|'string'|'int'|'float'|'bool'|'array'|'null' $type
381 * @return static<TKey, TEnsureOfType>
382 *
383 * @throws \UnexpectedValueException
384 */
385 public function ensure($type)
386 {
387 $allowedTypes = is_array($type) ? $type : [$type];
388
389 return $this->each(function ($item, $index) use ($allowedTypes) {
390 $itemType = get_debug_type($item);
391
392 foreach ($allowedTypes as $allowedType) {
393 if ($itemType === $allowedType || $item instanceof $allowedType) {
394 return true;
395 }
396 }
397
398 throw new UnexpectedValueException(
399 sprintf("Collection should only include [%s] items, but '%s' found at position %d.", implode(', ', $allowedTypes), $itemType, $index)
400 );
401 });
402 }
403
404 /**
405 * Determine if the collection is not empty.
406 *
407 * @phpstan-assert-if-true TValue $this->first()
408 * @phpstan-assert-if-true TValue $this->last()
409 *
410 * @phpstan-assert-if-false null $this->first()
411 * @phpstan-assert-if-false null $this->last()
412 *
413 * @return bool
414 */
415 public function isNotEmpty()
416 {
417 return ! $this->isEmpty();
418 }
419
420 /**
421 * Run a map over each nested chunk of items.
422 *
423 * @template TMapSpreadValue
424 *
425 * @param callable(mixed...): TMapSpreadValue $callback
426 * @return static<TKey, TMapSpreadValue>
427 */
428 public function mapSpread(callable $callback)
429 {
430 return $this->map(function ($chunk, $key) use ($callback) {
431 $chunk[] = $key;
432
433 return $callback(...$chunk);
434 });
435 }
436
437 /**
438 * Run a grouping map over the items.
439 *
440 * The callback should return an associative array with a single key/value pair.
441 *
442 * @template TMapToGroupsKey of array-key
443 * @template TMapToGroupsValue
444 *
445 * @param callable(TValue, TKey): array<TMapToGroupsKey, TMapToGroupsValue> $callback
446 * @return static<TMapToGroupsKey, static<int, TMapToGroupsValue>>
447 */
448 public function mapToGroups(callable $callback)
449 {
450 $groups = $this->mapToDictionary($callback);
451
452 return $groups->map($this->make(...));
453 }
454
455 /**
456 * Map a collection and flatten the result by a single level.
457 *
458 * @template TFlatMapKey of array-key
459 * @template TFlatMapValue
460 *
461 * @param callable(TValue, TKey): (\Illuminate\Support\Collection<TFlatMapKey, TFlatMapValue>|array<TFlatMapKey, TFlatMapValue>) $callback
462 * @return static<TFlatMapKey, TFlatMapValue>
463 */
464 public function flatMap(callable $callback)
465 {
466 return $this->map($callback)->collapse();
467 }
468
469 /**
470 * Map the values into a new class.
471 *
472 * @template TMapIntoValue
473 *
474 * @param class-string<TMapIntoValue> $class
475 * @return static<TKey, TMapIntoValue>
476 */
477 public function mapInto($class)
478 {
479 if (is_subclass_of($class, BackedEnum::class)) {
480 return $this->map(fn ($value, $key) => $class::from($value));
481 }
482
483 return $this->map(fn ($value, $key) => new $class($value, $key));
484 }
485
486 /**
487 * Get the min value of a given key.
488 *
489 * @param (callable(TValue):mixed)|string|null $callback
490 * @return mixed
491 */
492 public function min($callback = null)
493 {
494 $callback = $this->valueRetriever($callback);
495
496 return $this->map(fn ($value) => $callback($value))
497 ->reject(fn ($value) => is_null($value))
498 ->reduce(fn ($result, $value) => is_null($result) || $value < $result ? $value : $result);
499 }
500
501 /**
502 * Get the max value of a given key.
503 *
504 * @param (callable(TValue):mixed)|string|null $callback
505 * @return mixed
506 */
507 public function max($callback = null)
508 {
509 $callback = $this->valueRetriever($callback);
510
511 return $this->reject(fn ($value) => is_null($value))->reduce(function ($result, $item) use ($callback) {
512 $value = $callback($item);
513
514 return is_null($result) || $value > $result ? $value : $result;
515 });
516 }
517
518 /**
519 * "Paginate" the collection by slicing it into a smaller collection.
520 *
521 * @param int $page
522 * @param int $perPage
523 * @return static
524 */
525 public function forPage($page, $perPage)
526 {
527 $offset = max(0, ($page - 1) * $perPage);
528
529 return $this->slice($offset, $perPage);
530 }
531
532 /**
533 * Partition the collection into two arrays using the given callback or key.
534 *
535 * @param (callable(TValue, TKey): bool)|TValue|string $key
536 * @param mixed $operator
537 * @param mixed $value
538 * @return static<int<0, 1>, static<TKey, TValue>>
539 */
540 public function partition($key, $operator = null, $value = null)
541 {
542 $callback = func_num_args() === 1
543 ? $this->valueRetriever($key)
544 : $this->operatorForWhere(...func_get_args());
545
546 [$passed, $failed] = Arr::partition($this->getIterator(), $callback);
547
548 return new static([new static($passed), new static($failed)]);
549 }
550
551 /**
552 * Calculate the percentage of items that pass a given truth test.
553 *
554 * @param (callable(TValue, TKey): bool) $callback
555 * @param int $precision
556 * @return float|null
557 */
558 public function percentage(callable $callback, int $precision = 2)
559 {
560 if ($this->isEmpty()) {
561 return null;
562 }
563
564 return round(
565 $this->filter($callback)->count() / $this->count() * 100,
566 $precision
567 );
568 }
569
570 /**
571 * Get the sum of the given values.
572 *
573 * @template TReturnType
574 *
575 * @param (callable(TValue): TReturnType)|string|null $callback
576 * @return ($callback is callable ? TReturnType : mixed)
577 */
578 public function sum($callback = null)
579 {
580 $callback = is_null($callback)
581 ? $this->identity()
582 : $this->valueRetriever($callback);
583
584 return $this->reduce(fn ($result, $item) => $result + $callback($item), 0);
585 }
586
587 /**
588 * Apply the callback if the collection is empty.
589 *
590 * @template TWhenEmptyReturnType
591 *
592 * @param (callable($this): TWhenEmptyReturnType) $callback
593 * @param (callable($this): TWhenEmptyReturnType)|null $default
594 * @return $this|TWhenEmptyReturnType
595 */
596 public function whenEmpty(callable $callback, ?callable $default = null)
597 {
598 return $this->when($this->isEmpty(), $callback, $default);
599 }
600
601 /**
602 * Apply the callback if the collection is not empty.
603 *
604 * @template TWhenNotEmptyReturnType
605 *
606 * @param callable($this): TWhenNotEmptyReturnType $callback
607 * @param (callable($this): TWhenNotEmptyReturnType)|null $default
608 * @return $this|TWhenNotEmptyReturnType
609 */
610 public function whenNotEmpty(callable $callback, ?callable $default = null)
611 {
612 return $this->when($this->isNotEmpty(), $callback, $default);
613 }
614
615 /**
616 * Apply the callback unless the collection is empty.
617 *
618 * @template TUnlessEmptyReturnType
619 *
620 * @param callable($this): TUnlessEmptyReturnType $callback
621 * @param (callable($this): TUnlessEmptyReturnType)|null $default
622 * @return $this|TUnlessEmptyReturnType
623 */
624 public function unlessEmpty(callable $callback, ?callable $default = null)
625 {
626 return $this->whenNotEmpty($callback, $default);
627 }
628
629 /**
630 * Apply the callback unless the collection is not empty.
631 *
632 * @template TUnlessNotEmptyReturnType
633 *
634 * @param callable($this): TUnlessNotEmptyReturnType $callback
635 * @param (callable($this): TUnlessNotEmptyReturnType)|null $default
636 * @return $this|TUnlessNotEmptyReturnType
637 */
638 public function unlessNotEmpty(callable $callback, ?callable $default = null)
639 {
640 return $this->whenEmpty($callback, $default);
641 }
642
643 /**
644 * Filter items by the given key value pair.
645 *
646 * @param callable|string $key
647 * @param mixed $operator
648 * @param mixed $value
649 * @return static
650 */
651 public function where($key, $operator = null, $value = null)
652 {
653 return $this->filter($this->operatorForWhere(...func_get_args()));
654 }
655
656 /**
657 * Filter items where the value for the given key is null.
658 *
659 * @param string|null $key
660 * @return static
661 */
662 public function whereNull($key = null)
663 {
664 return $this->whereStrict($key, null);
665 }
666
667 /**
668 * Filter items where the value for the given key is not null.
669 *
670 * @param string|null $key
671 * @return static
672 */
673 public function whereNotNull($key = null)
674 {
675 return $this->where($key, '!==', null);
676 }
677
678 /**
679 * Filter items by the given key value pair using strict comparison.
680 *
681 * @param string $key
682 * @param mixed $value
683 * @return static
684 */
685 public function whereStrict($key, $value)
686 {
687 return $this->where($key, '===', $value);
688 }
689
690 /**
691 * Filter items by the given key value pair.
692 *
693 * @param string $key
694 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
695 * @param bool $strict
696 * @return static
697 */
698 public function whereIn($key, $values, $strict = false)
699 {
700 $values = $this->getArrayableItems($values);
701
702 return $this->filter(fn ($item) => in_array(data_get($item, $key), $values, $strict));
703 }
704
705 /**
706 * Filter items by the given key value pair using strict comparison.
707 *
708 * @param string $key
709 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
710 * @return static
711 */
712 public function whereInStrict($key, $values)
713 {
714 return $this->whereIn($key, $values, true);
715 }
716
717 /**
718 * Filter items such that the value of the given key is between the given values.
719 *
720 * @param string $key
721 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
722 * @return static
723 */
724 public function whereBetween($key, $values)
725 {
726 return $this->where($key, '>=', reset($values))->where($key, '<=', end($values));
727 }
728
729 /**
730 * Filter items such that the value of the given key is not between the given values.
731 *
732 * @param string $key
733 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
734 * @return static
735 */
736 public function whereNotBetween($key, $values)
737 {
738 return $this->filter(
739 fn ($item) => data_get($item, $key) < reset($values) || data_get($item, $key) > end($values)
740 );
741 }
742
743 /**
744 * Filter items by the given key value pair.
745 *
746 * @param string $key
747 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
748 * @param bool $strict
749 * @return static
750 */
751 public function whereNotIn($key, $values, $strict = false)
752 {
753 $values = $this->getArrayableItems($values);
754
755 return $this->reject(fn ($item) => in_array(data_get($item, $key), $values, $strict));
756 }
757
758 /**
759 * Filter items by the given key value pair using strict comparison.
760 *
761 * @param string $key
762 * @param \Illuminate\Contracts\Support\Arrayable|iterable $values
763 * @return static
764 */
765 public function whereNotInStrict($key, $values)
766 {
767 return $this->whereNotIn($key, $values, true);
768 }
769
770 /**
771 * Filter the items, removing any items that don't match the given type(s).
772 *
773 * @template TWhereInstanceOf
774 *
775 * @param class-string<TWhereInstanceOf>|array<array-key, class-string<TWhereInstanceOf>> $type
776 * @return static<TKey, TWhereInstanceOf>
777 */
778 public function whereInstanceOf($type)
779 {
780 return $this->filter(function ($value) use ($type) {
781 if (is_array($type)) {
782 foreach ($type as $classType) {
783 if ($value instanceof $classType) {
784 return true;
785 }
786 }
787
788 return false;
789 }
790
791 return $value instanceof $type;
792 });
793 }
794
795 /**
796 * Pass the collection to the given callback and return the result.
797 *
798 * @template TPipeReturnType
799 *
800 * @param callable($this): TPipeReturnType $callback
801 * @return TPipeReturnType
802 */
803 public function pipe(callable $callback)
804 {
805 return $callback($this);
806 }
807
808 /**
809 * Pass the collection into a new class.
810 *
811 * @template TPipeIntoValue
812 *
813 * @param class-string<TPipeIntoValue> $class
814 * @return TPipeIntoValue
815 */
816 public function pipeInto($class)
817 {
818 return new $class($this);
819 }
820
821 /**
822 * Pass the collection through a series of callable pipes and return the result.
823 *
824 * @param array<callable> $callbacks
825 * @return mixed
826 */
827 public function pipeThrough($callbacks)
828 {
829 return (new Collection($callbacks))->reduce(
830 fn ($carry, $callback) => $callback($carry),
831 $this,
832 );
833 }
834
835 /**
836 * Reduce the collection to a single value.
837 *
838 * @template TReduceInitial
839 * @template TReduceReturnType
840 *
841 * @param callable(TReduceInitial|TReduceReturnType, TValue, TKey): TReduceReturnType $callback
842 * @param TReduceInitial $initial
843 * @return TReduceReturnType
844 */
845 public function reduce(callable $callback, $initial = null)
846 {
847 $result = $initial;
848
849 foreach ($this as $key => $value) {
850 $result = $callback($result, $value, $key);
851 }
852
853 return $result;
854 }
855
856 /**
857 * Reduce the collection to multiple aggregate values.
858 *
859 * @param callable $callback
860 * @param mixed ...$initial
861 * @return array
862 *
863 * @throws \UnexpectedValueException
864 */
865 public function reduceSpread(callable $callback, ...$initial)
866 {
867 $result = $initial;
868
869 foreach ($this as $key => $value) {
870 $result = call_user_func_array($callback, array_merge($result, [$value, $key]));
871
872 if (! is_array($result)) {
873 throw new UnexpectedValueException(sprintf(
874 "%s::reduceSpread expects reducer to return an array, but got a '%s' instead.",
875 class_basename(static::class), gettype($result)
876 ));
877 }
878 }
879
880 return $result;
881 }
882
883 /**
884 * Reduce an associative collection to a single value.
885 *
886 * @template TReduceWithKeysInitial
887 * @template TReduceWithKeysReturnType
888 *
889 * @param callable(TReduceWithKeysInitial|TReduceWithKeysReturnType, TValue, TKey): TReduceWithKeysReturnType $callback
890 * @param TReduceWithKeysInitial $initial
891 * @return TReduceWithKeysReturnType
892 */
893 public function reduceWithKeys(callable $callback, $initial = null)
894 {
895 return $this->reduce($callback, $initial);
896 }
897
898 /**
899 * Create a collection of all elements that do not pass a given truth test.
900 *
901 * @param (callable(TValue, TKey): bool)|bool|TValue $callback
902 * @return static
903 */
904 public function reject($callback = true)
905 {
906 $useAsCallable = $this->useAsCallable($callback);
907
908 return $this->filter(function ($value, $key) use ($callback, $useAsCallable) {
909 return $useAsCallable
910 ? ! $callback($value, $key)
911 : $value != $callback;
912 });
913 }
914
915 /**
916 * Pass the collection to the given callback and then return it.
917 *
918 * @param callable($this): mixed $callback
919 * @return $this
920 */
921 public function tap(callable $callback)
922 {
923 $callback($this);
924
925 return $this;
926 }
927
928 /**
929 * Return only unique items from the collection array.
930 *
931 * @param (callable(TValue, TKey): mixed)|string|null $key
932 * @param bool $strict
933 * @return static
934 */
935 public function unique($key = null, $strict = false)
936 {
937 $callback = $this->valueRetriever($key);
938
939 $exists = [];
940
941 return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
942 if (in_array($id = $callback($item, $key), $exists, $strict)) {
943 return true;
944 }
945
946 $exists[] = $id;
947 });
948 }
949
950 /**
951 * Return only unique items from the collection array using strict comparison.
952 *
953 * @param (callable(TValue, TKey): mixed)|string|null $key
954 * @return static
955 */
956 public function uniqueStrict($key = null)
957 {
958 return $this->unique($key, true);
959 }
960
961 /**
962 * Collect the values into a collection.
963 *
964 * @return \Illuminate\Support\Collection<TKey, TValue>
965 */
966 public function collect()
967 {
968 return new Collection($this->all());
969 }
970
971 /**
972 * Get the collection of items as a plain array.
973 *
974 * @return array<TKey, mixed>
975 */
976 public function toArray()
977 {
978 return $this->map(fn ($value) => $value instanceof Arrayable ? $value->toArray() : $value)->all();
979 }
980
981 /**
982 * Convert the object into something JSON serializable.
983 *
984 * @return array<TKey, mixed>
985 */
986 public function jsonSerialize(): array
987 {
988 return array_map(function ($value) {
989 return match (true) {
990 $value instanceof JsonSerializable => $value->jsonSerialize(),
991 $value instanceof Jsonable => json_decode($value->toJson(), true),
992 $value instanceof Arrayable => $value->toArray(),
993 default => $value,
994 };
995 }, $this->all());
996 }
997
998 /**
999 * Get the collection of items as JSON.
1000 *
1001 * @param int $options
1002 * @return string
1003 */
1004 public function toJson($options = 0)
1005 {
1006 return json_encode($this->jsonSerialize(), $options);
1007 }
1008
1009 /**
1010 * Get the collection of items as pretty print formatted JSON.
1011 *
1012 * @param int $options
1013 * @return string
1014 */
1015 public function toPrettyJson(int $options = 0)
1016 {
1017 return $this->toJson(JSON_PRETTY_PRINT | $options);
1018 }
1019
1020 /**
1021 * Get a CachingIterator instance.
1022 *
1023 * @param int $flags
1024 * @return \CachingIterator
1025 */
1026 public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING)
1027 {
1028 return new CachingIterator($this->getIterator(), $flags);
1029 }
1030
1031 /**
1032 * Convert the collection to its string representation.
1033 *
1034 * @return string
1035 */
1036 public function __toString()
1037 {
1038 return $this->escapeWhenCastingToString
1039 ? e($this->toJson())
1040 : $this->toJson();
1041 }
1042
1043 /**
1044 * Indicate that the model's string representation should be escaped when __toString is invoked.
1045 *
1046 * @param bool $escape
1047 * @return $this
1048 */
1049 public function escapeWhenCastingToString($escape = true)
1050 {
1051 $this->escapeWhenCastingToString = $escape;
1052
1053 return $this;
1054 }
1055
1056 /**
1057 * Add a method to the list of proxied methods.
1058 *
1059 * @param string $method
1060 * @return void
1061 */
1062 public static function proxy($method)
1063 {
1064 static::$proxies[] = $method;
1065 }
1066
1067 /**
1068 * Dynamically access collection proxies.
1069 *
1070 * @param string $key
1071 * @return mixed
1072 *
1073 * @throws \Exception
1074 */
1075 public function __get($key)
1076 {
1077 if (! in_array($key, static::$proxies)) {
1078 throw new Exception("Property [{$key}] does not exist on this collection instance.");
1079 }
1080
1081 return new HigherOrderCollectionProxy($this, $key);
1082 }
1083
1084 /**
1085 * Results array of items from Collection or Arrayable.
1086 *
1087 * @param mixed $items
1088 * @return array<TKey, TValue>
1089 */
1090 protected function getArrayableItems($items)
1091 {
1092 return is_null($items) || is_scalar($items) || $items instanceof UnitEnum
1093 ? Arr::wrap($items)
1094 : Arr::from($items);
1095 }
1096
1097 /**
1098 * Get an operator checker callback.
1099 *
1100 * @param callable|string $key
1101 * @param string|null $operator
1102 * @param mixed $value
1103 * @return \Closure
1104 */
1105 protected function operatorForWhere($key, $operator = null, $value = null)
1106 {
1107 if ($this->useAsCallable($key)) {
1108 return $key;
1109 }
1110
1111 if (func_num_args() === 1) {
1112 $value = true;
1113
1114 $operator = '=';
1115 }
1116
1117 if (func_num_args() === 2) {
1118 $value = $operator;
1119
1120 $operator = '=';
1121 }
1122
1123 return function ($item) use ($key, $operator, $value) {
1124 $retrieved = enum_value(data_get($item, $key));
1125 $value = enum_value($value);
1126
1127 $strings = array_filter([$retrieved, $value], function ($value) {
1128 return match (true) {
1129 is_string($value) => true,
1130 $value instanceof \Stringable => true,
1131 default => false,
1132 };
1133 });
1134
1135 if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) {
1136 return in_array($operator, ['!=', '<>', '!==']);
1137 }
1138
1139 switch ($operator) {
1140 default:
1141 case '=':
1142 case '==': return $retrieved == $value;
1143 case '!=':
1144 case '<>': return $retrieved != $value;
1145 case '<': return $retrieved < $value;
1146 case '>': return $retrieved > $value;
1147 case '<=': return $retrieved <= $value;
1148 case '>=': return $retrieved >= $value;
1149 case '===': return $retrieved === $value;
1150 case '!==': return $retrieved !== $value;
1151 case '<=>': return $retrieved <=> $value;
1152 }
1153 };
1154 }
1155
1156 /**
1157 * Determine if the given value is callable, but not a string.
1158 *
1159 * @param mixed $value
1160 * @return bool
1161 */
1162 protected function useAsCallable($value)
1163 {
1164 return ! is_string($value) && is_callable($value);
1165 }
1166
1167 /**
1168 * Get a value retrieving callback.
1169 *
1170 * @param callable|string|null $value
1171 * @return callable
1172 */
1173 protected function valueRetriever($value)
1174 {
1175 if ($this->useAsCallable($value)) {
1176 return $value;
1177 }
1178
1179 return fn ($item) => data_get($item, $value);
1180 }
1181
1182 /**
1183 * Make a function to check an item's equality.
1184 *
1185 * @param mixed $value
1186 * @return \Closure(mixed): bool
1187 */
1188 protected function equality($value)
1189 {
1190 return fn ($item) => $item === $value;
1191 }
1192
1193 /**
1194 * Make a function using another function, by negating its result.
1195 *
1196 * @param \Closure $callback
1197 * @return \Closure
1198 */
1199 protected function negate(Closure $callback)
1200 {
1201 return fn (...$params) => ! $callback(...$params);
1202 }
1203
1204 /**
1205 * Make a function that returns what's passed to it.
1206 *
1207 * @return \Closure(TValue): TValue
1208 */
1209 protected function identity()
1210 {
1211 return fn ($value) => $value;
1212 }
1213 }