Arr.php 35 KB

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