PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Hash.php

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