PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/Hash.php

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