Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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