Debian Codegraph @

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

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support;
4
5 use ArgumentCountError;
6 use ArrayAccess;
7 use Closure;
8 use Illuminate\Contracts\Support\Arrayable;
9 use Illuminate\Contracts\Support\Jsonable;
10 use Illuminate\Support\Traits\Macroable;
11 use InvalidArgumentException;
12 use JsonSerializable;
13 use Random\Randomizer;
14 use Traversable;
15 use WeakMap;
16
17 class Arr
18 {
19 use Macroable;
20
21 /**
22 * Determine whether the given value is array accessible.
23 *
24 * @param mixed $value
25 * @return bool
26 */
27 public static function accessible($value)
28 {
29 return is_array($value) || $value instanceof ArrayAccess;
30 }
31
32 /**
33 * Determine whether the given value is arrayable.
34 *
35 * @param mixed $value
36 * @return ($value is array
37 * ? true
38 * : ($value is \Illuminate\Contracts\Support\Arrayable
39 * ? true
40 * : ($value is \Traversable
41 * ? true
42 * : ($value is \Illuminate\Contracts\Support\Jsonable
43 * ? true
44 * : ($value is \JsonSerializable ? true : false)
45 * )
46 * )
47 * )
48 * )
49 */
50 public static function arrayable($value)
51 {
52 return is_array($value)
53 || $value instanceof Arrayable
54 || $value instanceof Traversable
55 || $value instanceof Jsonable
56 || $value instanceof JsonSerializable;
57 }
58
59 /**
60 * Add an element to an array using "dot" notation if it doesn't exist.
61 *
62 * @param array $array
63 * @param string|int|float $key
64 * @param mixed $value
65 * @return array
66 */
67 public static function add($array, $key, $value)
68 {
69 if (is_null(static::get($array, $key))) {
70 static::set($array, $key, $value);
71 }
72
73 return $array;
74 }
75
76 /**
77 * Get an array item from an array using "dot" notation.
78 *
79 * @throws \InvalidArgumentException
80 */
81 public static function array(ArrayAccess|array $array, string|int|null $key, ?array $default = null): array
82 {
83 $value = Arr::get($array, $key, $default);
84
85 if (! is_array($value)) {
86 throw new InvalidArgumentException(
87 sprintf('Array value for key [%s] must be an array, %s found.', $key, gettype($value))
88 );
89 }
90
91 return $value;
92 }
93
94 /**
95 * Get a boolean item from an array using "dot" notation.
96 *
97 * @throws \InvalidArgumentException
98 */
99 public static function boolean(ArrayAccess|array $array, string|int|null $key, ?bool $default = null): bool
100 {
101 $value = Arr::get($array, $key, $default);
102
103 if (! is_bool($value)) {
104 throw new InvalidArgumentException(
105 sprintf('Array value for key [%s] must be a boolean, %s found.', $key, gettype($value))
106 );
107 }
108
109 return $value;
110 }
111
112 /**
113 * Collapse an array of arrays into a single array.
114 *
115 * @param iterable $array
116 * @return array
117 */
118 public static function collapse($array)
119 {
120 $results = [];
121
122 foreach ($array as $values) {
123 if ($values instanceof Collection) {
124 $results[] = $values->all();
125 } elseif (is_array($values)) {
126 $results[] = $values;
127 }
128 }
129
130 return array_merge([], ...$results);
131 }
132
133 /**
134 * Cross join the given arrays, returning all possible permutations.
135 *
136 * @template TValue
137 *
138 * @param iterable<TValue> ...$arrays
139 * @return array<int, array<array-key, TValue>>
140 */
141 public static function crossJoin(...$arrays)
142 {
143 $results = [[]];
144
145 foreach ($arrays as $index => $array) {
146 $append = [];
147
148 foreach ($results as $product) {
149 foreach ($array as $item) {
150 $product[$index] = $item;
151
152 $append[] = $product;
153 }
154 }
155
156 $results = $append;
157 }
158
159 return $results;
160 }
161
162 /**
163 * Divide an array into two arrays. One with keys and the other with values.
164 *
165 * @template TKey of array-key
166 * @template TValue
167 *
168 * @param array<TKey, TValue> $array
169 * @return array{TKey[], TValue[]}
170 */
171 public static function divide($array)
172 {
173 return [array_keys($array), array_values($array)];
174 }
175
176 /**
177 * Flatten a multi-dimensional associative array with dots.
178 *
179 * @param iterable $array
180 * @param string $prepend
181 * @param int $depth
182 * @return array
183 */
184 public static function dot($array, $prepend = '', $depth = INF)
185 {
186 $results = [];
187
188 $flatten = function ($data, $prefix, $currentDepth) use (&$results, &$flatten, $depth): void {
189 foreach ($data as $key => $value) {
190 $newKey = $prefix.$key;
191
192 if (is_array($value) && ! empty($value) && $currentDepth < $depth) {
193 $flatten($value, $newKey.'.', $currentDepth + 1);
194 } else {
195 $results[$newKey] = $value;
196 }
197 }
198 };
199
200 $flatten($array, $prepend, 0);
201
202 // Destroy self-referencing closure to avoid memory leak...
203 $flatten = null;
204
205 return $results;
206 }
207
208 /**
209 * Convert a flatten "dot" notation array into an expanded array.
210 *
211 * @param iterable $array
212 * @return array
213 */
214 public static function undot($array)
215 {
216 $results = [];
217
218 foreach ($array as $key => $value) {
219 static::set($results, $key, $value);
220 }
221
222 return $results;
223 }
224
225 /**
226 * Get all of the given array except for a specified array of keys.
227 *
228 * @param array $array
229 * @param array|string|int|float $keys
230 * @return array
231 */
232 public static function except($array, $keys)
233 {
234 static::forget($array, $keys);
235
236 return $array;
237 }
238
239 /**
240 * Get all of the given array except for a specified array of values.
241 *
242 * @param array $array
243 * @param mixed $values
244 * @param bool $strict
245 * @return array
246 */
247 public static function exceptValues($array, $values, $strict = false)
248 {
249 $values = (array) $values;
250
251 return array_filter($array, function ($value) use ($values, $strict) {
252 return ! in_array($value, $values, $strict);
253 });
254 }
255
256 /**
257 * Determine if the given key exists in the provided array.
258 *
259 * @param \ArrayAccess|array $array
260 * @param string|int|float $key
261 * @return bool
262 */
263 public static function exists($array, $key)
264 {
265 if ($array instanceof Enumerable) {
266 return $array->has($key);
267 }
268
269 if ($array instanceof ArrayAccess) {
270 return $array->offsetExists($key);
271 }
272
273 if (is_float($key) || is_null($key)) {
274 $key = (string) $key;
275 }
276
277 return array_key_exists($key, $array);
278 }
279
280 /**
281 * Return the first element in an iterable passing a given truth test.
282 *
283 * @template TKey
284 * @template TValue
285 * @template TFirstDefault
286 *
287 * @param iterable<TKey, TValue> $array
288 * @param (callable(TValue, TKey): bool)|null $callback
289 * @param TFirstDefault|(\Closure(): TFirstDefault) $default
290 * @return TValue|TFirstDefault
291 */
292 public static function first($array, ?callable $callback = null, $default = null)
293 {
294 if (is_null($callback)) {
295 if (empty($array)) {
296 return value($default);
297 }
298
299 if (is_array($array)) {
300 return array_first($array);
301 }
302
303 foreach ($array as $item) {
304 return $item;
305 }
306
307 return value($default);
308 }
309
310 $array = static::from($array);
311
312 $key = array_find_key($array, $callback);
313
314 return $key !== null ? $array[$key] : value($default);
315 }
316
317 /**
318 * Return the last element in an array passing a given truth test.
319 *
320 * @template TKey
321 * @template TValue
322 * @template TLastDefault
323 *
324 * @param iterable<TKey, TValue> $array
325 * @param (callable(TValue, TKey): bool)|null $callback
326 * @param TLastDefault|(\Closure(): TLastDefault) $default
327 * @return TValue|TLastDefault
328 */
329 public static function last($array, ?callable $callback = null, $default = null)
330 {
331 if (is_null($callback)) {
332 return empty($array) ? value($default) : array_last($array);
333 }
334
335 return static::first(array_reverse($array, true), $callback, $default);
336 }
337
338 /**
339 * Take the first or last {$limit} items from an array.
340 *
341 * @param array $array
342 * @param int $limit
343 * @return array
344 */
345 public static function take($array, $limit)
346 {
347 if ($limit < 0) {
348 return array_slice($array, $limit, abs($limit));
349 }
350
351 return array_slice($array, 0, $limit);
352 }
353
354 /**
355 * Flatten a multi-dimensional array into a single level.
356 *
357 * @param iterable $array
358 * @param int $depth
359 * @return array
360 */
361 public static function flatten($array, $depth = INF)
362 {
363 $result = [];
364
365 foreach ($array as $item) {
366 $item = $item instanceof Collection ? $item->all() : $item;
367
368 if (! is_array($item)) {
369 $result[] = $item;
370 } else {
371 $values = $depth === 1
372 ? array_values($item)
373 : static::flatten($item, $depth - 1);
374
375 foreach ($values as $value) {
376 $result[] = $value;
377 }
378 }
379 }
380
381 return $result;
382 }
383
384 /**
385 * Get a float item from an array using "dot" notation.
386 *
387 * @throws \InvalidArgumentException
388 */
389 public static function float(ArrayAccess|array $array, string|int|null $key, ?float $default = null): float
390 {
391 $value = Arr::get($array, $key, $default);
392
393 if (! is_float($value)) {
394 throw new InvalidArgumentException(
395 sprintf('Array value for key [%s] must be a float, %s found.', $key, gettype($value))
396 );
397 }
398
399 return $value;
400 }
401
402 /**
403 * Remove one or many array items from a given array using "dot" notation.
404 *
405 * @param array $array
406 * @param array|string|int|float $keys
407 * @return void
408 */
409 public static function forget(&$array, $keys)
410 {
411 $original = &$array;
412
413 $keys = (array) $keys;
414
415 if (count($keys) === 0) {
416 return;
417 }
418
419 foreach ($keys as $key) {
420 // if the exact key exists in the top-level, remove it
421 if (static::exists($array, $key)) {
422 unset($array[$key]);
423
424 continue;
425 }
426
427 $parts = explode('.', $key);
428
429 // clean up before each pass
430 $array = &$original;
431
432 while (count($parts) > 1) {
433 $part = array_shift($parts);
434
435 if (isset($array[$part]) && static::accessible($array[$part])) {
436 $array = &$array[$part];
437 } else {
438 continue 2;
439 }
440 }
441
442 unset($array[array_shift($parts)]);
443 }
444 }
445
446 /**
447 * Get the underlying array of items from the given argument.
448 *
449 * @template TKey of array-key = array-key
450 * @template TValue = mixed
451 *
452 * @param array<TKey, TValue>|Enumerable<TKey, TValue>|Arrayable<TKey, TValue>|WeakMap<object, TValue>|Traversable<TKey, TValue>|Jsonable|JsonSerializable|object $items
453 * @return ($items is WeakMap ? list<TValue> : array<TKey, TValue>)
454 *
455 * @throws \InvalidArgumentException
456 */
457 public static function from($items)
458 {
459 return match (true) {
460 is_array($items) => $items,
461 $items instanceof Enumerable => $items->all(),
462 $items instanceof Arrayable => $items->toArray(),
463 $items instanceof WeakMap => iterator_to_array($items, false),
464 $items instanceof Traversable => iterator_to_array($items),
465 $items instanceof Jsonable => json_decode($items->toJson(), true),
466 $items instanceof JsonSerializable => (array) $items->jsonSerialize(),
467 is_object($items) => (array) $items,
468 default => throw new InvalidArgumentException('Items cannot be represented by a scalar value.'),
469 };
470 }
471
472 /**
473 * Get an item from an array using "dot" notation.
474 *
475 * @param \ArrayAccess|array $array
476 * @param string|int|null $key
477 * @param mixed $default
478 * @return mixed
479 */
480 public static function get($array, $key, $default = null)
481 {
482 if (! static::accessible($array)) {
483 return value($default);
484 }
485
486 if (is_null($key)) {
487 return $array;
488 }
489
490 if (static::exists($array, $key)) {
491 return $array[$key];
492 }
493
494 if (! str_contains($key, '.')) {
495 return value($default);
496 }
497
498 foreach (explode('.', $key) as $segment) {
499 if (static::accessible($array) && static::exists($array, $segment)) {
500 $array = $array[$segment];
501 } else {
502 return value($default);
503 }
504 }
505
506 return $array;
507 }
508
509 /**
510 * Check if an item or items exist in an array using "dot" notation.
511 *
512 * @param \ArrayAccess|array $array
513 * @param string|array $keys
514 * @return bool
515 */
516 public static function has($array, $keys)
517 {
518 $keys = (array) $keys;
519
520 if (! $array || $keys === []) {
521 return false;
522 }
523
524 foreach ($keys as $key) {
525 $subKeyArray = $array;
526
527 if (static::exists($array, $key)) {
528 continue;
529 }
530
531 foreach (explode('.', $key) as $segment) {
532 if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
533 $subKeyArray = $subKeyArray[$segment];
534 } else {
535 return false;
536 }
537 }
538 }
539
540 return true;
541 }
542
543 /**
544 * Determine if all keys exist in an array using "dot" notation.
545 *
546 * @param \ArrayAccess|array $array
547 * @param string|array $keys
548 * @return bool
549 */
550 public static function hasAll($array, $keys)
551 {
552 $keys = (array) $keys;
553
554 if (! $array || $keys === []) {
555 return false;
556 }
557
558 foreach ($keys as $key) {
559 if (! static::has($array, $key)) {
560 return false;
561 }
562 }
563
564 return true;
565 }
566
567 /**
568 * Determine if any of the keys exist in an array using "dot" notation.
569 *
570 * @param \ArrayAccess|array $array
571 * @param string|array $keys
572 * @return bool
573 */
574 public static function hasAny($array, $keys)
575 {
576 if (is_null($keys)) {
577 return false;
578 }
579
580 $keys = (array) $keys;
581
582 if (! $array) {
583 return false;
584 }
585
586 if ($keys === []) {
587 return false;
588 }
589
590 foreach ($keys as $key) {
591 if (static::has($array, $key)) {
592 return true;
593 }
594 }
595
596 return false;
597 }
598
599 /**
600 * Determine if all items pass the given truth test.
601 *
602 * @param iterable $array
603 * @param (callable(mixed, array-key): bool) $callback
604 * @return bool
605 */
606 public static function every($array, callable $callback)
607 {
608 return array_all($array, $callback);
609 }
610
611 /**
612 * Determine if some items pass the given truth test.
613 *
614 * @param iterable $array
615 * @param (callable(mixed, array-key): bool) $callback
616 * @return bool
617 */
618 public static function some($array, callable $callback)
619 {
620 return array_any($array, $callback);
621 }
622
623 /**
624 * Get an integer item from an array using "dot" notation.
625 *
626 * @throws \InvalidArgumentException
627 */
628 public static function integer(ArrayAccess|array $array, string|int|null $key, ?int $default = null): int
629 {
630 $value = Arr::get($array, $key, $default);
631
632 if (! is_int($value)) {
633 throw new InvalidArgumentException(
634 sprintf('Array value for key [%s] must be an integer, %s found.', $key, gettype($value))
635 );
636 }
637
638 return $value;
639 }
640
641 /**
642 * Determines if an array is associative.
643 *
644 * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
645 *
646 * @param array $array
647 * @return ($array is list ? false : true)
648 */
649 public static function isAssoc(array $array)
650 {
651 return ! array_is_list($array);
652 }
653
654 /**
655 * Determines if an array is a list.
656 *
657 * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between.
658 *
659 * @param array $array
660 * @return ($array is list ? true : false)
661 */
662 public static function isList($array)
663 {
664 return array_is_list($array);
665 }
666
667 /**
668 * Join all items using a string. The final items can use a separate glue string.
669 *
670 * @param array $array
671 * @param string $glue
672 * @param string $finalGlue
673 * @return string
674 */
675 public static function join($array, $glue, $finalGlue = '')
676 {
677 if ($finalGlue === '') {
678 return implode($glue, $array);
679 }
680
681 if (count($array) === 0) {
682 return '';
683 }
684
685 if (count($array) === 1) {
686 return array_last($array);
687 }
688
689 $finalItem = array_pop($array);
690
691 return implode($glue, $array).$finalGlue.$finalItem;
692 }
693
694 /**
695 * Key an associative array by a field or using a callback.
696 *
697 * @param iterable $array
698 * @param callable|array|string $keyBy
699 * @return array
700 */
701 public static function keyBy($array, $keyBy)
702 {
703 return (new Collection($array))->keyBy($keyBy)->all();
704 }
705
706 /**
707 * Prepend the key names of an associative array.
708 *
709 * @param array $array
710 * @param string $prependWith
711 * @return array
712 */
713 public static function prependKeysWith($array, $prependWith)
714 {
715 return static::mapWithKeys($array, fn ($item, $key) => [$prependWith.$key => $item]);
716 }
717
718 /**
719 * Get a subset of the items from the given array.
720 *
721 * @param array $array
722 * @param array|string $keys
723 * @return array
724 */
725 public static function only($array, $keys)
726 {
727 return array_intersect_key($array, array_flip((array) $keys));
728 }
729
730 /**
731 * Get a subset of the items from the given array by value.
732 *
733 * @param array $array
734 * @param mixed $values
735 * @param bool $strict
736 * @return array
737 */
738 public static function onlyValues($array, $values, $strict = false)
739 {
740 $values = (array) $values;
741
742 return array_filter($array, function ($value) use ($values, $strict) {
743 return in_array($value, $values, $strict);
744 });
745 }
746
747 /**
748 * Select an array of values from an array.
749 *
750 * @param array $array
751 * @param array|string $keys
752 * @return array
753 */
754 public static function select($array, $keys)
755 {
756 $keys = static::wrap($keys);
757
758 return static::map($array, function ($item) use ($keys) {
759 $result = [];
760
761 foreach ($keys as $key) {
762 if (Arr::accessible($item) && Arr::exists($item, $key)) {
763 $result[$key] = $item[$key];
764 } elseif (is_object($item) && isset($item->{$key})) {
765 $result[$key] = $item->{$key};
766 }
767 }
768
769 return $result;
770 });
771 }
772
773 /**
774 * Pluck an array of values from an array.
775 *
776 * @param iterable $array
777 * @param string|array|int|Closure|null $value
778 * @param string|array|Closure|null $key
779 * @return array
780 */
781 public static function pluck($array, $value, $key = null)
782 {
783 $results = [];
784
785 [$value, $key] = static::explodePluckParameters($value, $key);
786
787 foreach ($array as $item) {
788 $itemValue = $value instanceof Closure
789 ? $value($item)
790 : data_get($item, $value);
791
792 // If the key is "null", we will just append the value to the array and keep
793 // looping. Otherwise we will key the array using the value of the key we
794 // received from the developer. Then we'll return the final array form.
795 if (is_null($key)) {
796 $results[] = $itemValue;
797 } else {
798 $itemKey = $key instanceof Closure
799 ? $key($item)
800 : data_get($item, $key);
801
802 if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
803 $itemKey = (string) $itemKey;
804 }
805
806 $results[$itemKey] = $itemValue;
807 }
808 }
809
810 return $results;
811 }
812
813 /**
814 * Explode the "value" and "key" arguments passed to "pluck".
815 *
816 * @param Closure|array|string $value
817 * @param string|array|Closure|null $key
818 * @return array
819 */
820 protected static function explodePluckParameters($value, $key)
821 {
822 $value = is_string($value) ? explode('.', $value) : $value;
823
824 $key = is_null($key) || is_array($key) || $key instanceof Closure ? $key : explode('.', $key);
825
826 return [$value, $key];
827 }
828
829 /**
830 * Run a map over each of the items in the array.
831 *
832 * @param array $array
833 * @param callable $callback
834 * @return array
835 */
836 public static function map(array $array, callable $callback)
837 {
838 $keys = array_keys($array);
839
840 try {
841 $items = array_map($callback, $array, $keys);
842 } catch (ArgumentCountError) {
843 $items = array_map($callback, $array);
844 }
845
846 return array_combine($keys, $items);
847 }
848
849 /**
850 * Run an associative map over each of the items.
851 *
852 * The callback should return an associative array with a single key/value pair.
853 *
854 * @template TKey
855 * @template TValue
856 * @template TMapWithKeysKey of array-key
857 * @template TMapWithKeysValue
858 *
859 * @param array<TKey, TValue> $array
860 * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
861 * @return array
862 */
863 public static function mapWithKeys(array $array, callable $callback)
864 {
865 $result = [];
866
867 foreach ($array as $key => $value) {
868 $assoc = $callback($value, $key);
869
870 foreach ($assoc as $mapKey => $mapValue) {
871 $result[$mapKey] = $mapValue;
872 }
873 }
874
875 return $result;
876 }
877
878 /**
879 * Run a map over each nested chunk of items.
880 *
881 * @template TKey
882 * @template TValue
883 *
884 * @param array<TKey, array> $array
885 * @param callable(mixed...): TValue $callback
886 * @return array<TKey, TValue>
887 */
888 public static function mapSpread(array $array, callable $callback)
889 {
890 return static::map($array, function ($chunk, $key) use ($callback) {
891 $chunk[] = $key;
892
893 return $callback(...$chunk);
894 });
895 }
896
897 /**
898 * Push an item onto the beginning of an array.
899 *
900 * @param array $array
901 * @param mixed $value
902 * @param mixed $key
903 * @return array
904 */
905 public static function prepend($array, $value, $key = null)
906 {
907 if (func_num_args() == 2) {
908 array_unshift($array, $value);
909 } else {
910 $array = [$key => $value] + $array;
911 }
912
913 return $array;
914 }
915
916 /**
917 * Get a value from the array, and remove it.
918 *
919 * @param array $array
920 * @param string|int $key
921 * @param mixed $default
922 * @return mixed
923 */
924 public static function pull(&$array, $key, $default = null)
925 {
926 $value = static::get($array, $key, $default);
927
928 static::forget($array, $key);
929
930 return $value;
931 }
932
933 /**
934 * Convert the array into a query string.
935 *
936 * @param array $array
937 * @return string
938 */
939 public static function query($array)
940 {
941 return http_build_query($array, '', '&', PHP_QUERY_RFC3986);
942 }
943
944 /**
945 * Get one or a specified number of random values from an array.
946 *
947 * @param array $array
948 * @param int|null $number
949 * @param bool $preserveKeys
950 * @return mixed
951 *
952 * @throws \InvalidArgumentException
953 */
954 public static function random($array, $number = null, $preserveKeys = false)
955 {
956 $requested = is_null($number) ? 1 : $number;
957
958 $count = count($array);
959
960 if ($requested > $count) {
961 throw new InvalidArgumentException(
962 "You requested {$requested} items, but there are only {$count} items available."
963 );
964 }
965
966 if (empty($array) || (! is_null($number) && $number <= 0)) {
967 return is_null($number) ? null : [];
968 }
969
970 $keys = (new Randomizer)->pickArrayKeys($array, $requested);
971
972 if (is_null($number)) {
973 return $array[$keys[0]];
974 }
975
976 $results = [];
977
978 if ($preserveKeys) {
979 foreach ($keys as $key) {
980 $results[$key] = $array[$key];
981 }
982 } else {
983 foreach ($keys as $key) {
984 $results[] = $array[$key];
985 }
986 }
987
988 return $results;
989 }
990
991 /**
992 * Set an array item to a given value using "dot" notation.
993 *
994 * If no key is given to the method, the entire array will be replaced.
995 *
996 * @param array $array
997 * @param string|int|null $key
998 * @param mixed $value
999 * @return array
1000 */
1001 public static function set(&$array, $key, $value)
1002 {
1003 if (is_null($key)) {
1004 return $array = $value;
1005 }
1006
1007 $keys = explode('.', $key);
1008
1009 foreach ($keys as $i => $key) {
1010 if (count($keys) === 1) {
1011 break;
1012 }
1013
1014 unset($keys[$i]);
1015
1016 // If the key doesn't exist at this depth, we will just create an empty array
1017 // to hold the next value, allowing us to create the arrays to hold final
1018 // values at the correct depth. Then we'll keep digging into the array.
1019 if (! isset($array[$key]) || ! is_array($array[$key])) {
1020 $array[$key] = [];
1021 }
1022
1023 $array = &$array[$key];
1024 }
1025
1026 $array[array_shift($keys)] = $value;
1027
1028 return $array;
1029 }
1030
1031 /**
1032 * Push an item into an array using "dot" notation.
1033 *
1034 * @param \ArrayAccess|array $array
1035 * @param string|int|null $key
1036 * @param mixed $values
1037 * @return array
1038 */
1039 public static function push(ArrayAccess|array &$array, string|int|null $key, mixed ...$values): array
1040 {
1041 $target = static::array($array, $key, []);
1042
1043 array_push($target, ...$values);
1044
1045 return static::set($array, $key, $target);
1046 }
1047
1048 /**
1049 * Shuffle the given array and return the result.
1050 *
1051 * @param array $array
1052 * @return array
1053 */
1054 public static function shuffle($array)
1055 {
1056 return (new Randomizer)->shuffleArray($array);
1057 }
1058
1059 /**
1060 * Get the first item in the array, but only if exactly one item exists. Otherwise, throw an exception.
1061 *
1062 * @param array $array
1063 * @param (callable(mixed, array-key): array)|null $callback
1064 *
1065 * @throws \Illuminate\Support\ItemNotFoundException
1066 * @throws \Illuminate\Support\MultipleItemsFoundException
1067 */
1068 public static function sole($array, ?callable $callback = null)
1069 {
1070 if ($callback) {
1071 $array = static::where($array, $callback);
1072 }
1073
1074 $count = count($array);
1075
1076 if ($count === 0) {
1077 throw new ItemNotFoundException;
1078 }
1079
1080 if ($count > 1) {
1081 throw new MultipleItemsFoundException($count);
1082 }
1083
1084 return static::first($array);
1085 }
1086
1087 /**
1088 * Sort the array using the given callback or "dot" notation.
1089 *
1090 * @template TKey of array-key
1091 * @template TValue
1092 *
1093 * @param iterable<TKey, TValue> $array
1094 * @param callable|string|null|array<int, (callable(TValue, TValue): -1|0|1)|array{string, 'asc'|'desc'}> $callback
1095 * @return array<TKey, TValue>
1096 */
1097 public static function sort($array, $callback = null)
1098 {
1099 return (new Collection($array))->sortBy($callback)->all();
1100 }
1101
1102 /**
1103 * Sort the array in descending order using the given callback or "dot" notation.
1104 *
1105 * @template TKey of array-key
1106 * @template TValue
1107 *
1108 * @param iterable<TKey, TValue> $array
1109 * @param callable|string|null|array<int, (callable(TValue, TValue): -1|0|1)|array{string, 'asc'|'desc'}> $callback
1110 * @return array<TKey, TValue>
1111 */
1112 public static function sortDesc($array, $callback = null)
1113 {
1114 return (new Collection($array))->sortByDesc($callback)->all();
1115 }
1116
1117 /**
1118 * Recursively sort an array by keys and values.
1119 *
1120 * @template TKey of array-key
1121 * @template TValue
1122 *
1123 * @param array<TKey, TValue> $array
1124 * @param int-mask-of<SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_LOCALE_STRING|SORT_NATURAL|SORT_FLAG_CASE> $options
1125 * @param bool $descending
1126 * @return array<TKey, TValue>
1127 */
1128 public static function sortRecursive($array, $options = SORT_REGULAR, $descending = false)
1129 {
1130 foreach ($array as &$value) {
1131 if (is_array($value)) {
1132 $value = static::sortRecursive($value, $options, $descending);
1133 }
1134 }
1135
1136 if (! array_is_list($array)) {
1137 $descending
1138 ? krsort($array, $options)
1139 : ksort($array, $options);
1140 } else {
1141 $descending
1142 ? rsort($array, $options)
1143 : sort($array, $options);
1144 }
1145
1146 return $array;
1147 }
1148
1149 /**
1150 * Recursively sort an array by keys and values in descending order.
1151 *
1152 * @template TKey of array-key
1153 * @template TValue
1154 *
1155 * @param array<TKey, TValue> $array
1156 * @param int-mask-of<SORT_REGULAR|SORT_NUMERIC|SORT_STRING|SORT_LOCALE_STRING|SORT_NATURAL|SORT_FLAG_CASE> $options
1157 * @return array<TKey, TValue>
1158 */
1159 public static function sortRecursiveDesc($array, $options = SORT_REGULAR)
1160 {
1161 return static::sortRecursive($array, $options, true);
1162 }
1163
1164 /**
1165 * Get a string item from an array using "dot" notation.
1166 *
1167 * @throws \InvalidArgumentException
1168 */
1169 public static function string(ArrayAccess|array $array, string|int|null $key, ?string $default = null): string
1170 {
1171 $value = Arr::get($array, $key, $default);
1172
1173 if (! is_string($value)) {
1174 throw new InvalidArgumentException(
1175 sprintf('Array value for key [%s] must be a string, %s found.', $key, gettype($value))
1176 );
1177 }
1178
1179 return $value;
1180 }
1181
1182 /**
1183 * Conditionally compile classes from an array into a CSS class list.
1184 *
1185 * @param array<string, bool>|array<int, string|int>|string $array
1186 * @return ($array is array<string, false> ? '' : ($array is '' ? '' : ($array is array{} ? '' : non-empty-string)))
1187 */
1188 public static function toCssClasses($array)
1189 {
1190 $classList = static::wrap($array);
1191
1192 $classes = [];
1193
1194 foreach ($classList as $class => $constraint) {
1195 if (is_numeric($class)) {
1196 $classes[] = $constraint;
1197 } elseif ($constraint) {
1198 $classes[] = $class;
1199 }
1200 }
1201
1202 return implode(' ', $classes);
1203 }
1204
1205 /**
1206 * Conditionally compile styles from an array into a style list.
1207 *
1208 * @param array<string, bool>|array<int, string|int>|string $array
1209 * @return ($array is array<string, false> ? '' : ($array is '' ? '' : ($array is array{} ? '' : non-empty-string)))
1210 */
1211 public static function toCssStyles($array)
1212 {
1213 $styleList = static::wrap($array);
1214
1215 $styles = [];
1216
1217 foreach ($styleList as $class => $constraint) {
1218 if (is_numeric($class)) {
1219 $styles[] = Str::finish($constraint, ';');
1220 } elseif ($constraint) {
1221 $styles[] = Str::finish($class, ';');
1222 }
1223 }
1224
1225 return implode(' ', $styles);
1226 }
1227
1228 /**
1229 * Filter the array using the given callback.
1230 *
1231 * @template TKey of array-key
1232 * @template TValue
1233 *
1234 * @param array<TKey, TValue> $array
1235 * @param callable(TValue, TKey): bool $callback
1236 * @return array<TKey, TValue>
1237 */
1238 public static function where($array, callable $callback)
1239 {
1240 return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
1241 }
1242
1243 /**
1244 * Filter the array using the negation of the given callback.
1245 *
1246 * @template TKey of array-key
1247 * @template TValue
1248 *
1249 * @param array<TKey, TValue> $array
1250 * @param callable(TValue, TKey): bool $callback
1251 * @return array<TKey, TValue>
1252 */
1253 public static function reject($array, callable $callback)
1254 {
1255 return static::where($array, fn ($value, $key) => ! $callback($value, $key));
1256 }
1257
1258 /**
1259 * Partition the array into two arrays using the given callback.
1260 *
1261 * @template TKey of array-key
1262 * @template TValue of mixed
1263 *
1264 * @param iterable<TKey, TValue> $array
1265 * @param callable(TValue, TKey): bool $callback
1266 * @return array<int<0, 1>, array<TKey, TValue>>
1267 */
1268 public static function partition($array, callable $callback)
1269 {
1270 $passed = [];
1271 $failed = [];
1272
1273 foreach ($array as $key => $item) {
1274 if ($callback($item, $key)) {
1275 $passed[$key] = $item;
1276 } else {
1277 $failed[$key] = $item;
1278 }
1279 }
1280
1281 return [$passed, $failed];
1282 }
1283
1284 /**
1285 * Filter items where the value is not null.
1286 *
1287 * @param array $array
1288 * @return array
1289 */
1290 public static function whereNotNull($array)
1291 {
1292 return static::where($array, fn ($value) => ! is_null($value));
1293 }
1294
1295 /**
1296 * If the given value is not an array and not null, wrap it in one.
1297 *
1298 * @template TKey of array-key = array-key
1299 * @template TValue
1300 *
1301 * @param array<TKey, TValue>|TValue|null $value
1302 * @return ($value is null ? array{} : ($value is array ? array<TKey, TValue> : array{TValue}))
1303 */
1304 public static function wrap($value)
1305 {
1306 if (is_null($value)) {
1307 return [];
1308 }
1309
1310 return is_array($value) ? $value : [$value];
1311 }
1312 }