Hash.php 29 KB

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