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