PageRenderTime 71ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/Hash.php

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