Hash.php 31 KB

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