PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Utility/Hash.php

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