PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Utility/Hash.php

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