PageRenderTime 65ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/Hash.php

https://bitbucket.org/tlorens/cakefoundation
PHP | 973 lines | 559 code | 78 blank | 336 comment | 146 complexity | ea110936131958762d1c8515a4e84aeb MD5 | raw file
  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) || empty($path)) {
  40. return null;
  41. }
  42. if (is_string($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 ($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)) {
  483. if (!empty($data)) {
  484. $stack[] = array($data, $path);
  485. }
  486. $data = $element;
  487. $path .= $key . $separator;
  488. } else {
  489. $result[$path . $key] = $element;
  490. }
  491. if (empty($data) && !empty($stack)) {
  492. list($data, $path) = array_pop($stack);
  493. }
  494. }
  495. return $result;
  496. }
  497. /**
  498. * Expand/unflattens an string to an array
  499. *
  500. * For example, unflattens an array that was collapsed with `Hash::flatten()`
  501. * into a multi-dimensional array. So, `array('0.Foo.Bar' => 'Far')` becomes
  502. * `array(array('Foo' => array('Bar' => 'Far')))`.
  503. *
  504. * @param array $data Flattened array
  505. * @param string $separator The delimiter used
  506. * @return array
  507. */
  508. public static function expand($data, $separator = '.') {
  509. $result = array();
  510. foreach ($data as $flat => $value) {
  511. $keys = explode($separator, $flat);
  512. $keys = array_reverse($keys);
  513. $child = array(
  514. $keys[0] => $value
  515. );
  516. array_shift($keys);
  517. foreach ($keys as $k) {
  518. $child = array(
  519. $k => $child
  520. );
  521. }
  522. $result = self::merge($result, $child);
  523. }
  524. return $result;
  525. }
  526. /**
  527. * This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
  528. *
  529. * The difference between this method and the built-in ones, is that if an array key contains another array, then
  530. * Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for
  531. * keys that contain scalar values (unlike `array_merge_recursive`).
  532. *
  533. * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
  534. *
  535. * @param array $data Array to be merged
  536. * @param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
  537. * @return array Merged array
  538. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
  539. */
  540. public static function merge(array $data, $merge) {
  541. $args = func_get_args();
  542. $return = current($args);
  543. while (($arg = next($args)) !== false) {
  544. foreach ((array)$arg as $key => $val) {
  545. if (!empty($return[$key]) && is_array($return[$key]) && is_array($val)) {
  546. $return[$key] = self::merge($return[$key], $val);
  547. } elseif (is_int($key)) {
  548. $return[] = $val;
  549. } else {
  550. $return[$key] = $val;
  551. }
  552. }
  553. }
  554. return $return;
  555. }
  556. /**
  557. * Checks to see if all the values in the array are numeric
  558. *
  559. * @param array $array The array to check.
  560. * @return boolean true if values are numeric, false otherwise
  561. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric
  562. */
  563. public static function numeric(array $data) {
  564. if (empty($data)) {
  565. return false;
  566. }
  567. $values = array_values($data);
  568. $str = implode('', $values);
  569. return (bool)ctype_digit($str);
  570. }
  571. /**
  572. * Counts the dimensions of an array.
  573. * Only considers the dimension of the first element in the array.
  574. *
  575. * If you have an un-even or hetrogenous array, consider using Hash::maxDimensions()
  576. * to get the dimensions of the array.
  577. *
  578. * @param array $array Array to count dimensions on
  579. * @return integer The number of dimensions in $data
  580. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions
  581. */
  582. public static function dimensions(array $data) {
  583. if (empty($data)) {
  584. return 0;
  585. }
  586. reset($data);
  587. $depth = 1;
  588. while ($elem = array_shift($data)) {
  589. if (is_array($elem)) {
  590. $depth += 1;
  591. $data =& $elem;
  592. } else {
  593. break;
  594. }
  595. }
  596. return $depth;
  597. }
  598. /**
  599. * Counts the dimensions of *all* array elements. Useful for finding the maximum
  600. * number of dimensions in a mixed array.
  601. *
  602. * @param array $data Array to count dimensions on
  603. * @return integer The maximum number of dimensions in $data
  604. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions
  605. */
  606. public static function maxDimensions(array $data) {
  607. $depth = array();
  608. if (is_array($data) && reset($data) !== false) {
  609. foreach ($data as $value) {
  610. $depth[] = self::dimensions((array)$value) + 1;
  611. }
  612. }
  613. return max($depth);
  614. }
  615. /**
  616. * Map a callback across all elements in a set.
  617. * Can be provided a path to only modify slices of the set.
  618. *
  619. * @param array $data The data to map over, and extract data out of.
  620. * @param string $path The path to extract for mapping over.
  621. * @param callable $function The function to call on each extracted value.
  622. * @return array An array of the modified values.
  623. */
  624. public static function map(array $data, $path, $function) {
  625. $values = (array)self::extract($data, $path);
  626. return array_map($function, $values);
  627. }
  628. /**
  629. * Reduce a set of extracted values using `$function`.
  630. *
  631. * @param array $data The data to reduce.
  632. * @param string $path The path to extract from $data.
  633. * @return mixed The reduced value.
  634. */
  635. public static function reduce(array $data, $path, $function) {
  636. $values = (array)self::extract($data, $path);
  637. return array_reduce($values, $function);
  638. }
  639. /**
  640. * Apply a callback to a set of extracted values using `$function`.
  641. * The function will get the extracted values as the first argument.
  642. *
  643. * @param array $data The data to reduce.
  644. * @param string $path The path to extract from $data.
  645. * @return mixed The results of the applied method.
  646. */
  647. public static function apply(array $data, $path, $function) {
  648. $values = (array)self::extract($data, $path);
  649. return call_user_func($function, $values);
  650. }
  651. /**
  652. * Sorts an array by any value, determined by a Set-compatible path
  653. *
  654. * ### Sort directions
  655. *
  656. * - `asc` Sort ascending.
  657. * - `desc` Sort descending.
  658. *
  659. * ## Sort types
  660. *
  661. * - `numeric` Sort by numeric value.
  662. * - `regular` Sort by numeric value.
  663. * - `string` Sort by numeric value.
  664. * - `natural` Sort by natural order. Requires PHP 5.4 or greater.
  665. *
  666. * @param array $data An array of data to sort
  667. * @param string $path A Set-compatible path to the array value
  668. * @param string $dir See directions above.
  669. * @param string $type See direction types above. Defaults to 'regular'.
  670. * @return array Sorted array of data
  671. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
  672. */
  673. public static function sort(array $data, $path, $dir, $type = 'regular') {
  674. $originalKeys = array_keys($data);
  675. $numeric = is_numeric(implode('', $originalKeys));
  676. if ($numeric) {
  677. $data = array_values($data);
  678. }
  679. $sortValues = self::extract($data, $path);
  680. $sortCount = count($sortValues);
  681. $dataCount = count($data);
  682. // Make sortValues match the data length, as some keys could be missing
  683. // the sorted value path.
  684. if ($sortCount < $dataCount) {
  685. $sortValues = array_pad($sortValues, $dataCount, null);
  686. }
  687. $result = self::_squash($sortValues);
  688. $keys = self::extract($result, '{n}.id');
  689. $values = self::extract($result, '{n}.value');
  690. $dir = strtolower($dir);
  691. $type = strtolower($type);
  692. if ($type == 'natural' && version_compare(PHP_VERSION, '5.4.0', '<')) {
  693. $type == 'regular';
  694. }
  695. if ($dir === 'asc') {
  696. $dir = SORT_ASC;
  697. } else {
  698. $dir = SORT_DESC;
  699. }
  700. if ($type === 'numeric') {
  701. $type = SORT_NUMERIC;
  702. } elseif ($type === 'string') {
  703. $type = SORT_STRING;
  704. } elseif ($type === 'natural') {
  705. $type = SORT_NATURAL;
  706. } else {
  707. $type = SORT_REGULAR;
  708. }
  709. array_multisort($values, $dir, $type, $keys, $dir, $type);
  710. $sorted = array();
  711. $keys = array_unique($keys);
  712. foreach ($keys as $k) {
  713. if ($numeric) {
  714. $sorted[] = $data[$k];
  715. continue;
  716. }
  717. if (isset($originalKeys[$k])) {
  718. $sorted[$originalKeys[$k]] = $data[$originalKeys[$k]];
  719. } else {
  720. $sorted[$k] = $data[$k];
  721. }
  722. }
  723. return $sorted;
  724. }
  725. /**
  726. * Helper method for sort()
  727. * Sqaushes an array to a single hash so it can be sorted.
  728. *
  729. * @param array $data The data to squash.
  730. * @param string $key The key for the data.
  731. * @return array
  732. */
  733. protected static function _squash($data, $key = null) {
  734. $stack = array();
  735. foreach ($data as $k => $r) {
  736. $id = $k;
  737. if (!is_null($key)) {
  738. $id = $key;
  739. }
  740. if (is_array($r) && !empty($r)) {
  741. $stack = array_merge($stack, self::_squash($r, $id));
  742. } else {
  743. $stack[] = array('id' => $id, 'value' => $r);
  744. }
  745. }
  746. return $stack;
  747. }
  748. /**
  749. * Computes the difference between two complex arrays.
  750. * This method differs from the built-in array_diff() in that it will preserve keys
  751. * and work on multi-dimensional arrays.
  752. *
  753. * @param array $data First value
  754. * @param array $compare Second value
  755. * @return array Returns the key => value pairs that are not common in $data and $compare
  756. * The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
  757. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::diff
  758. */
  759. public static function diff(array $data, $compare) {
  760. if (empty($data)) {
  761. return (array)$compare;
  762. }
  763. if (empty($compare)) {
  764. return (array)$data;
  765. }
  766. $intersection = array_intersect_key($data, $compare);
  767. while (($key = key($intersection)) !== null) {
  768. if ($data[$key] == $compare[$key]) {
  769. unset($data[$key]);
  770. unset($compare[$key]);
  771. }
  772. next($intersection);
  773. }
  774. return $data + $compare;
  775. }
  776. /**
  777. * Merges the difference between $data and $push onto $data.
  778. *
  779. * @param array $data The data to append onto.
  780. * @param array $compare The data to compare and append onto.
  781. * @return array The merged array.
  782. */
  783. public static function mergeDiff(array $data, $compare) {
  784. if (empty($data) && !empty($compare)) {
  785. return $compare;
  786. }
  787. if (empty($compare)) {
  788. return $data;
  789. }
  790. foreach ($compare as $key => $value) {
  791. if (!array_key_exists($key, $data)) {
  792. $data[$key] = $value;
  793. } elseif (is_array($value)) {
  794. $data[$key] = self::mergeDiff($data[$key], $compare[$key]);
  795. }
  796. }
  797. return $data;
  798. }
  799. /**
  800. * Normalizes an array, and converts it to a standard format.
  801. *
  802. * @param array $data List to normalize
  803. * @param boolean $assoc If true, $data will be converted to an associative array.
  804. * @return array
  805. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize
  806. */
  807. public static function normalize(array $data, $assoc = true) {
  808. $keys = array_keys($data);
  809. $count = count($keys);
  810. $numeric = true;
  811. if (!$assoc) {
  812. for ($i = 0; $i < $count; $i++) {
  813. if (!is_int($keys[$i])) {
  814. $numeric = false;
  815. break;
  816. }
  817. }
  818. }
  819. if (!$numeric || $assoc) {
  820. $newList = array();
  821. for ($i = 0; $i < $count; $i++) {
  822. if (is_int($keys[$i])) {
  823. $newList[$data[$keys[$i]]] = null;
  824. } else {
  825. $newList[$keys[$i]] = $data[$keys[$i]];
  826. }
  827. }
  828. $data = $newList;
  829. }
  830. return $data;
  831. }
  832. /**
  833. * Takes in a flat array and returns a nested array
  834. *
  835. * ### Options:
  836. *
  837. * - `children` The key name to use in the resultset for children.
  838. * - `idPath` The path to a key that identifies each entry. Should be
  839. * compatible with Hash::extract(). Defaults to `{n}.$alias.id`
  840. * - `parentPath` The path to a key that identifies the parent of each entry.
  841. * Should be compatible with Hash::extract(). Defaults to `{n}.$alias.parent_id`
  842. * - `root` The id of the desired top-most result.
  843. *
  844. * @param array $data The data to nest.
  845. * @param array $options Options are:
  846. * @return array of results, nested
  847. * @see Hash::extract()
  848. */
  849. public static function nest(array $data, $options = array()) {
  850. if (!$data) {
  851. return $data;
  852. }
  853. $alias = key(current($data));
  854. $options += array(
  855. 'idPath' => "{n}.$alias.id",
  856. 'parentPath' => "{n}.$alias.parent_id",
  857. 'children' => 'children',
  858. 'root' => null
  859. );
  860. $return = $idMap = array();
  861. $ids = self::extract($data, $options['idPath']);
  862. $idKeys = explode('.', $options['idPath']);
  863. array_shift($idKeys);
  864. $parentKeys = explode('.', $options['parentPath']);
  865. array_shift($parentKeys);
  866. foreach ($data as $result) {
  867. $result[$options['children']] = array();
  868. $id = self::get($result, $idKeys);
  869. $parentId = self::get($result, $parentKeys);
  870. if (isset($idMap[$id][$options['children']])) {
  871. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  872. } else {
  873. $idMap[$id] = array_merge($result, array($options['children'] => array()));
  874. }
  875. if (!$parentId || !in_array($parentId, $ids)) {
  876. $return[] =& $idMap[$id];
  877. } else {
  878. $idMap[$parentId][$options['children']][] =& $idMap[$id];
  879. }
  880. }
  881. if ($options['root']) {
  882. $root = $options['root'];
  883. } else {
  884. $root = self::get($return[0], $parentKeys);
  885. }
  886. foreach ($return as $i => $result) {
  887. $id = self::get($result, $idKeys);
  888. $parentId = self::get($result, $parentKeys);
  889. if ($id !== $root && $parentId != $root) {
  890. unset($return[$i]);
  891. }
  892. }
  893. return array_values($return);
  894. }
  895. }