Arr.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Supports;
  4. use ArrayAccess;
  5. use InvalidArgumentException;
  6. /**
  7. * Most of the methods in this file come from illuminate/support and hyperf/support,
  8. * thanks provide such a useful class.
  9. */
  10. class Arr
  11. {
  12. public static function accessible(mixed $value): bool
  13. {
  14. return is_array($value) || $value instanceof ArrayAccess;
  15. }
  16. public static function add(array $array, string $key, mixed $value): array
  17. {
  18. if (is_null(static::get($array, $key))) {
  19. static::set($array, $key, $value);
  20. }
  21. return $array;
  22. }
  23. public static function collapse(array $array): array
  24. {
  25. $results = [];
  26. foreach ($array as $values) {
  27. if ($values instanceof Collection) {
  28. $values = $values->all();
  29. } elseif (!is_array($values)) {
  30. continue;
  31. }
  32. $results[] = $values;
  33. }
  34. return array_merge([], ...$results);
  35. }
  36. public static function crossJoin(...$arrays): array
  37. {
  38. $results = [[]];
  39. foreach ($arrays as $index => $array) {
  40. $append = [];
  41. foreach ($results as $product) {
  42. foreach ($array as $item) {
  43. $product[$index] = $item;
  44. $append[] = $product;
  45. }
  46. }
  47. $results = $append;
  48. }
  49. return $results;
  50. }
  51. public static function divide(array $array): array
  52. {
  53. return [array_keys($array), array_values($array)];
  54. }
  55. public static function dot(array $array, string $prepend = ''): array
  56. {
  57. $results = [];
  58. foreach ($array as $key => $value) {
  59. if (is_array($value) && !empty($value)) {
  60. $results = array_merge($results, static::dot($value, $prepend.$key.'.'));
  61. } else {
  62. $results[$prepend.$key] = $value;
  63. }
  64. }
  65. return $results;
  66. }
  67. public static function except(array $array, array|string $keys): array
  68. {
  69. static::forget($array, $keys);
  70. return $array;
  71. }
  72. public static function exists(array|ArrayAccess $array, int|string $key): bool
  73. {
  74. if ($array instanceof ArrayAccess) {
  75. return $array->offsetExists($key);
  76. }
  77. return array_key_exists($key, $array);
  78. }
  79. public static function first(array $array, ?callable $callback = null, mixed $default = null): mixed
  80. {
  81. if (is_null($callback)) {
  82. if (empty($array)) {
  83. return $default;
  84. }
  85. foreach ($array as $item) {
  86. return $item;
  87. }
  88. }
  89. foreach ($array as $key => $value) {
  90. if (call_user_func($callback, $value, $key)) {
  91. return $value;
  92. }
  93. }
  94. return $default;
  95. }
  96. public static function last(array $array, ?callable $callback = null, mixed $default = null): mixed
  97. {
  98. if (is_null($callback)) {
  99. return empty($array) ? $default : end($array);
  100. }
  101. return static::first(array_reverse($array, true), $callback, $default);
  102. }
  103. public static function flatten(array $array, float|int $depth = INF): array
  104. {
  105. $result = [];
  106. foreach ($array as $item) {
  107. $item = $item instanceof Collection ? $item->all() : $item;
  108. if (!is_array($item)) {
  109. $result[] = $item;
  110. } elseif (1 === $depth) {
  111. $result = array_merge($result, array_values($item));
  112. } else {
  113. $result = array_merge($result, static::flatten($item, $depth - 1));
  114. }
  115. }
  116. return $result;
  117. }
  118. public static function forget(array &$array, array|string $keys): void
  119. {
  120. $original = &$array;
  121. $keys = (array) $keys;
  122. if (0 === count($keys)) {
  123. return;
  124. }
  125. foreach ($keys as $key) {
  126. // if the exact key exists in the top-level, remove it
  127. if (static::exists($array, $key)) {
  128. unset($array[$key]);
  129. continue;
  130. }
  131. $parts = explode('.', $key);
  132. // clean up before each pass
  133. $array = &$original;
  134. while (count($parts) > 1) {
  135. $part = array_shift($parts);
  136. if (isset($array[$part]) && is_array($array[$part])) {
  137. $array = &$array[$part];
  138. } else {
  139. continue 2;
  140. }
  141. }
  142. unset($array[array_shift($parts)]);
  143. }
  144. }
  145. public static function get(array|ArrayAccess $array, null|int|string $key = null, mixed $default = null): mixed
  146. {
  147. if (!static::accessible($array)) {
  148. return $default;
  149. }
  150. if (is_null($key)) {
  151. return $array;
  152. }
  153. if (static::exists($array, $key)) {
  154. return $array[$key];
  155. }
  156. if (!is_string($key) || !str_contains($key, '.')) {
  157. return $array[$key] ?? $default;
  158. }
  159. foreach (explode('.', $key) as $segment) {
  160. if (static::accessible($array) && static::exists($array, $segment)) {
  161. $array = $array[$segment];
  162. } else {
  163. return $default;
  164. }
  165. }
  166. return $array;
  167. }
  168. public static function has(array|ArrayAccess $array, null|array|string $keys): bool
  169. {
  170. if (is_null($keys)) {
  171. return false;
  172. }
  173. $keys = (array) $keys;
  174. if (!$array) {
  175. return false;
  176. }
  177. if ([] === $keys) {
  178. return false;
  179. }
  180. foreach ($keys as $key) {
  181. $subKeyArray = $array;
  182. if (static::exists($array, $key)) {
  183. continue;
  184. }
  185. foreach (explode('.', $key) as $segment) {
  186. if (static::accessible($subKeyArray) && static::exists($subKeyArray, $segment)) {
  187. $subKeyArray = $subKeyArray[$segment];
  188. } else {
  189. return false;
  190. }
  191. }
  192. }
  193. return true;
  194. }
  195. public static function isAssoc(array $array): bool
  196. {
  197. $keys = array_keys($array);
  198. return array_keys($keys) !== $keys;
  199. }
  200. public static function only(array $array, array|string $keys): array
  201. {
  202. return array_intersect_key($array, array_flip((array) $keys));
  203. }
  204. public static function pluck(array $array, array|string $value, null|array|string $key = null): array
  205. {
  206. $results = [];
  207. foreach ($array as $item) {
  208. $itemValue = data_get($item, $value);
  209. // If the key is "null", we will just append the value to the array and keep
  210. // looping, Otherwise we will key the array using the value of the key we
  211. // received from the developer. Then we'll return the final array form.
  212. if (is_null($key)) {
  213. $results[] = $itemValue;
  214. } else {
  215. $itemKey = data_get($item, $key);
  216. if (is_object($itemKey) && method_exists($itemKey, '__toString')) {
  217. $itemKey = (string) $itemKey;
  218. }
  219. $results[$itemKey] = $itemValue;
  220. }
  221. }
  222. return $results;
  223. }
  224. public static function prepend(array $array, mixed $value, mixed $key = null): array
  225. {
  226. if (is_null($key)) {
  227. array_unshift($array, $value);
  228. } else {
  229. $array = [$key => $value] + $array;
  230. }
  231. return $array;
  232. }
  233. public static function pull(array &$array, string $key, mixed $default = null): mixed
  234. {
  235. $value = static::get($array, $key, $default);
  236. static::forget($array, $key);
  237. return $value;
  238. }
  239. /**
  240. * @throws InvalidArgumentException
  241. */
  242. public static function random(array $array, int $number = 1): array
  243. {
  244. $count = count($array);
  245. if ($number > $count) {
  246. throw new InvalidArgumentException("You requested {$number} items, but there are only {$count} items available.");
  247. }
  248. if (0 === $number) {
  249. return [];
  250. }
  251. $keys = array_rand($array, $number);
  252. $results = [];
  253. foreach ((array) $keys as $key) {
  254. $results[] = $array[$key];
  255. }
  256. return $results;
  257. }
  258. /**
  259. * Set an array item to a given value using "dot" notation.
  260. * If no key is given to the method, the entire array will be replaced.
  261. */
  262. public static function set(array &$array, null|int|string $key, mixed $value): array
  263. {
  264. if (is_null($key)) {
  265. return $array = $value;
  266. }
  267. if (!is_string($key)) {
  268. $array[$key] = $value;
  269. return $array;
  270. }
  271. $keys = explode('.', $key);
  272. while (count($keys) > 1) {
  273. $key = array_shift($keys);
  274. // If the key doesn't exist at this depth, we will just create an empty array
  275. // to hold the next value, allowing us to create the arrays to hold final
  276. // values at the correct depth. Then we'll keep digging into the array.
  277. if (!isset($array[$key]) || !is_array($array[$key])) {
  278. $array[$key] = [];
  279. }
  280. $array = &$array[$key];
  281. }
  282. $array[array_shift($keys)] = $value;
  283. return $array;
  284. }
  285. public static function shuffle(array $array, ?int $seed = null): array
  286. {
  287. if (is_null($seed)) {
  288. shuffle($array);
  289. } else {
  290. srand($seed);
  291. usort($array, function () {
  292. return rand(-1, 1);
  293. });
  294. }
  295. return $array;
  296. }
  297. public static function sort(array $array, callable $callback): array
  298. {
  299. $results = [];
  300. foreach ($array as $key => $value) {
  301. $results[$key] = $callback($value);
  302. }
  303. return $results;
  304. }
  305. public static function sortRecursive(array $array): array
  306. {
  307. foreach ($array as &$value) {
  308. if (is_array($value)) {
  309. $value = static::sortRecursive($value);
  310. }
  311. }
  312. if (static::isAssoc($array)) {
  313. ksort($array);
  314. } else {
  315. sort($array);
  316. }
  317. return $array;
  318. }
  319. public static function query(array $array, int $encodingType = PHP_QUERY_RFC1738): string
  320. {
  321. return http_build_query($array, '', '&', $encodingType);
  322. }
  323. public static function toString(array $array, string $separator = '&'): string
  324. {
  325. $result = '';
  326. foreach ($array as $key => $value) {
  327. $result .= $key.'='.$value.$separator;
  328. }
  329. return substr($result, 0, 0 - Str::length($separator));
  330. }
  331. public static function where(array $array, callable $callback): array
  332. {
  333. return array_filter($array, $callback, ARRAY_FILTER_USE_BOTH);
  334. }
  335. public static function wrap(mixed $value): array
  336. {
  337. if (is_null($value)) {
  338. return [];
  339. }
  340. return !is_array($value) ? [$value] : $value;
  341. }
  342. public static function wrapJson(string $json): ?array
  343. {
  344. $result = json_decode($json, true);
  345. return is_array($result) ? $result : null;
  346. }
  347. public static function wrapXml(string $xml): array
  348. {
  349. if (empty($xml)) {
  350. return [];
  351. }
  352. $data = json_decode(json_encode(
  353. simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA),
  354. JSON_UNESCAPED_UNICODE
  355. ), true);
  356. if (JSON_ERROR_NONE === json_last_error()) {
  357. return $data;
  358. }
  359. return [];
  360. }
  361. /**
  362. * @param bool $raw 是否原始解析,有些情况下,原始解析会更好
  363. * @param bool $spaceToPlus 是否将空格转换为加号
  364. */
  365. public static function wrapQuery(string $query, bool $raw = false, bool $spaceToPlus = false): array
  366. {
  367. if (!$raw) {
  368. parse_str($query, $data);
  369. return $spaceToPlus ? self::querySpaceToPlus($data) : $data;
  370. }
  371. if (empty($query) || !Str::contains($query, '=')) {
  372. return [];
  373. }
  374. $result = [];
  375. foreach (explode('&', $query) as $item) {
  376. $pos = strpos($item, '=');
  377. $result[substr($item, 0, $pos)] = substr($item, $pos + 1);
  378. }
  379. return $result;
  380. }
  381. public static function querySpaceToPlus(array $data): array
  382. {
  383. foreach ($data as $key => $item) {
  384. $data[$key] = is_array($item) ? self::querySpaceToPlus($item) : str_replace(' ', '+', $item);
  385. }
  386. return $data;
  387. }
  388. public static function unique(array $array): array
  389. {
  390. $result = [];
  391. foreach ($array as $key => $item) {
  392. if (is_array($item)) {
  393. $result[$key] = self::unique($item);
  394. } else {
  395. $result[$key] = $item;
  396. }
  397. }
  398. if (!self::isAssoc($result)) {
  399. return array_unique($result);
  400. }
  401. return $result;
  402. }
  403. public static function merge(array $array1, array $array2, bool $unique = true): array
  404. {
  405. $isAssoc = static::isAssoc($array1 ?: $array2);
  406. if ($isAssoc) {
  407. foreach ($array2 as $key => $value) {
  408. if (is_array($value)) {
  409. $array1[$key] = static::merge($array1[$key] ?? [], $value, $unique);
  410. } else {
  411. $array1[$key] = $value;
  412. }
  413. }
  414. } else {
  415. foreach ($array2 as $value) {
  416. if ($unique && in_array($value, $array1, true)) {
  417. continue;
  418. }
  419. $array1[] = $value;
  420. }
  421. $array1 = array_values($array1);
  422. }
  423. return $array1;
  424. }
  425. public static function encoding(array $array, string $to_encoding, string $from_encoding = 'gb2312'): array
  426. {
  427. $encoded = [];
  428. foreach ($array as $key => $value) {
  429. $encoded[$key] = is_array($value) ? self::encoding($value, $to_encoding, $from_encoding) :
  430. mb_convert_encoding($value, $to_encoding, $from_encoding);
  431. }
  432. return $encoded;
  433. }
  434. public static function camelCaseKey(mixed $data): mixed
  435. {
  436. if (!self::accessible($data)
  437. && !(is_object($data) && method_exists($data, 'toArray'))) {
  438. return $data;
  439. }
  440. $result = [];
  441. foreach ((is_object($data) ? $data->toArray() : $data) as $key => $value) {
  442. $result[is_string($key) ? Str::camel($key) : $key] = self::camelCaseKey($value);
  443. }
  444. return $result;
  445. }
  446. public static function snakeCaseKey(mixed $data): mixed
  447. {
  448. if (!self::accessible($data)
  449. && !(is_object($data) && method_exists($data, 'toArray'))) {
  450. return $data;
  451. }
  452. $result = [];
  453. foreach ((is_object($data) ? $data->toArray() : $data) as $key => $value) {
  454. $result[is_string($key) ? Str::snake($key) : $key] = self::snakeCaseKey($value);
  455. }
  456. return $result;
  457. }
  458. }