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