Hash.php 41 KB

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