Arrays.php 11 KB

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