PageRenderTime 30ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/cakephp/utility/Hash.php

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