Hash.php 41 KB

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