Hash.php 27 KB

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