Arr.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Collection;
  12. use ArgumentCountError;
  13. use ArrayAccess;
  14. use Hyperf\Macroable\Macroable;
  15. use Hyperf\Stringable\Str;
  16. use InvalidArgumentException;
  17. /**
  18. * @template TKey of array-key
  19. * @template TValue
  20. *
  21. * Most of the methods in this file come from illuminate/collections,
  22. * thanks Laravel Team provide such a useful class.
  23. */
  24. class Arr
  25. {
  26. use Macroable;
  27. /**
  28. * Determine whether the given value is array accessible.
  29. */
  30. public static function accessible(mixed $value): bool
  31. {
  32. return is_array($value) || $value instanceof ArrayAccess;
  33. }
  34. /**
  35. * Add an element to an array using "dot" notation if it doesn't exist.
  36. */
  37. public static function add(array $array, string $key, mixed $value): array
  38. {
  39. if (is_null(static::get($array, $key))) {
  40. static::set($array, $key, $value);
  41. }
  42. return $array;
  43. }
  44. /**
  45. * Collapse an array of arrays into a single array.
  46. */
  47. public static function collapse(array $array): array
  48. {
  49. $results = [];
  50. foreach ($array as $values) {
  51. if ($values instanceof Collection) {
  52. $values = $values->all();
  53. } elseif (! is_array($values)) {
  54. continue;
  55. }
  56. $results[] = $values;
  57. }
  58. return array_merge([], ...$results);
  59. }
  60. /**
  61. * Cross join the given arrays, returning all possible permutations.
  62. *
  63. * @param array ...$arrays
  64. */
  65. public static function crossJoin(...$arrays): array
  66. {
  67. $results = [[]];
  68. foreach ($arrays as $index => $array) {
  69. $append = [];
  70. foreach ($results as $product) {
  71. foreach ($array as $item) {
  72. $product[$index] = $item;
  73. $append[] = $product;
  74. }
  75. }
  76. $results = $append;
  77. }
  78. return $results;
  79. }
  80. /**
  81. * Divide an array into two arrays. One with keys and the other with values.
  82. */
  83. public static function divide(array $array): array
  84. {
  85. return [array_keys($array), array_values($array)];
  86. }
  87. /**
  88. * Flatten a multi-dimensional associative array with dots.
  89. */
  90. public static function dot(array $array, string $prepend = ''): array
  91. {
  92. $results = [];
  93. foreach ($array as $key => $value) {
  94. if (is_array($value) && ! empty($value)) {
  95. $results = array_merge($results, static::dot($value, $prepend . $key . '.'));
  96. } else {
  97. $results[$prepend . $key] = $value;
  98. }
  99. }
  100. return $results;
  101. }
  102. /**
  103. * Get all the given array except for a specified array of keys.
  104. */
  105. public static function except(array $array, array|int|string $keys): array
  106. {
  107. static::forget($array, $keys);
  108. return $array;
  109. }
  110. /**
  111. * Determine if the given key exists in the provided array.
  112. */
  113. public static function exists(array|ArrayAccess $array, int|string $key): bool
  114. {
  115. if ($array instanceof ArrayAccess) {
  116. return $array->offsetExists($key);
  117. }
  118. return array_key_exists($key, $array);
  119. }
  120. /**
  121. * Return the first element in an array passing a given truth test.
  122. */
  123. public static function first(array $array, ?callable $callback = null, mixed $default = null): mixed
  124. {
  125. if (is_null($callback)) {
  126. if (empty($array)) {
  127. return value($default);
  128. }
  129. foreach ($array as $item) {
  130. return $item;
  131. }
  132. }
  133. foreach ($array as $key => $value) {
  134. if (call_user_func($callback, $value, $key)) {
  135. return $value;
  136. }
  137. }
  138. return value($default);
  139. }
  140. /**
  141. * Return the last element in an array passing a given truth test.
  142. */
  143. public static function last(array $array, ?callable $callback = null, mixed $default = null): mixed
  144. {
  145. if (is_null($callback)) {
  146. return empty($array) ? value($default) : end($array);
  147. }
  148. return static::first(array_reverse($array, true), $callback, $default);
  149. }
  150. /**
  151. * Flatten a multi-dimensional array into a single level.
  152. */
  153. public static function flatten(array $array, float|int $depth = INF): array
  154. {
  155. $result = [];
  156. foreach ($array as $item) {
  157. $item = $item instanceof Collection ? $item->all() : $item;
  158. if (! is_array($item)) {
  159. $result[] = $item;
  160. } else {
  161. $values = $depth <= 1
  162. ? array_values($item)
  163. : static::flatten($item, $depth - 1);
  164. foreach ($values as $value) {
  165. $result[] = $value;
  166. }
  167. }
  168. }
  169. return $result;
  170. }
  171. /**
  172. * Remove one or many array items from a given array using "dot" notation.
  173. *
  174. * @param array|string $keys
  175. */
  176. public static function forget(array &$array, array|int|string $keys): void
  177. {
  178. $original = &$array;
  179. $keys = (array) $keys;
  180. if (count($keys) === 0) {
  181. return;
  182. }
  183. foreach ($keys as $key) {
  184. // if the exact key exists in the top-level, remove it
  185. if (static::exists($array, $key)) {
  186. unset($array[$key]);
  187. continue;
  188. }
  189. $parts = explode('.', (string) $key);
  190. // clean up before each pass
  191. $array = &$original;
  192. while (count($parts) > 1) {
  193. $part = array_shift($parts);
  194. if (isset($array[$part]) && is_array($array[$part])) {
  195. $array = &$array[$part];
  196. } else {
  197. continue 2;
  198. }
  199. }
  200. unset($array[array_shift($parts)]);
  201. }
  202. }
  203. /**
  204. * Get an item from an array using "dot" notation.
  205. */
  206. public static function get(mixed $array, null|int|string $key = null, mixed $default = null)
  207. {
  208. if (! static::accessible($array)) {
  209. return value($default);
  210. }
  211. if (is_null($key)) {
  212. return $array;
  213. }
  214. if (static::exists($array, $key)) {
  215. return $array[$key];
  216. }
  217. if (! is_string($key) || ! str_contains($key, '.')) {
  218. return $array[$key] ?? value($default);
  219. }
  220. foreach (explode('.', $key) as $segment) {
  221. if (static::accessible($array) && static::exists($array, $segment)) {
  222. $array = $array[$segment];
  223. } else {
  224. return value($default);
  225. }
  226. }
  227. return $array;
  228. }
  229. /**
  230. * Check if an item or items exist in an array using "dot" notation.
  231. *
  232. * @param null|array|string $keys
  233. */
  234. public static function has(array|ArrayAccess $array, null|array|int|string $keys): bool
  235. {
  236. if (is_null($keys)) {
  237. return false;
  238. }
  239. $keys = (array) $keys;
  240. if (! $array) {
  241. return false;
  242. }
  243. if ($keys === []) {
  244. return false;
  245. }
  246. foreach ($keys as $key) {
  247. $subKeyArray = $array;
  248. if (static::exists($array, $key)) {
  249. continue;
  250. }
  251. foreach (explode('.', (string) $key) as $segment) {
  252. if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
  253. $subKeyArray = $subKeyArray[$segment];
  254. } else {
  255. return false;
  256. }
  257. }
  258. }
  259. return true;
  260. }
  261. /**
  262. * Determine if any of the keys exist in an array using "dot" notation.
  263. */
  264. public static function hasAny(array|ArrayAccess $array, null|array|int|string $keys): bool
  265. {
  266. if (is_null($keys)) {
  267. return false;
  268. }
  269. $keys = (array) $keys;
  270. if (! $array) {
  271. return false;
  272. }
  273. if ($keys === []) {
  274. return false;
  275. }
  276. foreach ($keys as $key) {
  277. if (static::has($array, $key)) {
  278. return true;
  279. }
  280. }
  281. return false;
  282. }
  283. /**
  284. * Determines if an array is associative.
  285. * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
  286. */
  287. public static function isAssoc(array $array): bool
  288. {
  289. $keys = array_keys($array);
  290. return array_keys($keys) !== $keys;
  291. }
  292. /**
  293. * Determines if an array is a list.
  294. *
  295. * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between.
  296. */
  297. public static function isList(array $array): bool
  298. {
  299. return array_is_list($array);
  300. }
  301. /**
  302. * Run an associative map over each of the items.
  303. *
  304. * The callback should return an associative array with a single key/value pair.
  305. *
  306. * @template TMapWithKeysKey of array-key
  307. * @template TMapWithKeysValue
  308. *
  309. * @param array<TKey, TValue> $array
  310. * @param callable(TValue, TKey): array<TMapWithKeysKey, TMapWithKeysValue> $callback
  311. * @return array
  312. */
  313. public static function mapWithKeys(array $array, callable $callback)
  314. {
  315. $result = [];
  316. foreach ($array as $key => $value) {
  317. $assoc = $callback($value, $key);
  318. foreach ($assoc as $mapKey => $mapValue) {
  319. $result[$mapKey] = $mapValue;
  320. }
  321. }
  322. return $result;
  323. }
  324. /**
  325. * Get a subset of the items from the given array.
  326. */
  327. public static function only(array $array, array|int|string $keys): array
  328. {
  329. return array_intersect_key($array, array_flip((array) $keys));
  330. }
  331. /**
  332. * Pluck an array of values from an array.
  333. */
  334. public static function pluck(array $array, array|string $value, null|array|string $key = null): array
  335. {
  336. $results = [];
  337. [$value, $key] = static::explodePluckParameters($value, $key);
  338. foreach ($array as $item) {
  339. $itemValue = data_get($item, $value);
  340. // If the key is "null", we will just append the value to the array and keep
  341. // looping. Otherwise, we will key the array using the value of the key we
  342. // received from the developer. Then we'll return the final array form.
  343. if (is_null($key)) {
  344. $results[] = $itemValue;
  345. } else {
  346. $itemKey = data_get($item, $key);
  347. if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
  348. $itemKey = (string) $itemKey;
  349. }
  350. $results[$itemKey] = $itemValue;
  351. }
  352. }
  353. return $results;
  354. }
  355. /**
  356. * Push an item onto the beginning of an array.
  357. *
  358. * @param array<TKey, TValue> $array
  359. * @param null|TKey $key
  360. * @param TValue $value
  361. * @return array<TKey, TValue>
  362. */
  363. public static function prepend(array $array, mixed $value, null|int|string $key = null): array
  364. {
  365. if (is_null($key)) {
  366. array_unshift($array, $value);
  367. } else {
  368. $array = [$key => $value] + $array;
  369. }
  370. return $array;
  371. }
  372. /**
  373. * Get a value from the array, and remove it.
  374. */
  375. public static function pull(array &$array, string $key, mixed $default = null): mixed
  376. {
  377. $value = static::get($array, $key, $default);
  378. static::forget($array, $key);
  379. return $value;
  380. }
  381. /**
  382. * Get one or a specified number of random values from an array.
  383. *
  384. * @throws InvalidArgumentException
  385. */
  386. public static function random(array $array, ?int $number = null): mixed
  387. {
  388. $requested = is_null($number) ? 1 : $number;
  389. $count = count($array);
  390. if ($requested > $count) {
  391. throw new InvalidArgumentException("You requested {$requested} items, but there are only {$count} items available.");
  392. }
  393. if (is_null($number)) {
  394. return $array[array_rand($array)];
  395. }
  396. if ($number === 0) {
  397. return [];
  398. }
  399. $keys = array_rand($array, $number);
  400. $results = [];
  401. foreach ((array) $keys as $key) {
  402. $results[] = $array[$key];
  403. }
  404. return $results;
  405. }
  406. /**
  407. * Set an array item to a given value using "dot" notation.
  408. * If no key is given to the method, the entire array will be replaced.
  409. */
  410. public static function set(array &$array, null|int|string $key, mixed $value): array
  411. {
  412. if (is_null($key)) {
  413. return $array = $value;
  414. }
  415. if (! is_string($key)) {
  416. $array[$key] = $value;
  417. return $array;
  418. }
  419. $keys = explode('.', $key);
  420. while (count($keys) > 1) {
  421. $key = array_shift($keys);
  422. // If the key doesn't exist at this depth, we will just create an empty array
  423. // to hold the next value, allowing us to create the arrays to hold final
  424. // values at the correct depth. Then we'll keep digging into the array.
  425. if (! isset($array[$key]) || ! is_array($array[$key])) {
  426. $array[$key] = [];
  427. }
  428. $array = &$array[$key];
  429. }
  430. $array[array_shift($keys)] = $value;
  431. return $array;
  432. }
  433. /**
  434. * Shuffle the given array and return the result.
  435. */
  436. public static function shuffle(array $array, ?int $seed = null): array
  437. {
  438. if (empty($array)) {
  439. return [];
  440. }
  441. if (! is_null($seed)) {
  442. mt_srand($seed);
  443. shuffle($array);
  444. mt_srand();
  445. return $array;
  446. }
  447. shuffle($array);
  448. return $array;
  449. }
  450. /**
  451. * Sort the array using the given callback or "dot" notation.
  452. */
  453. public static function sort(array $array, null|callable|string $callback = null): array
  454. {
  455. return Collection::make($array)->sortBy($callback)->all();
  456. }
  457. /**
  458. * Recursively sort an array by keys and values.
  459. */
  460. public static function sortRecursive(array $array, int $options = SORT_REGULAR, bool $descending = false): array
  461. {
  462. foreach ($array as &$value) {
  463. if (is_array($value)) {
  464. $value = static::sortRecursive($value, $options, $descending);
  465. }
  466. }
  467. if (static::isAssoc($array)) {
  468. $descending ? krsort($array, $options) : ksort($array, $options);
  469. } else {
  470. $descending ? rsort($array, $options) : sort($array, $options);
  471. }
  472. return $array;
  473. }
  474. /**
  475. * Convert the array into a query string.
  476. */
  477. public static function query(array $array): string
  478. {
  479. return http_build_query($array, '', '&', PHP_QUERY_RFC3986);
  480. }
  481. /**
  482. * Filter the array using the given callback.
  483. */
  484. public static function where(array $array, callable $callback): array
  485. {
  486. return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
  487. }
  488. /**
  489. * If the given value is not an array and not null, wrap it in one.
  490. * @param mixed $value
  491. */
  492. public static function wrap($value): array
  493. {
  494. if (is_null($value)) {
  495. return [];
  496. }
  497. return ! is_array($value) ? [$value] : $value;
  498. }
  499. /**
  500. * Make array elements unique.
  501. */
  502. public static function unique(array $array): array
  503. {
  504. $result = [];
  505. foreach ($array as $key => $item) {
  506. if (is_array($item)) {
  507. $result[$key] = self::unique($item);
  508. } else {
  509. $result[$key] = $item;
  510. }
  511. }
  512. if (! self::isAssoc($result)) {
  513. return array_unique($result);
  514. }
  515. return $result;
  516. }
  517. public static function merge(array $array1, array $array2, bool $unique = true): array
  518. {
  519. $isAssoc = static::isAssoc($array1 ?: $array2);
  520. if ($isAssoc) {
  521. foreach ($array2 as $key => $value) {
  522. if (is_array($value)) {
  523. $array1[$key] = static::merge($array1[$key] ?? [], $value, $unique);
  524. } else {
  525. $array1[$key] = $value;
  526. }
  527. }
  528. } else {
  529. foreach ($array2 as $value) {
  530. if ($unique && in_array($value, $array1, true)) {
  531. continue;
  532. }
  533. $array1[] = $value;
  534. }
  535. $array1 = array_values($array1);
  536. }
  537. return $array1;
  538. }
  539. /**
  540. * Remove one or more elements from an array.
  541. */
  542. public static function remove(array $array, mixed ...$value): array
  543. {
  544. $array = array_diff($array, $value);
  545. return array_values($array);
  546. }
  547. /**
  548. * Removes one or more elements from an array, keeping the original keys.
  549. */
  550. public static function removeKeepKey(array $array, mixed ...$value): array
  551. {
  552. foreach ($value as $item) {
  553. while (false !== ($index = array_search($item, $array))) {
  554. unset($array[$index]);
  555. }
  556. }
  557. return $array;
  558. }
  559. /**
  560. * Convert a flatten "dot" notation array into an expanded array.
  561. */
  562. public static function undot(array $array): array
  563. {
  564. $result = [];
  565. foreach ($array as $key => $value) {
  566. static::set($result, $key, $value);
  567. }
  568. return $result;
  569. }
  570. /**
  571. * Conditionally compile classes from an array into a CSS class list.
  572. */
  573. public static function toCssClasses(array $array): string
  574. {
  575. $classList = static::wrap($array);
  576. $classes = [];
  577. foreach ($classList as $class => $constraint) {
  578. if (is_numeric($class)) {
  579. $classes[] = $constraint;
  580. } elseif ($constraint) {
  581. $classes[] = $class;
  582. }
  583. }
  584. return implode(' ', $classes);
  585. }
  586. /**
  587. * Conditionally compile styles from an array into a style list.
  588. */
  589. public static function toCssStyles(array $array): string
  590. {
  591. $styleList = static::wrap($array);
  592. $styles = [];
  593. foreach ($styleList as $class => $constraint) {
  594. if (is_numeric($class)) {
  595. $styles[] = Str::finish($constraint, ';');
  596. } elseif ($constraint) {
  597. $styles[] = Str::finish($class, ';');
  598. }
  599. }
  600. return implode(' ', $styles);
  601. }
  602. /**
  603. * Join all items using a string. The final items can use a separate glue string.
  604. */
  605. public static function join(array $array, string $glue, string $finalGlue = ''): string
  606. {
  607. if ($finalGlue === '') {
  608. return implode($glue, $array);
  609. }
  610. if (count($array) === 0) {
  611. return '';
  612. }
  613. if (count($array) === 1) {
  614. return end($array);
  615. }
  616. $finalItem = array_pop($array);
  617. return implode($glue, $array) . $finalGlue . $finalItem;
  618. }
  619. /**
  620. * Key an associative array by a field or using a callback.
  621. */
  622. public static function keyBy(array $array, array|callable|string $keyBy): array
  623. {
  624. return Collection::make($array)->keyBy($keyBy)->all();
  625. }
  626. /**
  627. * Prepend the key names of an associative array.
  628. */
  629. public static function prependKeysWith(array $array, string $prependWith): array
  630. {
  631. return static::mapWithKeys($array, fn ($item, $key) => [$prependWith . $key => $item]);
  632. }
  633. /**
  634. * Select an array of values from an array.
  635. */
  636. public static function select(array $array, array|string $keys): array
  637. {
  638. $keys = static::wrap($keys);
  639. return static::map($array, static function ($item) use ($keys) {
  640. $result = [];
  641. foreach ($keys as $key) {
  642. if (Arr::accessible($item) && Arr::exists($item, $key)) {
  643. $result[$key] = $item[$key];
  644. } elseif (is_object($item) && isset($item->{$key})) {
  645. $result[$key] = $item->{$key};
  646. }
  647. }
  648. return $result;
  649. });
  650. }
  651. /**
  652. * Run a map over each nested chunk of items.
  653. *
  654. * @template TMapSpreadValue
  655. *
  656. * @param callable(mixed...): TMapSpreadValue $callback
  657. * @return array<TKey, TMapSpreadValue>
  658. */
  659. public static function mapSpread(array $array, callable $callback): array
  660. {
  661. return static::map($array, function ($chunk, $key) use ($callback) {
  662. $chunk[] = $key;
  663. return $callback(...$chunk);
  664. });
  665. }
  666. /**
  667. * Run a map over each of the items in the array.
  668. */
  669. public static function map(array $array, callable $callback): array
  670. {
  671. $keys = array_keys($array);
  672. try {
  673. $items = array_map($callback, $array, $keys);
  674. } catch (ArgumentCountError) {
  675. $items = array_map($callback, $array);
  676. }
  677. return array_combine($keys, $items);
  678. }
  679. /**
  680. * Sort the array in descending order using the given callback or "dot" notation.
  681. */
  682. public static function sortDesc(array $array, null|array|callable|string $callback = null): array
  683. {
  684. return Collection::make($array)->sortByDesc($callback)->all();
  685. }
  686. /**
  687. * Recursively sort an array by keys and values in descending order.
  688. */
  689. public static function sortRecursiveDesc(array $array, int $options = SORT_REGULAR): array
  690. {
  691. return static::sortRecursive($array, $options, true);
  692. }
  693. /**
  694. * Filter items where the value is not null.
  695. */
  696. public static function whereNotNull(array $array): array
  697. {
  698. return static::where($array, static fn ($value) => ! is_null($value));
  699. }
  700. /**
  701. * Explode the "value" and "key" arguments passed to "pluck".
  702. */
  703. protected static function explodePluckParameters(array|string $value, null|array|string $key): array
  704. {
  705. $value = is_string($value) ? explode('.', $value) : $value;
  706. $key = is_null($key) || is_array($key) ? $key : explode('.', $key);
  707. return [$value, $key];
  708. }
  709. }