PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Hash.php

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