Arrays.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. /**
  3. * This file is part of the Nette Framework (https://nette.org)
  4. * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  5. */
  6. declare(strict_types=1);
  7. namespace Nette\Utils;
  8. use JetBrains\PhpStorm\Language;
  9. use Nette;
  10. use function is_array, is_int, is_object, count;
  11. /**
  12. * Array tools library.
  13. */
  14. class Arrays
  15. {
  16. use Nette\StaticClass;
  17. /**
  18. * Returns item from array. If it does not exist, it throws an exception, unless a default value is set.
  19. * @template T
  20. * @param array<T> $array
  21. * @param array-key|array-key[] $key
  22. * @param ?T $default
  23. * @return ?T
  24. * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided
  25. */
  26. public static function get(array $array, $key, $default = null)
  27. {
  28. foreach (is_array($key) ? $key : [$key] as $k) {
  29. if (is_array($array) && array_key_exists($k, $array)) {
  30. $array = $array[$k];
  31. } else {
  32. if (func_num_args() < 3) {
  33. throw new Nette\InvalidArgumentException("Missing item '$k'.");
  34. }
  35. return $default;
  36. }
  37. }
  38. return $array;
  39. }
  40. /**
  41. * Returns reference to array item. If the index does not exist, new one is created with value null.
  42. * @template T
  43. * @param array<T> $array
  44. * @param array-key|array-key[] $key
  45. * @return ?T
  46. * @throws Nette\InvalidArgumentException if traversed item is not an array
  47. */
  48. public static function &getRef(array &$array, $key)
  49. {
  50. foreach (is_array($key) ? $key : [$key] as $k) {
  51. if (is_array($array) || $array === null) {
  52. $array = &$array[$k];
  53. } else {
  54. throw new Nette\InvalidArgumentException('Traversed item is not an array.');
  55. }
  56. }
  57. return $array;
  58. }
  59. /**
  60. * Recursively merges two fields. It is useful, for example, for merging tree structures. It behaves as
  61. * the + operator for array, ie. it adds a key/value pair from the second array to the first one and retains
  62. * the value from the first array in the case of a key collision.
  63. * @template T1
  64. * @template T2
  65. * @param array<T1> $array1
  66. * @param array<T2> $array2
  67. * @return array<T1|T2>
  68. */
  69. public static function mergeTree(array $array1, array $array2): array
  70. {
  71. $res = $array1 + $array2;
  72. foreach (array_intersect_key($array1, $array2) as $k => $v) {
  73. if (is_array($v) && is_array($array2[$k])) {
  74. $res[$k] = self::mergeTree($v, $array2[$k]);
  75. }
  76. }
  77. return $res;
  78. }
  79. /**
  80. * Returns zero-indexed position of given array key. Returns null if key is not found.
  81. * @param array-key $key
  82. * @return int|null offset if it is found, null otherwise
  83. */
  84. public static function getKeyOffset(array $array, $key): ?int
  85. {
  86. return Helpers::falseToNull(array_search(self::toKey($key), array_keys($array), true));
  87. }
  88. /**
  89. * @deprecated use getKeyOffset()
  90. */
  91. public static function searchKey(array $array, $key): ?int
  92. {
  93. return self::getKeyOffset($array, $key);
  94. }
  95. /**
  96. * Tests an array for the presence of value.
  97. * @param mixed $value
  98. */
  99. public static function contains(array $array, $value): bool
  100. {
  101. return in_array($value, $array, true);
  102. }
  103. /**
  104. * Returns the first item from the array or null if array is empty.
  105. * @template T
  106. * @param array<T> $array
  107. * @return ?T
  108. */
  109. public static function first(array $array)
  110. {
  111. return count($array) ? reset($array) : null;
  112. }
  113. /**
  114. * Returns the last item from the array or null if array is empty.
  115. * @template T
  116. * @param array<T> $array
  117. * @return ?T
  118. */
  119. public static function last(array $array)
  120. {
  121. return count($array) ? end($array) : null;
  122. }
  123. /**
  124. * Inserts the contents of the $inserted array into the $array immediately after the $key.
  125. * If $key is null (or does not exist), it is inserted at the beginning.
  126. * @param array-key|null $key
  127. */
  128. public static function insertBefore(array &$array, $key, array $inserted): void
  129. {
  130. $offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key);
  131. $array = array_slice($array, 0, $offset, true)
  132. + $inserted
  133. + array_slice($array, $offset, count($array), true);
  134. }
  135. /**
  136. * Inserts the contents of the $inserted array into the $array before the $key.
  137. * If $key is null (or does not exist), it is inserted at the end.
  138. * @param array-key|null $key
  139. */
  140. public static function insertAfter(array &$array, $key, array $inserted): void
  141. {
  142. if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) {
  143. $offset = count($array) - 1;
  144. }
  145. $array = array_slice($array, 0, $offset + 1, true)
  146. + $inserted
  147. + array_slice($array, $offset + 1, count($array), true);
  148. }
  149. /**
  150. * Renames key in array.
  151. * @param array-key $oldKey
  152. * @param array-key $newKey
  153. */
  154. public static function renameKey(array &$array, $oldKey, $newKey): bool
  155. {
  156. $offset = self::getKeyOffset($array, $oldKey);
  157. if ($offset === null) {
  158. return false;
  159. }
  160. $val = &$array[$oldKey];
  161. $keys = array_keys($array);
  162. $keys[$offset] = $newKey;
  163. $array = array_combine($keys, $array);
  164. $array[$newKey] = &$val;
  165. return true;
  166. }
  167. /**
  168. * Returns only those array items, which matches a regular expression $pattern.
  169. * @param string[] $array
  170. * @return string[]
  171. */
  172. public static function grep(
  173. array $array,
  174. #[Language('RegExp')]
  175. string $pattern,
  176. int $flags = 0
  177. ): array
  178. {
  179. return Strings::pcre('preg_grep', [$pattern, $array, $flags]);
  180. }
  181. /**
  182. * Transforms multidimensional array to flat array.
  183. */
  184. public static function flatten(array $array, bool $preserveKeys = false): array
  185. {
  186. $res = [];
  187. $cb = $preserveKeys
  188. ? function ($v, $k) use (&$res): void { $res[$k] = $v; }
  189. : function ($v) use (&$res): void { $res[] = $v; };
  190. array_walk_recursive($array, $cb);
  191. return $res;
  192. }
  193. /**
  194. * Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list.
  195. * @param mixed $value
  196. */
  197. public static function isList($value): bool
  198. {
  199. return is_array($value) && (PHP_VERSION_ID < 80100
  200. ? !$value || array_keys($value) === range(0, count($value) - 1)
  201. : array_is_list($value)
  202. );
  203. }
  204. /**
  205. * Reformats table to associative tree. Path looks like 'field|field[]field->field=field'.
  206. * @param string|string[] $path
  207. * @return array|\stdClass
  208. */
  209. public static function associate(array $array, $path)
  210. {
  211. $parts = is_array($path)
  212. ? $path
  213. : preg_split('#(\[\]|->|=|\|)#', $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  214. if (!$parts || $parts === ['->'] || $parts[0] === '=' || $parts[0] === '|') {
  215. throw new Nette\InvalidArgumentException("Invalid path '$path'.");
  216. }
  217. $res = $parts[0] === '->' ? new \stdClass : [];
  218. foreach ($array as $rowOrig) {
  219. $row = (array) $rowOrig;
  220. $x = &$res;
  221. for ($i = 0; $i < count($parts); $i++) {
  222. $part = $parts[$i];
  223. if ($part === '[]') {
  224. $x = &$x[];
  225. } elseif ($part === '=') {
  226. if (isset($parts[++$i])) {
  227. $x = $row[$parts[$i]];
  228. $row = null;
  229. }
  230. } elseif ($part === '->') {
  231. if (isset($parts[++$i])) {
  232. if ($x === null) {
  233. $x = new \stdClass;
  234. }
  235. $x = &$x->{$row[$parts[$i]]};
  236. } else {
  237. $row = is_object($rowOrig) ? $rowOrig : (object) $row;
  238. }
  239. } elseif ($part !== '|') {
  240. $x = &$x[(string) $row[$part]];
  241. }
  242. }
  243. if ($x === null) {
  244. $x = $row;
  245. }
  246. }
  247. return $res;
  248. }
  249. /**
  250. * Normalizes array to associative array. Replace numeric keys with their values, the new value will be $filling.
  251. * @param mixed $filling
  252. */
  253. public static function normalize(array $array, $filling = null): array
  254. {
  255. $res = [];
  256. foreach ($array as $k => $v) {
  257. $res[is_int($k) ? $v : $k] = is_int($k) ? $filling : $v;
  258. }
  259. return $res;
  260. }
  261. /**
  262. * Returns and removes the value of an item from an array. If it does not exist, it throws an exception,
  263. * or returns $default, if provided.
  264. * @template T
  265. * @param array<T> $array
  266. * @param array-key $key
  267. * @param ?T $default
  268. * @return ?T
  269. * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided
  270. */
  271. public static function pick(array &$array, $key, $default = null)
  272. {
  273. if (array_key_exists($key, $array)) {
  274. $value = $array[$key];
  275. unset($array[$key]);
  276. return $value;
  277. } elseif (func_num_args() < 3) {
  278. throw new Nette\InvalidArgumentException("Missing item '$key'.");
  279. } else {
  280. return $default;
  281. }
  282. }
  283. /**
  284. * Tests whether at least one element in the array passes the test implemented by the
  285. * provided callback with signature `function ($value, $key, array $array): bool`.
  286. */
  287. public static function some(iterable $array, callable $callback): bool
  288. {
  289. foreach ($array as $k => $v) {
  290. if ($callback($v, $k, $array)) {
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. /**
  297. * Tests whether all elements in the array pass the test implemented by the provided function,
  298. * which has the signature `function ($value, $key, array $array): bool`.
  299. */
  300. public static function every(iterable $array, callable $callback): bool
  301. {
  302. foreach ($array as $k => $v) {
  303. if (!$callback($v, $k, $array)) {
  304. return false;
  305. }
  306. }
  307. return true;
  308. }
  309. /**
  310. * Calls $callback on all elements in the array and returns the array of return values.
  311. * The callback has the signature `function ($value, $key, array $array): bool`.
  312. */
  313. public static function map(iterable $array, callable $callback): array
  314. {
  315. $res = [];
  316. foreach ($array as $k => $v) {
  317. $res[$k] = $callback($v, $k, $array);
  318. }
  319. return $res;
  320. }
  321. /**
  322. * Invokes all callbacks and returns array of results.
  323. * @param callable[] $callbacks
  324. */
  325. public static function invoke(iterable $callbacks, ...$args): array
  326. {
  327. $res = [];
  328. foreach ($callbacks as $k => $cb) {
  329. $res[$k] = $cb(...$args);
  330. }
  331. return $res;
  332. }
  333. /**
  334. * Invokes method on every object in an array and returns array of results.
  335. * @param object[] $objects
  336. */
  337. public static function invokeMethod(iterable $objects, string $method, ...$args): array
  338. {
  339. $res = [];
  340. foreach ($objects as $k => $obj) {
  341. $res[$k] = $obj->$method(...$args);
  342. }
  343. return $res;
  344. }
  345. /**
  346. * Copies the elements of the $array array to the $object object and then returns it.
  347. * @template T of object
  348. * @param T $object
  349. * @return T
  350. */
  351. public static function toObject(iterable $array, $object)
  352. {
  353. foreach ($array as $k => $v) {
  354. $object->$k = $v;
  355. }
  356. return $object;
  357. }
  358. /**
  359. * Converts value to array key.
  360. * @param mixed $value
  361. * @return array-key
  362. */
  363. public static function toKey($value)
  364. {
  365. return key([$value => null]);
  366. }
  367. /**
  368. * Returns copy of the $array where every item is converted to string
  369. * and prefixed by $prefix and suffixed by $suffix.
  370. * @param string[] $array
  371. * @return string[]
  372. */
  373. public static function wrap(array $array, string $prefix = '', string $suffix = ''): array
  374. {
  375. $res = [];
  376. foreach ($array as $k => $v) {
  377. $res[$k] = $prefix . $v . $suffix;
  378. }
  379. return $res;
  380. }
  381. }