PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Utility/Hash.php

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