Hash.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 boolean
  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 boolean 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. if ($prop === true || $prop === false) {
  192. $prop = $prop ? 'true' : 'false';
  193. }
  194. // Pattern matches and other operators.
  195. if ($op === '=' && $val && $val[0] === '/') {
  196. if (!preg_match($val, $prop)) {
  197. return false;
  198. }
  199. } elseif (
  200. ($op === '=' && $prop != $val) ||
  201. ($op === '!=' && $prop == $val) ||
  202. ($op === '>' && $prop <= $val) ||
  203. ($op === '<' && $prop >= $val) ||
  204. ($op === '>=' && $prop < $val) ||
  205. ($op === '<=' && $prop > $val)
  206. ) {
  207. return false;
  208. }
  209. }
  210. return true;
  211. }
  212. /**
  213. * Insert $values into an array with the given $path. You can use
  214. * `{n}` and `{s}` elements to insert $data multiple times.
  215. *
  216. * @param array $data The data to insert into.
  217. * @param string $path The path to insert at.
  218. * @param array $values The values to insert.
  219. * @return array The data with $values inserted.
  220. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::insert
  221. */
  222. public static function insert(array $data, $path, $values = null) {
  223. if (strpos($path, '[') === false) {
  224. $tokens = explode('.', $path);
  225. } else {
  226. $tokens = String::tokenize($path, '.', '[', ']');
  227. }
  228. if (strpos($path, '{') === false && strpos($path, '[') === false) {
  229. return self::_simpleOp('insert', $data, $tokens, $values);
  230. }
  231. $token = array_shift($tokens);
  232. $nextPath = implode('.', $tokens);
  233. list($token, $conditions) = self::_splitConditions($token);
  234. foreach ($data as $k => $v) {
  235. if (self::_matchToken($k, $token)) {
  236. if ($conditions && self::_matches($v, $conditions)) {
  237. $data[$k] = array_merge($v, $values);
  238. continue;
  239. }
  240. if (!$conditions) {
  241. $data[$k] = self::insert($v, $nextPath, $values);
  242. }
  243. }
  244. }
  245. return $data;
  246. }
  247. /**
  248. * Perform a simple insert/remove operation.
  249. *
  250. * @param string $op The operation to do.
  251. * @param array $data The data to operate on.
  252. * @param array $path The path to work on.
  253. * @param mixed $values The values to insert when doing inserts.
  254. * @return array $data.
  255. */
  256. protected static function _simpleOp($op, $data, $path, $values = null) {
  257. $_list =& $data;
  258. $count = count($path);
  259. $last = $count - 1;
  260. foreach ($path as $i => $key) {
  261. if (is_numeric($key) && intval($key) > 0 || $key === '0') {
  262. $key = intval($key);
  263. }
  264. if ($op === 'insert') {
  265. if ($i === $last) {
  266. $_list[$key] = $values;
  267. return $data;
  268. }
  269. if (!isset($_list[$key])) {
  270. $_list[$key] = array();
  271. }
  272. $_list =& $_list[$key];
  273. if (!is_array($_list)) {
  274. $_list = array();
  275. }
  276. } elseif ($op === 'remove') {
  277. if ($i === $last) {
  278. unset($_list[$key]);
  279. return $data;
  280. }
  281. if (!isset($_list[$key])) {
  282. return $data;
  283. }
  284. $_list =& $_list[$key];
  285. }
  286. }
  287. }
  288. /**
  289. * Remove data matching $path from the $data array.
  290. * You can use `{n}` and `{s}` to remove multiple elements
  291. * from $data.
  292. *
  293. * @param array $data The data to operate on
  294. * @param string $path A path expression to use to remove.
  295. * @return array The modified array.
  296. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::remove
  297. */
  298. public static function remove(array $data, $path) {
  299. if (strpos($path, '[') === false) {
  300. $tokens = explode('.', $path);
  301. } else {
  302. $tokens = String::tokenize($path, '.', '[', ']');
  303. }
  304. if (strpos($path, '{') === false && strpos($path, '[') === false) {
  305. return self::_simpleOp('remove', $data, $tokens);
  306. }
  307. $token = array_shift($tokens);
  308. $nextPath = implode('.', $tokens);
  309. list($token, $conditions) = self::_splitConditions($token);
  310. foreach ($data as $k => $v) {
  311. $match = self::_matchToken($k, $token);
  312. if ($match && is_array($v)) {
  313. if ($conditions && self::_matches($v, $conditions)) {
  314. unset($data[$k]);
  315. continue;
  316. }
  317. $data[$k] = self::remove($v, $nextPath);
  318. if (empty($data[$k])) {
  319. unset($data[$k]);
  320. }
  321. } elseif ($match) {
  322. unset($data[$k]);
  323. }
  324. }
  325. return $data;
  326. }
  327. /**
  328. * Creates an associative array using `$keyPath` as the path to build its keys, and optionally
  329. * `$valuePath` as path to get the values. If `$valuePath` is not specified, all values will be initialized
  330. * to null (useful for Hash::merge). You can optionally group the values by what is obtained when
  331. * following the path specified in `$groupPath`.
  332. *
  333. * @param array $data Array from where to extract keys and values
  334. * @param string $keyPath A dot-separated string.
  335. * @param string $valuePath A dot-separated string.
  336. * @param string $groupPath A dot-separated string.
  337. * @return array Combined array
  338. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::combine
  339. * @throws CakeException CakeException When keys and values count is unequal.
  340. */
  341. public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null) {
  342. if (empty($data)) {
  343. return array();
  344. }
  345. if (is_array($keyPath)) {
  346. $format = array_shift($keyPath);
  347. $keys = self::format($data, $keyPath, $format);
  348. } else {
  349. $keys = self::extract($data, $keyPath);
  350. }
  351. if (empty($keys)) {
  352. return array();
  353. }
  354. if (!empty($valuePath) && is_array($valuePath)) {
  355. $format = array_shift($valuePath);
  356. $vals = self::format($data, $valuePath, $format);
  357. } elseif (!empty($valuePath)) {
  358. $vals = self::extract($data, $valuePath);
  359. }
  360. if (empty($vals)) {
  361. $vals = array_fill(0, count($keys), null);
  362. }
  363. if (count($keys) !== count($vals)) {
  364. throw new CakeException(__d(
  365. 'cake_dev',
  366. 'Hash::combine() needs an equal number of keys + values.'
  367. ));
  368. }
  369. if ($groupPath !== null) {
  370. $group = self::extract($data, $groupPath);
  371. if (!empty($group)) {
  372. $c = count($keys);
  373. for ($i = 0; $i < $c; $i++) {
  374. if (!isset($group[$i])) {
  375. $group[$i] = 0;
  376. }
  377. if (!isset($out[$group[$i]])) {
  378. $out[$group[$i]] = array();
  379. }
  380. $out[$group[$i]][$keys[$i]] = $vals[$i];
  381. }
  382. return $out;
  383. }
  384. }
  385. if (empty($vals)) {
  386. return array();
  387. }
  388. return array_combine($keys, $vals);
  389. }
  390. /**
  391. * Returns a formatted series of values extracted from `$data`, using
  392. * `$format` as the format and `$paths` as the values to extract.
  393. *
  394. * Usage:
  395. *
  396. * {{{
  397. * $result = Hash::format($users, array('{n}.User.id', '{n}.User.name'), '%s : %s');
  398. * }}}
  399. *
  400. * The `$format` string can use any format options that `vsprintf()` and `sprintf()` do.
  401. *
  402. * @param array $data Source array from which to extract the data
  403. * @param string $paths An array containing one or more Hash::extract()-style key paths
  404. * @param string $format Format string into which values will be inserted, see sprintf()
  405. * @return array An array of strings extracted from `$path` and formatted with `$format`
  406. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
  407. * @see sprintf()
  408. * @see Hash::extract()
  409. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::format
  410. */
  411. public static function format(array $data, array $paths, $format) {
  412. $extracted = array();
  413. $count = count($paths);
  414. if (!$count) {
  415. return;
  416. }
  417. for ($i = 0; $i < $count; $i++) {
  418. $extracted[] = self::extract($data, $paths[$i]);
  419. }
  420. $out = array();
  421. $data = $extracted;
  422. $count = count($data[0]);
  423. $countTwo = count($data);
  424. for ($j = 0; $j < $count; $j++) {
  425. $args = array();
  426. for ($i = 0; $i < $countTwo; $i++) {
  427. if (array_key_exists($j, $data[$i])) {
  428. $args[] = $data[$i][$j];
  429. }
  430. }
  431. $out[] = vsprintf($format, $args);
  432. }
  433. return $out;
  434. }
  435. /**
  436. * Determines if one array contains the exact keys and values of another.
  437. *
  438. * @param array $data The data to search through.
  439. * @param array $needle The values to file in $data
  440. * @return boolean true if $data contains $needle, false otherwise
  441. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::contains
  442. */
  443. public static function contains(array $data, array $needle) {
  444. if (empty($data) || empty($needle)) {
  445. return false;
  446. }
  447. $stack = array();
  448. while (!empty($needle)) {
  449. $key = key($needle);
  450. $val = $needle[$key];
  451. unset($needle[$key]);
  452. if (array_key_exists($key, $data) && is_array($val)) {
  453. $next = $data[$key];
  454. unset($data[$key]);
  455. if (!empty($val)) {
  456. $stack[] = array($val, $next);
  457. }
  458. } elseif (!array_key_exists($key, $data) || $data[$key] != $val) {
  459. return false;
  460. }
  461. if (empty($needle) && !empty($stack)) {
  462. list($needle, $data) = array_pop($stack);
  463. }
  464. }
  465. return true;
  466. }
  467. /**
  468. * Test whether or not a given path exists in $data.
  469. * This method uses the same path syntax as Hash::extract()
  470. *
  471. * Checking for paths that could target more than one element will
  472. * make sure that at least one matching element exists.
  473. *
  474. * @param array $data The data to check.
  475. * @param string $path The path to check for.
  476. * @return boolean Existence of path.
  477. * @see Hash::extract()
  478. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::check
  479. */
  480. public static function check(array $data, $path) {
  481. $results = self::extract($data, $path);
  482. if (!is_array($results)) {
  483. return false;
  484. }
  485. return count($results) > 0;
  486. }
  487. /**
  488. * Recursively filters a data set.
  489. *
  490. * @param array $data Either an array to filter, or value when in callback
  491. * @param callable $callback A function to filter the data with. Defaults to
  492. * `self::_filter()` Which strips out all non-zero empty values.
  493. * @return array Filtered array
  494. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::filter
  495. */
  496. public static function filter(array $data, $callback = array('self', '_filter')) {
  497. foreach ($data as $k => $v) {
  498. if (is_array($v)) {
  499. $data[$k] = self::filter($v, $callback);
  500. }
  501. }
  502. return array_filter($data, $callback);
  503. }
  504. /**
  505. * Callback function for filtering.
  506. *
  507. * @param array $var Array to filter.
  508. * @return boolean
  509. */
  510. protected static function _filter($var) {
  511. if ($var === 0 || $var === '0' || !empty($var)) {
  512. return true;
  513. }
  514. return false;
  515. }
  516. /**
  517. * Collapses a multi-dimensional array into a single dimension, using a delimited array path for
  518. * each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes
  519. * array('0.Foo.Bar' => 'Far').)
  520. *
  521. * @param array $data Array to flatten
  522. * @param string $separator String used to separate array key elements in a path, defaults to '.'
  523. * @return array
  524. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::flatten
  525. */
  526. public static function flatten(array $data, $separator = '.') {
  527. $result = array();
  528. $stack = array();
  529. $path = null;
  530. reset($data);
  531. while (!empty($data)) {
  532. $key = key($data);
  533. $element = $data[$key];
  534. unset($data[$key]);
  535. if (is_array($element) && !empty($element)) {
  536. if (!empty($data)) {
  537. $stack[] = array($data, $path);
  538. }
  539. $data = $element;
  540. reset($data);
  541. $path .= $key . $separator;
  542. } else {
  543. $result[$path . $key] = $element;
  544. }
  545. if (empty($data) && !empty($stack)) {
  546. list($data, $path) = array_pop($stack);
  547. reset($data);
  548. }
  549. }
  550. return $result;
  551. }
  552. /**
  553. * Expands a flat array to a nested array.
  554. *
  555. * For example, unflattens an array that was collapsed with `Hash::flatten()`
  556. * into a multi-dimensional array. So, `array('0.Foo.Bar' => 'Far')` becomes
  557. * `array(array('Foo' => array('Bar' => 'Far')))`.
  558. *
  559. * @param array $data Flattened array
  560. * @param string $separator The delimiter used
  561. * @return array
  562. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::expand
  563. */
  564. public static function expand($data, $separator = '.') {
  565. $result = array();
  566. foreach ($data as $flat => $value) {
  567. $keys = explode($separator, $flat);
  568. $keys = array_reverse($keys);
  569. $child = array(
  570. $keys[0] => $value
  571. );
  572. array_shift($keys);
  573. foreach ($keys as $k) {
  574. $child = array(
  575. $k => $child
  576. );
  577. }
  578. $result = self::merge($result, $child);
  579. }
  580. return $result;
  581. }
  582. /**
  583. * This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
  584. *
  585. * The difference between this method and the built-in ones, is that if an array key contains another array, then
  586. * Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for
  587. * keys that contain scalar values (unlike `array_merge_recursive`).
  588. *
  589. * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
  590. *
  591. * @param array $data Array to be merged
  592. * @param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
  593. * @return array Merged array
  594. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
  595. */
  596. public static function merge(array $data, $merge) {
  597. $args = func_get_args();
  598. $return = current($args);
  599. while (($arg = next($args)) !== false) {
  600. foreach ((array)$arg as $key => $val) {
  601. if (!empty($return[$key]) && is_array($return[$key]) && is_array($val)) {
  602. $return[$key] = self::merge($return[$key], $val);
  603. } elseif (is_int($key) && isset($return[$key])) {
  604. $return[] = $val;
  605. } else {
  606. $return[$key] = $val;
  607. }
  608. }
  609. }
  610. return $return;
  611. }
  612. /**
  613. * Checks to see if all the values in the array are numeric
  614. *
  615. * @param array $array The array to check.
  616. * @return boolean true if values are numeric, false otherwise
  617. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::numeric
  618. */
  619. public static function numeric(array $data) {
  620. if (empty($data)) {
  621. return false;
  622. }
  623. return $data === array_filter($data, 'is_numeric');
  624. }
  625. /**
  626. * Counts the dimensions of an array.
  627. * Only considers the dimension of the first element in the array.
  628. *
  629. * If you have an un-even or heterogenous array, consider using Hash::maxDimensions()
  630. * to get the dimensions of the array.
  631. *
  632. * @param array $array Array to count dimensions on
  633. * @return integer The number of dimensions in $data
  634. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::dimensions
  635. */
  636. public static function dimensions(array $data) {
  637. if (empty($data)) {
  638. return 0;
  639. }
  640. reset($data);
  641. $depth = 1;
  642. while ($elem = array_shift($data)) {
  643. if (is_array($elem)) {
  644. $depth += 1;
  645. $data =& $elem;
  646. } else {
  647. break;
  648. }
  649. }
  650. return $depth;
  651. }
  652. /**
  653. * Counts the dimensions of *all* array elements. Useful for finding the maximum
  654. * number of dimensions in a mixed array.
  655. *
  656. * @param array $data Array to count dimensions on
  657. * @return integer The maximum number of dimensions in $data
  658. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::maxDimensions
  659. */
  660. public static function maxDimensions(array $data) {
  661. $depth = array();
  662. if (is_array($data) && reset($data) !== false) {
  663. foreach ($data as $value) {
  664. $depth[] = self::dimensions((array)$value) + 1;
  665. }
  666. }
  667. return max($depth);
  668. }
  669. /**
  670. * Map a callback across all elements in a set.
  671. * Can be provided a path to only modify slices of the set.
  672. *
  673. * @param array $data The data to map over, and extract data out of.
  674. * @param string $path The path to extract for mapping over.
  675. * @param callable $function The function to call on each extracted value.
  676. * @return array An array of the modified values.
  677. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::map
  678. */
  679. public static function map(array $data, $path, $function) {
  680. $values = (array)self::extract($data, $path);
  681. return array_map($function, $values);
  682. }
  683. /**
  684. * Reduce a set of extracted values using `$function`.
  685. *
  686. * @param array $data The data to reduce.
  687. * @param string $path The path to extract from $data.
  688. * @param callable $function The function to call on each extracted value.
  689. * @return mixed The reduced value.
  690. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::reduce
  691. */
  692. public static function reduce(array $data, $path, $function) {
  693. $values = (array)self::extract($data, $path);
  694. return array_reduce($values, $function);
  695. }
  696. /**
  697. * Apply a callback to a set of extracted values using `$function`.
  698. * The function will get the extracted values as the first argument.
  699. *
  700. * ### Example
  701. *
  702. * You can easily count the results of an extract using apply().
  703. * For example to count the comments on an Article:
  704. *
  705. * `$count = Hash::apply($data, 'Article.Comment.{n}', 'count');`
  706. *
  707. * You could also use a function like `array_sum` to sum the results.
  708. *
  709. * `$total = Hash::apply($data, '{n}.Item.price', 'array_sum');`
  710. *
  711. * @param array $data The data to reduce.
  712. * @param string $path The path to extract from $data.
  713. * @param callable $function The function to call on each extracted value.
  714. * @return mixed The results of the applied method.
  715. */
  716. public static function apply(array $data, $path, $function) {
  717. $values = (array)self::extract($data, $path);
  718. return call_user_func($function, $values);
  719. }
  720. /**
  721. * Sorts an array by any value, determined by a Set-compatible path
  722. *
  723. * ### Sort directions
  724. *
  725. * - `asc` Sort ascending.
  726. * - `desc` Sort descending.
  727. *
  728. * ## Sort types
  729. *
  730. * - `regular` For regular sorting (don't change types)
  731. * - `numeric` Compare values numerically
  732. * - `string` Compare values as strings
  733. * - `natural` Compare items as strings using "natural ordering" in a human friendly way.
  734. * Will sort foo10 below foo2 as an example. Requires PHP 5.4 or greater or it will fallback to 'regular'
  735. *
  736. * @param array $data An array of data to sort
  737. * @param string $path A Set-compatible path to the array value
  738. * @param string $dir See directions above.
  739. * @param string $type See direction types above. Defaults to 'regular'.
  740. * @return array Sorted array of data
  741. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::sort
  742. */
  743. public static function sort(array $data, $path, $dir, $type = 'regular') {
  744. if (empty($data)) {
  745. return array();
  746. }
  747. $originalKeys = array_keys($data);
  748. $numeric = is_numeric(implode('', $originalKeys));
  749. if ($numeric) {
  750. $data = array_values($data);
  751. }
  752. $sortValues = self::extract($data, $path);
  753. $sortCount = count($sortValues);
  754. $dataCount = count($data);
  755. // Make sortValues match the data length, as some keys could be missing
  756. // the sorted value path.
  757. if ($sortCount < $dataCount) {
  758. $sortValues = array_pad($sortValues, $dataCount, null);
  759. }
  760. $result = self::_squash($sortValues);
  761. $keys = self::extract($result, '{n}.id');
  762. $values = self::extract($result, '{n}.value');
  763. $dir = strtolower($dir);
  764. $type = strtolower($type);
  765. if ($type === 'natural' && version_compare(PHP_VERSION, '5.4.0', '<')) {
  766. $type = 'regular';
  767. }
  768. if ($dir === 'asc') {
  769. $dir = SORT_ASC;
  770. } else {
  771. $dir = SORT_DESC;
  772. }
  773. if ($type === 'numeric') {
  774. $type = SORT_NUMERIC;
  775. } elseif ($type === 'string') {
  776. $type = SORT_STRING;
  777. } elseif ($type === 'natural') {
  778. $type = SORT_NATURAL;
  779. } else {
  780. $type = SORT_REGULAR;
  781. }
  782. array_multisort($values, $dir, $type, $keys, $dir, $type);
  783. $sorted = array();
  784. $keys = array_unique($keys);
  785. foreach ($keys as $k) {
  786. if ($numeric) {
  787. $sorted[] = $data[$k];
  788. continue;
  789. }
  790. if (isset($originalKeys[$k])) {
  791. $sorted[$originalKeys[$k]] = $data[$originalKeys[$k]];
  792. } else {
  793. $sorted[$k] = $data[$k];
  794. }
  795. }
  796. return $sorted;
  797. }
  798. /**
  799. * Helper method for sort()
  800. * Squashes an array to a single hash so it can be sorted.
  801. *
  802. * @param array $data The data to squash.
  803. * @param string $key The key for the data.
  804. * @return array
  805. */
  806. protected static function _squash($data, $key = null) {
  807. $stack = array();
  808. foreach ($data as $k => $r) {
  809. $id = $k;
  810. if ($key !== null) {
  811. $id = $key;
  812. }
  813. if (is_array($r) && !empty($r)) {
  814. $stack = array_merge($stack, self::_squash($r, $id));
  815. } else {
  816. $stack[] = array('id' => $id, 'value' => $r);
  817. }
  818. }
  819. return $stack;
  820. }
  821. /**
  822. * Computes the difference between two complex arrays.
  823. * This method differs from the built-in array_diff() in that it will preserve keys
  824. * and work on multi-dimensional arrays.
  825. *
  826. * @param array $data First value
  827. * @param array $compare Second value
  828. * @return array Returns the key => value pairs that are not common in $data and $compare
  829. * The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
  830. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::diff
  831. */
  832. public static function diff(array $data, $compare) {
  833. if (empty($data)) {
  834. return (array)$compare;
  835. }
  836. if (empty($compare)) {
  837. return (array)$data;
  838. }
  839. $intersection = array_intersect_key($data, $compare);
  840. while (($key = key($intersection)) !== null) {
  841. if ($data[$key] == $compare[$key]) {
  842. unset($data[$key]);
  843. unset($compare[$key]);
  844. }
  845. next($intersection);
  846. }
  847. return $data + $compare;
  848. }
  849. /**
  850. * Merges the difference between $data and $compare onto $data.
  851. *
  852. * @param array $data The data to append onto.
  853. * @param array $compare The data to compare and append onto.
  854. * @return array The merged array.
  855. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::mergeDiff
  856. */
  857. public static function mergeDiff(array $data, $compare) {
  858. if (empty($data) && !empty($compare)) {
  859. return $compare;
  860. }
  861. if (empty($compare)) {
  862. return $data;
  863. }
  864. foreach ($compare as $key => $value) {
  865. if (!array_key_exists($key, $data)) {
  866. $data[$key] = $value;
  867. } elseif (is_array($value)) {
  868. $data[$key] = self::mergeDiff($data[$key], $compare[$key]);
  869. }
  870. }
  871. return $data;
  872. }
  873. /**
  874. * Normalizes an array, and converts it to a standard format.
  875. *
  876. * @param array $data List to normalize
  877. * @param boolean $assoc If true, $data will be converted to an associative array.
  878. * @return array
  879. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::normalize
  880. */
  881. public static function normalize(array $data, $assoc = true) {
  882. $keys = array_keys($data);
  883. $count = count($keys);
  884. $numeric = true;
  885. if (!$assoc) {
  886. for ($i = 0; $i < $count; $i++) {
  887. if (!is_int($keys[$i])) {
  888. $numeric = false;
  889. break;
  890. }
  891. }
  892. }
  893. if (!$numeric || $assoc) {
  894. $newList = array();
  895. for ($i = 0; $i < $count; $i++) {
  896. if (is_int($keys[$i])) {
  897. $newList[$data[$keys[$i]]] = null;
  898. } else {
  899. $newList[$keys[$i]] = $data[$keys[$i]];
  900. }
  901. }
  902. $data = $newList;
  903. }
  904. return $data;
  905. }
  906. /**
  907. * Takes in a flat array and returns a nested array
  908. *
  909. * ### Options:
  910. *
  911. * - `children` The key name to use in the resultset for children.
  912. * - `idPath` The path to a key that identifies each entry. Should be
  913. * compatible with Hash::extract(). Defaults to `{n}.$alias.id`
  914. * - `parentPath` The path to a key that identifies the parent of each entry.
  915. * Should be compatible with Hash::extract(). Defaults to `{n}.$alias.parent_id`
  916. * - `root` The id of the desired top-most result.
  917. *
  918. * @param array $data The data to nest.
  919. * @param array $options Options are:
  920. * @return array of results, nested
  921. * @see Hash::extract()
  922. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::nest
  923. */
  924. public static function nest(array $data, $options = array()) {
  925. if (!$data) {
  926. return $data;
  927. }
  928. $alias = key(current($data));
  929. $options += array(
  930. 'idPath' => "{n}.$alias.id",
  931. 'parentPath' => "{n}.$alias.parent_id",
  932. 'children' => 'children',
  933. 'root' => null
  934. );
  935. $return = $idMap = array();
  936. $ids = self::extract($data, $options['idPath']);
  937. $idKeys = explode('.', $options['idPath']);
  938. array_shift($idKeys);
  939. $parentKeys = explode('.', $options['parentPath']);
  940. array_shift($parentKeys);
  941. foreach ($data as $result) {
  942. $result[$options['children']] = array();
  943. $id = self::get($result, $idKeys);
  944. $parentId = self::get($result, $parentKeys);
  945. if (isset($idMap[$id][$options['children']])) {
  946. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  947. } else {
  948. $idMap[$id] = array_merge($result, array($options['children'] => array()));
  949. }
  950. if (!$parentId || !in_array($parentId, $ids)) {
  951. $return[] =& $idMap[$id];
  952. } else {
  953. $idMap[$parentId][$options['children']][] =& $idMap[$id];
  954. }
  955. }
  956. if ($options['root']) {
  957. $root = $options['root'];
  958. } elseif (!$return) {
  959. return array();
  960. } else {
  961. $root = self::get($return[0], $parentKeys);
  962. }
  963. foreach ($return as $i => $result) {
  964. $id = self::get($result, $idKeys);
  965. $parentId = self::get($result, $parentKeys);
  966. if ($id !== $root && $parentId != $root) {
  967. unset($return[$i]);
  968. }
  969. }
  970. return array_values($return);
  971. }
  972. }