Hash.php 31 KB

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