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

/lib/Cake/Utility/Hash.php

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