Arr.php 32 KB

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