Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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