Hash.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @since 2.2.0
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Utility;
  15. use InvalidArgumentException;
  16. use RuntimeException;
  17. /**
  18. * Library of array functions for manipulating and extracting data
  19. * from arrays or 'sets' of data.
  20. *
  21. * `Hash` provides an improved interface, more consistent and
  22. * predictable set of features over `Set`. While it lacks the spotty
  23. * support for pseudo Xpath, its more fully featured dot notation provides
  24. * similar features in a more consistent implementation.
  25. *
  26. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html
  27. */
  28. class Hash
  29. {
  30. /**
  31. * Get a single value specified by $path out of $data.
  32. * Does not support the full dot notation feature set,
  33. * but is faster for simple read operations.
  34. *
  35. * @param array $data Array of data to operate on.
  36. * @param string|array $path The path being searched for. Either a dot
  37. * separated string, or an array of path segments.
  38. * @param mixed $default The return value when the path does not exist
  39. * @throws \InvalidArgumentException
  40. * @return mixed The value fetched from the array, or null.
  41. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::get
  42. */
  43. public static function get(array $data, $path, $default = null)
  44. {
  45. if (empty($data) || $path === null || $path === '') {
  46. return $default;
  47. }
  48. if (is_string($path) || is_numeric($path)) {
  49. $parts = explode('.', $path);
  50. } else {
  51. if (!is_array($path)) {
  52. throw new InvalidArgumentException(sprintf(
  53. 'Invalid Parameter %s, should be dot separated path or array.',
  54. $path
  55. ));
  56. }
  57. $parts = $path;
  58. }
  59. switch (count($parts)) {
  60. case 1:
  61. return isset($data[$parts[0]]) ? $data[$parts[0]] : $default;
  62. case 2:
  63. return isset($data[$parts[0]][$parts[1]]) ? $data[$parts[0]][$parts[1]] : $default;
  64. case 3:
  65. return isset($data[$parts[0]][$parts[1]][$parts[2]]) ? $data[$parts[0]][$parts[1]][$parts[2]] : $default;
  66. default:
  67. foreach ($parts as $key) {
  68. if (is_array($data) && isset($data[$key])) {
  69. $data = $data[$key];
  70. } else {
  71. return $default;
  72. }
  73. }
  74. }
  75. return $data;
  76. }
  77. /**
  78. * Gets the values from an array matching the $path expression.
  79. * The path expression is a dot separated expression, that can contain a set
  80. * of patterns and expressions:
  81. *
  82. * - `{n}` Matches any numeric key, or integer.
  83. * - `{s}` Matches any string key.
  84. * - `{*}` Matches any value.
  85. * - `Foo` Matches any key with the exact same value.
  86. *
  87. * There are a number of attribute operators:
  88. *
  89. * - `=`, `!=` Equality.
  90. * - `>`, `<`, `>=`, `<=` Value comparison.
  91. * - `=/.../` Regular expression pattern match.
  92. *
  93. * Given a set of User array data, from a `$User->find('all')` call:
  94. *
  95. * - `1.User.name` Get the name of the user at index 1.
  96. * - `{n}.User.name` Get the name of every user in the set of users.
  97. * - `{n}.User[id]` Get the name of every user with an id key.
  98. * - `{n}.User[id>=2]` Get the name of every user with an id key greater than or equal to 2.
  99. * - `{n}.User[username=/^paul/]` Get User elements with username matching `^paul`.
  100. *
  101. * @param array $data The data to extract from.
  102. * @param string $path The path to extract.
  103. * @return array An array of the extracted values. Returns an empty array
  104. * if there are no matches.
  105. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::extract
  106. */
  107. public static function extract(array $data, $path)
  108. {
  109. if (empty($path)) {
  110. return $data;
  111. }
  112. // Simple paths.
  113. if (!preg_match('/[{\[]/', $path)) {
  114. return (array)static::get($data, $path);
  115. }
  116. if (strpos($path, '[') === false) {
  117. if (function_exists('array_column') && preg_match('|^\{n\}\.(\w+)$|', $path, $matches)) {
  118. return array_column($data, $matches[1]);
  119. }
  120. $tokens = explode('.', $path);
  121. } else {
  122. $tokens = Text::tokenize($path, '.', '[', ']');
  123. }
  124. $_key = '__set_item__';
  125. $context = [$_key => [$data]];
  126. foreach ($tokens as $token) {
  127. $next = [];
  128. list($token, $conditions) = self::_splitConditions($token);
  129. foreach ($context[$_key] as $item) {
  130. foreach ((array)$item as $k => $v) {
  131. if (static::_matchToken($k, $token)) {
  132. $next[] = $v;
  133. }
  134. }
  135. }
  136. // Filter for attributes.
  137. if ($conditions) {
  138. $filter = [];
  139. foreach ($next as $item) {
  140. if (is_array($item) && static::_matches($item, $conditions)) {
  141. $filter[] = $item;
  142. }
  143. }
  144. $next = $filter;
  145. }
  146. $context = [$_key => $next];
  147. }
  148. return $context[$_key];
  149. }
  150. /**
  151. * Split token conditions
  152. *
  153. * @param string $token the token being splitted.
  154. * @return array [token, conditions] with token splitted
  155. */
  156. protected static function _splitConditions($token)
  157. {
  158. $conditions = false;
  159. $position = strpos($token, '[');
  160. if ($position !== false) {
  161. $conditions = substr($token, $position);
  162. $token = substr($token, 0, $position);
  163. }
  164. return [$token, $conditions];
  165. }
  166. /**
  167. * Check a key against a token.
  168. *
  169. * @param string $key The key in the array being searched.
  170. * @param string $token The token being matched.
  171. * @return bool
  172. */
  173. protected static function _matchToken($key, $token)
  174. {
  175. switch ($token) {
  176. case '{n}':
  177. return is_numeric($key);
  178. case '{s}':
  179. return is_string($key);
  180. case '{*}':
  181. return true;
  182. default:
  183. return is_numeric($token) ? ($key == $token) : $key === $token;
  184. }
  185. }
  186. /**
  187. * Checks whether or not $data matches the attribute patterns
  188. *
  189. * @param array $data Array of data to match.
  190. * @param string $selector The patterns to match.
  191. * @return bool Fitness of expression.
  192. */
  193. protected static function _matches(array $data, $selector)
  194. {
  195. preg_match_all(
  196. '/(\[ (?P<attr>[^=><!]+?) (\s* (?P<op>[><!]?[=]|[><]) \s* (?P<val>(?:\/.*?\/ | [^\]]+)) )? \])/x',
  197. $selector,
  198. $conditions,
  199. PREG_SET_ORDER
  200. );
  201. foreach ($conditions as $cond) {
  202. $attr = $cond['attr'];
  203. $op = isset($cond['op']) ? $cond['op'] : null;
  204. $val = isset($cond['val']) ? $cond['val'] : null;
  205. // Presence test.
  206. if (empty($op) && empty($val) && !isset($data[$attr])) {
  207. return false;
  208. }
  209. // Empty attribute = fail.
  210. if (!(isset($data[$attr]) || array_key_exists($attr, $data))) {
  211. return false;
  212. }
  213. $prop = null;
  214. if (isset($data[$attr])) {
  215. $prop = $data[$attr];
  216. }
  217. $isBool = is_bool($prop);
  218. if ($isBool && is_numeric($val)) {
  219. $prop = $prop ? '1' : '0';
  220. } elseif ($isBool) {
  221. $prop = $prop ? 'true' : 'false';
  222. }
  223. // Pattern matches and other operators.
  224. if ($op === '=' && $val && $val[0] === '/') {
  225. if (!preg_match($val, $prop)) {
  226. return false;
  227. }
  228. } elseif (($op === '=' && $prop != $val) ||
  229. ($op === '!=' && $prop == $val) ||
  230. ($op === '>' && $prop <= $val) ||
  231. ($op === '<' && $prop >= $val) ||
  232. ($op === '>=' && $prop < $val) ||
  233. ($op === '<=' && $prop > $val)
  234. ) {
  235. return false;
  236. }
  237. }
  238. return true;
  239. }
  240. /**
  241. * Insert $values into an array with the given $path. You can use
  242. * `{n}` and `{s}` elements to insert $data multiple times.
  243. *
  244. * @param array $data The data to insert into.
  245. * @param string $path The path to insert at.
  246. * @param array|null $values The values to insert.
  247. * @return array The data with $values inserted.
  248. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::insert
  249. */
  250. public static function insert(array $data, $path, $values = null)
  251. {
  252. $noTokens = strpos($path, '[') === false;
  253. if ($noTokens && strpos($path, '.') === false) {
  254. $data[$path] = $values;
  255. return $data;
  256. }
  257. if ($noTokens) {
  258. $tokens = explode('.', $path);
  259. } else {
  260. $tokens = Text::tokenize($path, '.', '[', ']');
  261. }
  262. if ($noTokens && strpos($path, '{') === false) {
  263. return static::_simpleOp('insert', $data, $tokens, $values);
  264. }
  265. $token = array_shift($tokens);
  266. $nextPath = implode('.', $tokens);
  267. list($token, $conditions) = static::_splitConditions($token);
  268. foreach ($data as $k => $v) {
  269. if (static::_matchToken($k, $token)) {
  270. if (!$conditions || static::_matches($v, $conditions)) {
  271. $data[$k] = $nextPath
  272. ? static::insert($v, $nextPath, $values)
  273. : array_merge($v, (array) $values);
  274. }
  275. }
  276. }
  277. return $data;
  278. }
  279. /**
  280. * Perform a simple insert/remove operation.
  281. *
  282. * @param string $op The operation to do.
  283. * @param array $data The data to operate on.
  284. * @param array $path The path to work on.
  285. * @param mixed $values The values to insert when doing inserts.
  286. * @return array data.
  287. */
  288. protected static function _simpleOp($op, $data, $path, $values = null)
  289. {
  290. $_list =& $data;
  291. $count = count($path);
  292. $last = $count - 1;
  293. foreach ($path as $i => $key) {
  294. if ((is_numeric($key) && (int)($key) > 0 || $key === '0') &&
  295. strpos($key, '0') !== 0
  296. ) {
  297. $key = (int)$key;
  298. }
  299. if ($op === 'insert') {
  300. if ($i === $last) {
  301. $_list[$key] = $values;
  302. return $data;
  303. }
  304. if (!isset($_list[$key])) {
  305. $_list[$key] = [];
  306. }
  307. $_list =& $_list[$key];
  308. if (!is_array($_list)) {
  309. $_list = [];
  310. }
  311. } elseif ($op === 'remove') {
  312. if ($i === $last) {
  313. unset($_list[$key]);
  314. return $data;
  315. }
  316. if (!isset($_list[$key])) {
  317. return $data;
  318. }
  319. $_list =& $_list[$key];
  320. }
  321. }
  322. }
  323. /**
  324. * Remove data matching $path from the $data array.
  325. * You can use `{n}` and `{s}` to remove multiple elements
  326. * from $data.
  327. *
  328. * @param array $data The data to operate on
  329. * @param string $path A path expression to use to remove.
  330. * @return array The modified array.
  331. * @link http://book.cakephp.org/3.0/en/core--libraries/hash.html#Hash::remove
  332. */
  333. public static function remove(array $data, $path)
  334. {
  335. $noTokens = strpos($path, '[') === false;
  336. $noExpansion = strpos($path, '{') === false;
  337. if ($noExpansion && $noTokens && strpos($path, '.') === false) {
  338. unset($data[$path]);
  339. return $data;
  340. }
  341. $tokens = $noTokens ? explode('.', $path) : Text::tokenize($path, '.', '[', ']');
  342. if ($noExpansion && $noTokens) {
  343. return static::_simpleOp('remove', $data, $tokens);
  344. }
  345. $token = array_shift($tokens);
  346. $nextPath = implode('.', $tokens);
  347. list($token, $conditions) = self::_splitConditions($token);
  348. foreach ($data as $k => $v) {
  349. $match = static::_matchToken($k, $token);
  350. if ($match && is_array($v)) {
  351. if ($conditions && static::_matches($v, $conditions)) {
  352. unset($data[$k]);
  353. continue;
  354. }
  355. $data[$k] = static::remove($v, $nextPath);
  356. if (empty($data[$k])) {
  357. unset($data[$k]);
  358. }
  359. } elseif ($match && empty($nextPath)) {
  360. unset($data[$k]);
  361. }
  362. }
  363. return $data;
  364. }
  365. /**
  366. * Creates an associative array using `$keyPath` as the path to build its keys, and optionally
  367. * `$valuePath` as path to get the values. If `$valuePath` is not specified, all values will be initialized
  368. * to null (useful for Hash::merge). You can optionally group the values by what is obtained when
  369. * following the path specified in `$groupPath`.
  370. *
  371. * @param array $data Array from where to extract keys and values
  372. * @param string $keyPath A dot-separated string.
  373. * @param string|null $valuePath A dot-separated string.
  374. * @param string|null $groupPath A dot-separated string.
  375. * @return array Combined array
  376. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::combine
  377. * @throws \RuntimeException When keys and values count is unequal.
  378. */
  379. public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null)
  380. {
  381. if (empty($data)) {
  382. return [];
  383. }
  384. if (is_array($keyPath)) {
  385. $format = array_shift($keyPath);
  386. $keys = static::format($data, $keyPath, $format);
  387. } else {
  388. $keys = static::extract($data, $keyPath);
  389. }
  390. if (empty($keys)) {
  391. return [];
  392. }
  393. if (!empty($valuePath) && is_array($valuePath)) {
  394. $format = array_shift($valuePath);
  395. $vals = static::format($data, $valuePath, $format);
  396. } elseif (!empty($valuePath)) {
  397. $vals = static::extract($data, $valuePath);
  398. }
  399. if (empty($vals)) {
  400. $vals = array_fill(0, count($keys), null);
  401. }
  402. if (count($keys) !== count($vals)) {
  403. throw new RuntimeException(
  404. 'Hash::combine() needs an equal number of keys + values.'
  405. );
  406. }
  407. if ($groupPath !== null) {
  408. $group = static::extract($data, $groupPath);
  409. if (!empty($group)) {
  410. $c = count($keys);
  411. for ($i = 0; $i < $c; $i++) {
  412. if (!isset($group[$i])) {
  413. $group[$i] = 0;
  414. }
  415. if (!isset($out[$group[$i]])) {
  416. $out[$group[$i]] = [];
  417. }
  418. $out[$group[$i]][$keys[$i]] = $vals[$i];
  419. }
  420. return $out;
  421. }
  422. }
  423. if (empty($vals)) {
  424. return [];
  425. }
  426. return array_combine($keys, $vals);
  427. }
  428. /**
  429. * Returns a formatted series of values extracted from `$data`, using
  430. * `$format` as the format and `$paths` as the values to extract.
  431. *
  432. * Usage:
  433. *
  434. * ```
  435. * $result = Hash::format($users, ['{n}.User.id', '{n}.User.name'], '%s : %s');
  436. * ```
  437. *
  438. * The `$format` string can use any format options that `vsprintf()` and `sprintf()` do.
  439. *
  440. * @param array $data Source array from which to extract the data
  441. * @param array $paths An array containing one or more Hash::extract()-style key paths
  442. * @param string $format Format string into which values will be inserted, see sprintf()
  443. * @return void|array An array of strings extracted from `$path` and formatted with `$format`
  444. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::format
  445. * @see sprintf()
  446. * @see Hash::extract()
  447. */
  448. public static function format(array $data, array $paths, $format)
  449. {
  450. $extracted = [];
  451. $count = count($paths);
  452. if (!$count) {
  453. return;
  454. }
  455. for ($i = 0; $i < $count; $i++) {
  456. $extracted[] = static::extract($data, $paths[$i]);
  457. }
  458. $out = [];
  459. $data = $extracted;
  460. $count = count($data[0]);
  461. $countTwo = count($data);
  462. for ($j = 0; $j < $count; $j++) {
  463. $args = [];
  464. for ($i = 0; $i < $countTwo; $i++) {
  465. if (array_key_exists($j, $data[$i])) {
  466. $args[] = $data[$i][$j];
  467. }
  468. }
  469. $out[] = vsprintf($format, $args);
  470. }
  471. return $out;
  472. }
  473. /**
  474. * Determines if one array contains the exact keys and values of another.
  475. *
  476. * @param array $data The data to search through.
  477. * @param array $needle The values to file in $data
  478. * @return bool true if $data contains $needle, false otherwise
  479. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::contains
  480. */
  481. public static function contains(array $data, array $needle)
  482. {
  483. if (empty($data) || empty($needle)) {
  484. return false;
  485. }
  486. $stack = [];
  487. while (!empty($needle)) {
  488. $key = key($needle);
  489. $val = $needle[$key];
  490. unset($needle[$key]);
  491. if (array_key_exists($key, $data) && is_array($val)) {
  492. $next = $data[$key];
  493. unset($data[$key]);
  494. if (!empty($val)) {
  495. $stack[] = [$val, $next];
  496. }
  497. } elseif (!array_key_exists($key, $data) || $data[$key] != $val) {
  498. return false;
  499. }
  500. if (empty($needle) && !empty($stack)) {
  501. list($needle, $data) = array_pop($stack);
  502. }
  503. }
  504. return true;
  505. }
  506. /**
  507. * Test whether or not a given path exists in $data.
  508. * This method uses the same path syntax as Hash::extract()
  509. *
  510. * Checking for paths that could target more than one element will
  511. * make sure that at least one matching element exists.
  512. *
  513. * @param array $data The data to check.
  514. * @param string $path The path to check for.
  515. * @return bool Existence of path.
  516. * @see Hash::extract()
  517. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::check
  518. */
  519. public static function check(array $data, $path)
  520. {
  521. $results = static::extract($data, $path);
  522. if (!is_array($results)) {
  523. return false;
  524. }
  525. return count($results) > 0;
  526. }
  527. /**
  528. * Recursively filters a data set.
  529. *
  530. * @param array $data Either an array to filter, or value when in callback
  531. * @param callable $callback A function to filter the data with. Defaults to
  532. * `static::_filter()` Which strips out all non-zero empty values.
  533. * @return array Filtered array
  534. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::filter
  535. */
  536. public static function filter(array $data, $callback = ['self', '_filter'])
  537. {
  538. foreach ($data as $k => $v) {
  539. if (is_array($v)) {
  540. $data[$k] = static::filter($v, $callback);
  541. }
  542. }
  543. return array_filter($data, $callback);
  544. }
  545. /**
  546. * Callback function for filtering.
  547. *
  548. * @param array $var Array to filter.
  549. * @return bool
  550. */
  551. protected static function _filter($var)
  552. {
  553. if ($var === 0 || $var === '0' || !empty($var)) {
  554. return true;
  555. }
  556. return false;
  557. }
  558. /**
  559. * Collapses a multi-dimensional array into a single dimension, using a delimited array path for
  560. * each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes
  561. * ['0.Foo.Bar' => 'Far'].)
  562. *
  563. * @param array $data Array to flatten
  564. * @param string $separator String used to separate array key elements in a path, defaults to '.'
  565. * @return array
  566. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::flatten
  567. */
  568. public static function flatten(array $data, $separator = '.')
  569. {
  570. $result = [];
  571. $stack = [];
  572. $path = null;
  573. reset($data);
  574. while (!empty($data)) {
  575. $key = key($data);
  576. $element = $data[$key];
  577. unset($data[$key]);
  578. if (is_array($element) && !empty($element)) {
  579. if (!empty($data)) {
  580. $stack[] = [$data, $path];
  581. }
  582. $data = $element;
  583. reset($data);
  584. $path .= $key . $separator;
  585. } else {
  586. $result[$path . $key] = $element;
  587. }
  588. if (empty($data) && !empty($stack)) {
  589. list($data, $path) = array_pop($stack);
  590. reset($data);
  591. }
  592. }
  593. return $result;
  594. }
  595. /**
  596. * Expands a flat array to a nested array.
  597. *
  598. * For example, unflattens an array that was collapsed with `Hash::flatten()`
  599. * into a multi-dimensional array. So, `['0.Foo.Bar' => 'Far']` becomes
  600. * `[['Foo' => ['Bar' => 'Far']]]`.
  601. *
  602. * @param array $data Flattened array
  603. * @param string $separator The delimiter used
  604. * @return array
  605. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::expand
  606. */
  607. public static function expand(array $data, $separator = '.')
  608. {
  609. $result = [];
  610. foreach ($data as $flat => $value) {
  611. $keys = explode($separator, $flat);
  612. $keys = array_reverse($keys);
  613. $child = [
  614. $keys[0] => $value
  615. ];
  616. array_shift($keys);
  617. foreach ($keys as $k) {
  618. $child = [
  619. $k => $child
  620. ];
  621. }
  622. $stack = [[$child, &$result]];
  623. static::_merge($stack, $result);
  624. }
  625. return $result;
  626. }
  627. /**
  628. * This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
  629. *
  630. * The difference between this method and the built-in ones, is that if an array key contains another array, then
  631. * Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for
  632. * keys that contain scalar values (unlike `array_merge_recursive`).
  633. *
  634. * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
  635. *
  636. * @param array $data Array to be merged
  637. * @param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
  638. * @return array Merged array
  639. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::merge
  640. */
  641. public static function merge(array $data, $merge)
  642. {
  643. $args = array_slice(func_get_args(), 1);
  644. $return = $data;
  645. foreach ($args as &$curArg) {
  646. $stack[] = [(array)$curArg, &$return];
  647. }
  648. unset($curArg);
  649. static::_merge($stack, $return);
  650. return $return;
  651. }
  652. /**
  653. * Merge helper function to reduce duplicated code between merge() and expand().
  654. *
  655. * @param array $stack The stack of operations to work with.
  656. * @param array $return The return value to operate on.
  657. * @return void
  658. */
  659. protected static function _merge($stack, &$return)
  660. {
  661. while (!empty($stack)) {
  662. foreach ($stack as $curKey => &$curMerge) {
  663. foreach ($curMerge[0] as $key => &$val) {
  664. if (!empty($curMerge[1][$key]) && (array)$curMerge[1][$key] === $curMerge[1][$key] && (array)$val === $val) {
  665. $stack[] = [&$val, &$curMerge[1][$key]];
  666. } elseif ((int)$key === $key && isset($curMerge[1][$key])) {
  667. $curMerge[1][] = $val;
  668. } else {
  669. $curMerge[1][$key] = $val;
  670. }
  671. }
  672. unset($stack[$curKey]);
  673. }
  674. unset($curMerge);
  675. }
  676. }
  677. /**
  678. * Checks to see if all the values in the array are numeric
  679. *
  680. * @param array $data The array to check.
  681. * @return bool true if values are numeric, false otherwise
  682. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::numeric
  683. */
  684. public static function numeric(array $data)
  685. {
  686. if (empty($data)) {
  687. return false;
  688. }
  689. return $data === array_filter($data, 'is_numeric');
  690. }
  691. /**
  692. * Counts the dimensions of an array.
  693. * Only considers the dimension of the first element in the array.
  694. *
  695. * If you have an un-even or heterogenous array, consider using Hash::maxDimensions()
  696. * to get the dimensions of the array.
  697. *
  698. * @param array $data Array to count dimensions on
  699. * @return int The number of dimensions in $data
  700. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::dimensions
  701. */
  702. public static function dimensions(array $data)
  703. {
  704. if (empty($data)) {
  705. return 0;
  706. }
  707. reset($data);
  708. $depth = 1;
  709. while ($elem = array_shift($data)) {
  710. if (is_array($elem)) {
  711. $depth += 1;
  712. $data = $elem;
  713. } else {
  714. break;
  715. }
  716. }
  717. return $depth;
  718. }
  719. /**
  720. * Counts the dimensions of *all* array elements. Useful for finding the maximum
  721. * number of dimensions in a mixed array.
  722. *
  723. * @param array $data Array to count dimensions on
  724. * @return int The maximum number of dimensions in $data
  725. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::maxDimensions
  726. */
  727. public static function maxDimensions(array $data)
  728. {
  729. $depth = [];
  730. if (is_array($data) && reset($data) !== false) {
  731. foreach ($data as $value) {
  732. if (is_array($value)) {
  733. $depth[] = static::maxDimensions($value) + 1;
  734. } else {
  735. $depth[] = 1;
  736. }
  737. }
  738. }
  739. return empty($depth) ? 0 : max($depth);
  740. }
  741. /**
  742. * Map a callback across all elements in a set.
  743. * Can be provided a path to only modify slices of the set.
  744. *
  745. * @param array $data The data to map over, and extract data out of.
  746. * @param string $path The path to extract for mapping over.
  747. * @param callable $function The function to call on each extracted value.
  748. * @return array An array of the modified values.
  749. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::map
  750. */
  751. public static function map(array $data, $path, $function)
  752. {
  753. $values = (array)static::extract($data, $path);
  754. return array_map($function, $values);
  755. }
  756. /**
  757. * Reduce a set of extracted values using `$function`.
  758. *
  759. * @param array $data The data to reduce.
  760. * @param string $path The path to extract from $data.
  761. * @param callable $function The function to call on each extracted value.
  762. * @return mixed The reduced value.
  763. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::reduce
  764. */
  765. public static function reduce(array $data, $path, $function)
  766. {
  767. $values = (array)static::extract($data, $path);
  768. return array_reduce($values, $function);
  769. }
  770. /**
  771. * Apply a callback to a set of extracted values using `$function`.
  772. * The function will get the extracted values as the first argument.
  773. *
  774. * ### Example
  775. *
  776. * You can easily count the results of an extract using apply().
  777. * For example to count the comments on an Article:
  778. *
  779. * ```
  780. * $count = Hash::apply($data, 'Article.Comment.{n}', 'count');
  781. * ```
  782. *
  783. * You could also use a function like `array_sum` to sum the results.
  784. *
  785. * ```
  786. * $total = Hash::apply($data, '{n}.Item.price', 'array_sum');
  787. * ```
  788. *
  789. * @param array $data The data to reduce.
  790. * @param string $path The path to extract from $data.
  791. * @param callable $function The function to call on each extracted value.
  792. * @return mixed The results of the applied method.
  793. */
  794. public static function apply(array $data, $path, $function)
  795. {
  796. $values = (array)static::extract($data, $path);
  797. return call_user_func($function, $values);
  798. }
  799. /**
  800. * Sorts an array by any value, determined by a Set-compatible path
  801. *
  802. * ### Sort directions
  803. *
  804. * - `asc` Sort ascending.
  805. * - `desc` Sort descending.
  806. *
  807. * ### Sort types
  808. *
  809. * - `regular` For regular sorting (don't change types)
  810. * - `numeric` Compare values numerically
  811. * - `string` Compare values as strings
  812. * - `natural` Compare items as strings using "natural ordering" in a human friendly way.
  813. * Will sort foo10 below foo2 as an example.
  814. *
  815. * @param array $data An array of data to sort
  816. * @param string $path A Set-compatible path to the array value
  817. * @param string $dir See directions above. Defaults to 'asc'.
  818. * @param string $type See direction types above. Defaults to 'regular'.
  819. * @return array Sorted array of data
  820. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::sort
  821. */
  822. public static function sort(array $data, $path, $dir = 'asc', $type = 'regular')
  823. {
  824. if (empty($data)) {
  825. return [];
  826. }
  827. $originalKeys = array_keys($data);
  828. $numeric = is_numeric(implode('', $originalKeys));
  829. if ($numeric) {
  830. $data = array_values($data);
  831. }
  832. $sortValues = static::extract($data, $path);
  833. $sortCount = count($sortValues);
  834. $dataCount = count($data);
  835. // Make sortValues match the data length, as some keys could be missing
  836. // the sorted value path.
  837. if ($sortCount < $dataCount) {
  838. $sortValues = array_pad($sortValues, $dataCount, null);
  839. }
  840. $result = static::_squash($sortValues);
  841. $keys = static::extract($result, '{n}.id');
  842. $values = static::extract($result, '{n}.value');
  843. $dir = strtolower($dir);
  844. $type = strtolower($type);
  845. if ($dir === 'asc') {
  846. $dir = SORT_ASC;
  847. } else {
  848. $dir = SORT_DESC;
  849. }
  850. if ($type === 'numeric') {
  851. $type = SORT_NUMERIC;
  852. } elseif ($type === 'string') {
  853. $type = SORT_STRING;
  854. } elseif ($type === 'natural') {
  855. $type = SORT_NATURAL;
  856. } else {
  857. $type = SORT_REGULAR;
  858. }
  859. array_multisort($values, $dir, $type, $keys, $dir, $type);
  860. $sorted = [];
  861. $keys = array_unique($keys);
  862. foreach ($keys as $k) {
  863. if ($numeric) {
  864. $sorted[] = $data[$k];
  865. continue;
  866. }
  867. if (isset($originalKeys[$k])) {
  868. $sorted[$originalKeys[$k]] = $data[$originalKeys[$k]];
  869. } else {
  870. $sorted[$k] = $data[$k];
  871. }
  872. }
  873. return $sorted;
  874. }
  875. /**
  876. * Helper method for sort()
  877. * Squashes an array to a single hash so it can be sorted.
  878. *
  879. * @param array $data The data to squash.
  880. * @param string|null $key The key for the data.
  881. * @return array
  882. */
  883. protected static function _squash(array $data, $key = null)
  884. {
  885. $stack = [];
  886. foreach ($data as $k => $r) {
  887. $id = $k;
  888. if ($key !== null) {
  889. $id = $key;
  890. }
  891. if (is_array($r) && !empty($r)) {
  892. $stack = array_merge($stack, static::_squash($r, $id));
  893. } else {
  894. $stack[] = ['id' => $id, 'value' => $r];
  895. }
  896. }
  897. return $stack;
  898. }
  899. /**
  900. * Computes the difference between two complex arrays.
  901. * This method differs from the built-in array_diff() in that it will preserve keys
  902. * and work on multi-dimensional arrays.
  903. *
  904. * @param array $data First value
  905. * @param array $compare Second value
  906. * @return array Returns the key => value pairs that are not common in $data and $compare
  907. * The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
  908. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::diff
  909. */
  910. public static function diff(array $data, array $compare)
  911. {
  912. if (empty($data)) {
  913. return (array)$compare;
  914. }
  915. if (empty($compare)) {
  916. return (array)$data;
  917. }
  918. $intersection = array_intersect_key($data, $compare);
  919. while (($key = key($intersection)) !== null) {
  920. if ($data[$key] == $compare[$key]) {
  921. unset($data[$key]);
  922. unset($compare[$key]);
  923. }
  924. next($intersection);
  925. }
  926. return $data + $compare;
  927. }
  928. /**
  929. * Merges the difference between $data and $compare onto $data.
  930. *
  931. * @param array $data The data to append onto.
  932. * @param array $compare The data to compare and append onto.
  933. * @return array The merged array.
  934. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::mergeDiff
  935. */
  936. public static function mergeDiff(array $data, array $compare)
  937. {
  938. if (empty($data) && !empty($compare)) {
  939. return $compare;
  940. }
  941. if (empty($compare)) {
  942. return $data;
  943. }
  944. foreach ($compare as $key => $value) {
  945. if (!array_key_exists($key, $data)) {
  946. $data[$key] = $value;
  947. } elseif (is_array($value)) {
  948. $data[$key] = static::mergeDiff($data[$key], $compare[$key]);
  949. }
  950. }
  951. return $data;
  952. }
  953. /**
  954. * Normalizes an array, and converts it to a standard format.
  955. *
  956. * @param array $data List to normalize
  957. * @param bool $assoc If true, $data will be converted to an associative array.
  958. * @return array
  959. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::normalize
  960. */
  961. public static function normalize(array $data, $assoc = true)
  962. {
  963. $keys = array_keys($data);
  964. $count = count($keys);
  965. $numeric = true;
  966. if (!$assoc) {
  967. for ($i = 0; $i < $count; $i++) {
  968. if (!is_int($keys[$i])) {
  969. $numeric = false;
  970. break;
  971. }
  972. }
  973. }
  974. if (!$numeric || $assoc) {
  975. $newList = [];
  976. for ($i = 0; $i < $count; $i++) {
  977. if (is_int($keys[$i])) {
  978. $newList[$data[$keys[$i]]] = null;
  979. } else {
  980. $newList[$keys[$i]] = $data[$keys[$i]];
  981. }
  982. }
  983. $data = $newList;
  984. }
  985. return $data;
  986. }
  987. /**
  988. * Takes in a flat array and returns a nested array
  989. *
  990. * ### Options:
  991. *
  992. * - `children` The key name to use in the resultset for children.
  993. * - `idPath` The path to a key that identifies each entry. Should be
  994. * compatible with Hash::extract(). Defaults to `{n}.$alias.id`
  995. * - `parentPath` The path to a key that identifies the parent of each entry.
  996. * Should be compatible with Hash::extract(). Defaults to `{n}.$alias.parent_id`
  997. * - `root` The id of the desired top-most result.
  998. *
  999. * @param array $data The data to nest.
  1000. * @param array $options Options are:
  1001. * @return array of results, nested
  1002. * @see Hash::extract()
  1003. * @throws \InvalidArgumentException When providing invalid data.
  1004. * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::nest
  1005. */
  1006. public static function nest(array $data, array $options = [])
  1007. {
  1008. if (!$data) {
  1009. return $data;
  1010. }
  1011. $alias = key(current($data));
  1012. $options += [
  1013. 'idPath' => "{n}.$alias.id",
  1014. 'parentPath' => "{n}.$alias.parent_id",
  1015. 'children' => 'children',
  1016. 'root' => null
  1017. ];
  1018. $return = $idMap = [];
  1019. $ids = static::extract($data, $options['idPath']);
  1020. $idKeys = explode('.', $options['idPath']);
  1021. array_shift($idKeys);
  1022. $parentKeys = explode('.', $options['parentPath']);
  1023. array_shift($parentKeys);
  1024. foreach ($data as $result) {
  1025. $result[$options['children']] = [];
  1026. $id = static::get($result, $idKeys);
  1027. $parentId = static::get($result, $parentKeys);
  1028. if (isset($idMap[$id][$options['children']])) {
  1029. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  1030. } else {
  1031. $idMap[$id] = array_merge($result, [$options['children'] => []]);
  1032. }
  1033. if (!$parentId || !in_array($parentId, $ids)) {
  1034. $return[] =& $idMap[$id];
  1035. } else {
  1036. $idMap[$parentId][$options['children']][] =& $idMap[$id];
  1037. }
  1038. }
  1039. if (!$return) {
  1040. throw new InvalidArgumentException('Invalid data array to nest.');
  1041. }
  1042. if ($options['root']) {
  1043. $root = $options['root'];
  1044. } else {
  1045. $root = static::get($return[0], $parentKeys);
  1046. }
  1047. foreach ($return as $i => $result) {
  1048. $id = static::get($result, $idKeys);
  1049. $parentId = static::get($result, $parentKeys);
  1050. if ($id !== $root && $parentId != $root) {
  1051. unset($return[$i]);
  1052. }
  1053. }
  1054. return array_values($return);
  1055. }
  1056. }