comparison cake/libs/set.php @ 0:261e66bd5a0c

hg init
author Shoshi TAMAKI <shoshi@cr.ie.u-ryukyu.ac.jp>
date Sun, 24 Jul 2011 21:08:31 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:261e66bd5a0c
1 <?php
2 /**
3 * Library of array functions for Cake.
4 *
5 * PHP versions 4 and 5
6 *
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
9 *
10 * Licensed under The MIT License
11 * Redistributions of files must retain the above copyright notice.
12 *
13 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link http://cakephp.org CakePHP(tm) Project
15 * @package cake
16 * @subpackage cake.cake.libs
17 * @since CakePHP(tm) v 1.2.0
18 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
19 */
20
21 /**
22 * Class used for manipulation of arrays.
23 *
24 * @package cake
25 * @subpackage cake.cake.libs
26 */
27 class Set {
28
29 /**
30 * This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference
31 * to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge)
32 * but does not do if for keys containing strings (unlike array_merge_recursive).
33 * See the unit test for more information.
34 *
35 * Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
36 *
37 * @param array $arr1 Array to be merged
38 * @param array $arr2 Array to merge with
39 * @return array Merged array
40 * @access public
41 * @static
42 */
43 function merge($arr1, $arr2 = null) {
44 $args = func_get_args();
45
46 $r = (array)current($args);
47 while (($arg = next($args)) !== false) {
48 foreach ((array)$arg as $key => $val) {
49 if (is_array($val) && isset($r[$key]) && is_array($r[$key])) {
50 $r[$key] = Set::merge($r[$key], $val);
51 } elseif (is_int($key)) {
52 $r[] = $val;
53 } else {
54 $r[$key] = $val;
55 }
56 }
57 }
58 return $r;
59 }
60
61 /**
62 * Filters empty elements out of a route array, excluding '0'.
63 *
64 * @param mixed $var Either an array to filter, or value when in callback
65 * @param boolean $isArray Force to tell $var is an array when $var is empty
66 * @return mixed Either filtered array, or true/false when in callback
67 * @access public
68 * @static
69 */
70 function filter($var, $isArray = false) {
71 if (is_array($var) && (!empty($var) || $isArray)) {
72 return array_filter($var, array('Set', 'filter'));
73 }
74
75 if ($var === 0 || $var === '0' || !empty($var)) {
76 return true;
77 }
78 return false;
79 }
80
81 /**
82 * Pushes the differences in $array2 onto the end of $array
83 *
84 * @param mixed $array Original array
85 * @param mixed $array2 Differences to push
86 * @return array Combined array
87 * @access public
88 * @static
89 */
90 function pushDiff($array, $array2) {
91 if (empty($array) && !empty($array2)) {
92 return $array2;
93 }
94 if (!empty($array) && !empty($array2)) {
95 foreach ($array2 as $key => $value) {
96 if (!array_key_exists($key, $array)) {
97 $array[$key] = $value;
98 } else {
99 if (is_array($value)) {
100 $array[$key] = Set::pushDiff($array[$key], $array2[$key]);
101 }
102 }
103 }
104 }
105 return $array;
106 }
107
108 /**
109 * Maps the contents of the Set object to an object hierarchy.
110 * Maintains numeric keys as arrays of objects
111 *
112 * @param string $class A class name of the type of object to map to
113 * @param string $tmp A temporary class name used as $class if $class is an array
114 * @return object Hierarchical object
115 * @access public
116 * @static
117 */
118 function map($class = 'stdClass', $tmp = 'stdClass') {
119 if (is_array($class)) {
120 $val = $class;
121 $class = $tmp;
122 }
123
124 if (empty($val)) {
125 return null;
126 }
127 return Set::__map($val, $class);
128 }
129
130 /**
131 * Get the array value of $array. If $array is null, it will return
132 * the current array Set holds. If it is an object of type Set, it
133 * will return its value. If it is another object, its object variables.
134 * If it is anything else but an array, it will return an array whose first
135 * element is $array.
136 *
137 * @param mixed $array Data from where to get the array.
138 * @return array Array from $array.
139 * @access private
140 */
141 function __array($array) {
142 if (empty($array)) {
143 $array = array();
144 } elseif (is_object($array)) {
145 $array = get_object_vars($array);
146 } elseif (!is_array($array)) {
147 $array = array($array);
148 }
149 return $array;
150 }
151
152 /**
153 * Maps the given value as an object. If $value is an object,
154 * it returns $value. Otherwise it maps $value as an object of
155 * type $class, and if primary assign _name_ $key on first array.
156 * If $value is not empty, it will be used to set properties of
157 * returned object (recursively). If $key is numeric will maintain array
158 * structure
159 *
160 * @param mixed $value Value to map
161 * @param string $class Class name
162 * @param boolean $primary whether to assign first array key as the _name_
163 * @return mixed Mapped object
164 * @access private
165 * @static
166 */
167 function __map(&$array, $class, $primary = false) {
168 if ($class === true) {
169 $out = new stdClass;
170 } else {
171 $out = new $class;
172 }
173 if (is_array($array)) {
174 $keys = array_keys($array);
175 foreach ($array as $key => $value) {
176 if ($keys[0] === $key && $class !== true) {
177 $primary = true;
178 }
179 if (is_numeric($key)) {
180 if (is_object($out)) {
181 $out = get_object_vars($out);
182 }
183 $out[$key] = Set::__map($value, $class);
184 if (is_object($out[$key])) {
185 if ($primary !== true && is_array($value) && Set::countDim($value, true) === 2) {
186 if (!isset($out[$key]->_name_)) {
187 $out[$key]->_name_ = $primary;
188 }
189 }
190 }
191 } elseif (is_array($value)) {
192 if ($primary === true) {
193 if (!isset($out->_name_)) {
194 $out->_name_ = $key;
195 }
196 $primary = false;
197 foreach ($value as $key2 => $value2) {
198 $out->{$key2} = Set::__map($value2, true);
199 }
200 } else {
201 if (!is_numeric($key)) {
202 $out->{$key} = Set::__map($value, true, $key);
203 if (is_object($out->{$key}) && !is_numeric($key)) {
204 if (!isset($out->{$key}->_name_)) {
205 $out->{$key}->_name_ = $key;
206 }
207 }
208 } else {
209 $out->{$key} = Set::__map($value, true);
210 }
211 }
212 } else {
213 $out->{$key} = $value;
214 }
215 }
216 } else {
217 $out = $array;
218 }
219 return $out;
220 }
221
222 /**
223 * Checks to see if all the values in the array are numeric
224 *
225 * @param array $array The array to check. If null, the value of the current Set object
226 * @return boolean true if values are numeric, false otherwise
227 * @access public
228 * @static
229 */
230 function numeric($array = null) {
231 if (empty($array)) {
232 return null;
233 }
234
235 if ($array === range(0, count($array) - 1)) {
236 return true;
237 }
238
239 $numeric = true;
240 $keys = array_keys($array);
241 $count = count($keys);
242
243 for ($i = 0; $i < $count; $i++) {
244 if (!is_numeric($array[$keys[$i]])) {
245 $numeric = false;
246 break;
247 }
248 }
249 return $numeric;
250 }
251
252 /**
253 * Return a value from an array list if the key exists.
254 *
255 * If a comma separated $list is passed arrays are numeric with the key of the first being 0
256 * $list = 'no, yes' would translate to $list = array(0 => 'no', 1 => 'yes');
257 *
258 * If an array is used, keys can be strings example: array('no' => 0, 'yes' => 1);
259 *
260 * $list defaults to 0 = no 1 = yes if param is not passed
261 *
262 * @param mixed $select Key in $list to return
263 * @param mixed $list can be an array or a comma-separated list.
264 * @return string the value of the array key or null if no match
265 * @access public
266 * @static
267 */
268 function enum($select, $list = null) {
269 if (empty($list)) {
270 $list = array('no', 'yes');
271 }
272
273 $return = null;
274 $list = Set::normalize($list, false);
275
276 if (array_key_exists($select, $list)) {
277 $return = $list[$select];
278 }
279 return $return;
280 }
281
282 /**
283 * Returns a series of values extracted from an array, formatted in a format string.
284 *
285 * @param array $data Source array from which to extract the data
286 * @param string $format Format string into which values will be inserted, see sprintf()
287 * @param array $keys An array containing one or more Set::extract()-style key paths
288 * @return array An array of strings extracted from $keys and formatted with $format
289 * @access public
290 * @static
291 */
292 function format($data, $format, $keys) {
293
294 $extracted = array();
295 $count = count($keys);
296
297 if (!$count) {
298 return;
299 }
300
301 for ($i = 0; $i < $count; $i++) {
302 $extracted[] = Set::extract($data, $keys[$i]);
303 }
304 $out = array();
305 $data = $extracted;
306 $count = count($data[0]);
307
308 if (preg_match_all('/\{([0-9]+)\}/msi', $format, $keys2) && isset($keys2[1])) {
309 $keys = $keys2[1];
310 $format = preg_split('/\{([0-9]+)\}/msi', $format);
311 $count2 = count($format);
312
313 for ($j = 0; $j < $count; $j++) {
314 $formatted = '';
315 for ($i = 0; $i <= $count2; $i++) {
316 if (isset($format[$i])) {
317 $formatted .= $format[$i];
318 }
319 if (isset($keys[$i]) && isset($data[$keys[$i]][$j])) {
320 $formatted .= $data[$keys[$i]][$j];
321 }
322 }
323 $out[] = $formatted;
324 }
325 } else {
326 $count2 = count($data);
327 for ($j = 0; $j < $count; $j++) {
328 $args = array();
329 for ($i = 0; $i < $count2; $i++) {
330 if (isset($data[$i][$j])) {
331 $args[] = $data[$i][$j];
332 }
333 }
334 $out[] = vsprintf($format, $args);
335 }
336 }
337 return $out;
338 }
339
340 /**
341 * Implements partial support for XPath 2.0. If $path is an array or $data is empty it the call
342 * is delegated to Set::classicExtract.
343 *
344 * #### Currently implemented selectors:
345 *
346 * - /User/id (similar to the classic {n}.User.id)
347 * - /User[2]/name (selects the name of the second User)
348 * - /User[id>2] (selects all Users with an id > 2)
349 * - /User[id>2][<5] (selects all Users with an id > 2 but < 5)
350 * - /Post/Comment[author_name=john]/../name (Selects the name of all Posts that have at least one Comment written by john)
351 * - /Posts[name] (Selects all Posts that have a 'name' key)
352 * - /Comment/.[1] (Selects the contents of the first comment)
353 * - /Comment/.[:last] (Selects the last comment)
354 * - /Comment/.[:first] (Selects the first comment)
355 * - /Comment[text=/cakephp/i] (Selects the all comments that have a text matching the regex /cakephp/i)
356 * - /Comment/@* (Selects the all key names of all comments)
357 *
358 * #### Other limitations:
359 *
360 * - Only absolute paths starting with a single '/' are supported right now
361 *
362 * **Warning**: Even so it has plenty of unit tests the XPath support has not gone through a lot of
363 * real-world testing. Please report Bugs as you find them. Suggestions for additional features to
364 * implement are also very welcome!
365 *
366 * @param string $path An absolute XPath 2.0 path
367 * @param array $data An array of data to extract from
368 * @param array $options Currently only supports 'flatten' which can be disabled for higher XPath-ness
369 * @return array An array of matched items
370 * @access public
371 * @static
372 */
373 function extract($path, $data = null, $options = array()) {
374 if (is_string($data)) {
375 $tmp = $data;
376 $data = $path;
377 $path = $tmp;
378 }
379 if (strpos($path, '/') === false) {
380 return Set::classicExtract($data, $path);
381 }
382 if (empty($data)) {
383 return array();
384 }
385 if ($path === '/') {
386 return $data;
387 }
388 $contexts = $data;
389 $options = array_merge(array('flatten' => true), $options);
390 if (!isset($contexts[0])) {
391 $current = current($data);
392 if ((is_array($current) && count($data) < 1) || !is_array($current) || !Set::numeric(array_keys($data))) {
393 $contexts = array($data);
394 }
395 }
396 $tokens = array_slice(preg_split('/(?<!=|\\\\)\/(?![a-z-\s]*\])/', $path), 1);
397
398 do {
399 $token = array_shift($tokens);
400 $conditions = false;
401 if (preg_match_all('/\[([^=]+=\/[^\/]+\/|[^\]]+)\]/', $token, $m)) {
402 $conditions = $m[1];
403 $token = substr($token, 0, strpos($token, '['));
404 }
405 $matches = array();
406 foreach ($contexts as $key => $context) {
407 if (!isset($context['trace'])) {
408 $context = array('trace' => array(null), 'item' => $context, 'key' => $key);
409 }
410 if ($token === '..') {
411 if (count($context['trace']) == 1) {
412 $context['trace'][] = $context['key'];
413 }
414 $parent = implode('/', $context['trace']) . '/.';
415 $context['item'] = Set::extract($parent, $data);
416 $context['key'] = array_pop($context['trace']);
417 if (isset($context['trace'][1]) && $context['trace'][1] > 0) {
418 $context['item'] = $context['item'][0];
419 } elseif (!empty($context['item'][$key])) {
420 $context['item'] = $context['item'][$key];
421 } else {
422 $context['item'] = array_shift($context['item']);
423 }
424 $matches[] = $context;
425 continue;
426 }
427 $match = false;
428 if ($token === '@*' && is_array($context['item'])) {
429 $matches[] = array(
430 'trace' => array_merge($context['trace'], (array)$key),
431 'key' => $key,
432 'item' => array_keys($context['item']),
433 );
434 } elseif (($key === $token || (ctype_digit($token) && $key == $token) || $token === '.')) {
435 $context['trace'][] = $key;
436 $matches[] = array(
437 'trace' => $context['trace'],
438 'key' => $key,
439 'item' => $context['item'],
440 );
441 } elseif (is_array($context['item']) && array_key_exists($token, $context['item'])) {
442 $items = $context['item'][$token];
443 if (!is_array($items)) {
444 $items = array($items);
445 } elseif (!isset($items[0])) {
446 $current = current($items);
447 $currentKey = key($items);
448 if (!is_array($current) || (is_array($current) && count($items) <= 1 && !is_numeric($currentKey))) {
449 $items = array($items);
450 }
451 }
452
453 foreach ($items as $key => $item) {
454 $ctext = array($context['key']);
455 if (!is_numeric($key)) {
456 $ctext[] = $token;
457 $tok = array_shift($tokens);
458 if (isset($items[$tok])) {
459 $ctext[] = $tok;
460 $item = $items[$tok];
461 $matches[] = array(
462 'trace' => array_merge($context['trace'], $ctext),
463 'key' => $tok,
464 'item' => $item,
465 );
466 break;
467 } elseif ($tok !== null) {
468 array_unshift($tokens, $tok);
469 }
470 } else {
471 $key = $token;
472 }
473
474 $matches[] = array(
475 'trace' => array_merge($context['trace'], $ctext),
476 'key' => $key,
477 'item' => $item,
478 );
479 }
480 }
481 }
482 if ($conditions) {
483 foreach ($conditions as $condition) {
484 $filtered = array();
485 $length = count($matches);
486 foreach ($matches as $i => $match) {
487 if (Set::matches(array($condition), $match['item'], $i + 1, $length)) {
488 $filtered[$i] = $match;
489 }
490 }
491 $matches = $filtered;
492 }
493 }
494 $contexts = $matches;
495
496 if (empty($tokens)) {
497 break;
498 }
499 } while(1);
500
501 $r = array();
502
503 foreach ($matches as $match) {
504 if ((!$options['flatten'] || is_array($match['item'])) && !is_int($match['key'])) {
505 $r[] = array($match['key'] => $match['item']);
506 } else {
507 $r[] = $match['item'];
508 }
509 }
510 return $r;
511 }
512
513 /**
514 * This function can be used to see if a single item or a given xpath match certain conditions.
515 *
516 * @param mixed $conditions An array of condition strings or an XPath expression
517 * @param array $data An array of data to execute the match on
518 * @param integer $i Optional: The 'nth'-number of the item being matched.
519 * @return boolean
520 * @access public
521 * @static
522 */
523 function matches($conditions, $data = array(), $i = null, $length = null) {
524 if (empty($conditions)) {
525 return true;
526 }
527 if (is_string($conditions)) {
528 return !!Set::extract($conditions, $data);
529 }
530 foreach ($conditions as $condition) {
531 if ($condition === ':last') {
532 if ($i != $length) {
533 return false;
534 }
535 continue;
536 } elseif ($condition === ':first') {
537 if ($i != 1) {
538 return false;
539 }
540 continue;
541 }
542 if (!preg_match('/(.+?)([><!]?[=]|[><])(.*)/', $condition, $match)) {
543 if (ctype_digit($condition)) {
544 if ($i != $condition) {
545 return false;
546 }
547 } elseif (preg_match_all('/(?:^[0-9]+|(?<=,)[0-9]+)/', $condition, $matches)) {
548 return in_array($i, $matches[0]);
549 } elseif (!array_key_exists($condition, $data)) {
550 return false;
551 }
552 continue;
553 }
554 list(,$key,$op,$expected) = $match;
555 if (!isset($data[$key])) {
556 return false;
557 }
558
559 $val = $data[$key];
560
561 if ($op === '=' && $expected && $expected{0} === '/') {
562 return preg_match($expected, $val);
563 }
564 if ($op === '=' && $val != $expected) {
565 return false;
566 }
567 if ($op === '!=' && $val == $expected) {
568 return false;
569 }
570 if ($op === '>' && $val <= $expected) {
571 return false;
572 }
573 if ($op === '<' && $val >= $expected) {
574 return false;
575 }
576 if ($op === '<=' && $val > $expected) {
577 return false;
578 }
579 if ($op === '>=' && $val < $expected) {
580 return false;
581 }
582 }
583 return true;
584 }
585
586 /**
587 * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.:
588 * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal,
589 * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as
590 * a regular expression.
591 *
592 * @param array $data Array from where to extract
593 * @param mixed $path As an array, or as a dot-separated string.
594 * @return array Extracted data
595 * @access public
596 * @static
597 */
598 function classicExtract($data, $path = null) {
599 if (empty($path)) {
600 return $data;
601 }
602 if (is_object($data)) {
603 $data = get_object_vars($data);
604 }
605 if (!is_array($data)) {
606 return $data;
607 }
608
609 if (!is_array($path)) {
610 if (!class_exists('String')) {
611 App::import('Core', 'String');
612 }
613 $path = String::tokenize($path, '.', '{', '}');
614 }
615 $tmp = array();
616
617 if (!is_array($path) || empty($path)) {
618 return null;
619 }
620
621 foreach ($path as $i => $key) {
622 if (is_numeric($key) && intval($key) > 0 || $key === '0') {
623 if (isset($data[intval($key)])) {
624 $data = $data[intval($key)];
625 } else {
626 return null;
627 }
628 } elseif ($key === '{n}') {
629 foreach ($data as $j => $val) {
630 if (is_int($j)) {
631 $tmpPath = array_slice($path, $i + 1);
632 if (empty($tmpPath)) {
633 $tmp[] = $val;
634 } else {
635 $tmp[] = Set::classicExtract($val, $tmpPath);
636 }
637 }
638 }
639 return $tmp;
640 } elseif ($key === '{s}') {
641 foreach ($data as $j => $val) {
642 if (is_string($j)) {
643 $tmpPath = array_slice($path, $i + 1);
644 if (empty($tmpPath)) {
645 $tmp[] = $val;
646 } else {
647 $tmp[] = Set::classicExtract($val, $tmpPath);
648 }
649 }
650 }
651 return $tmp;
652 } elseif (false !== strpos($key,'{') && false !== strpos($key,'}')) {
653 $pattern = substr($key, 1, -1);
654
655 foreach ($data as $j => $val) {
656 if (preg_match('/^'.$pattern.'/s', $j) !== 0) {
657 $tmpPath = array_slice($path, $i + 1);
658 if (empty($tmpPath)) {
659 $tmp[$j] = $val;
660 } else {
661 $tmp[$j] = Set::classicExtract($val, $tmpPath);
662 }
663 }
664 }
665 return $tmp;
666 } else {
667 if (isset($data[$key])) {
668 $data = $data[$key];
669 } else {
670 return null;
671 }
672 }
673 }
674 return $data;
675 }
676
677 /**
678 * Inserts $data into an array as defined by $path.
679 *
680 * @param mixed $list Where to insert into
681 * @param mixed $path A dot-separated string.
682 * @param array $data Data to insert
683 * @return array
684 * @access public
685 * @static
686 */
687 function insert($list, $path, $data = null) {
688 if (!is_array($path)) {
689 $path = explode('.', $path);
690 }
691 $_list =& $list;
692
693 foreach ($path as $i => $key) {
694 if (is_numeric($key) && intval($key) > 0 || $key === '0') {
695 $key = intval($key);
696 }
697 if ($i === count($path) - 1) {
698 $_list[$key] = $data;
699 } else {
700 if (!isset($_list[$key])) {
701 $_list[$key] = array();
702 }
703 $_list =& $_list[$key];
704 }
705 }
706 return $list;
707 }
708
709 /**
710 * Removes an element from a Set or array as defined by $path.
711 *
712 * @param mixed $list From where to remove
713 * @param mixed $path A dot-separated string.
714 * @return array Array with $path removed from its value
715 * @access public
716 * @static
717 */
718 function remove($list, $path = null) {
719 if (empty($path)) {
720 return $list;
721 }
722 if (!is_array($path)) {
723 $path = explode('.', $path);
724 }
725 $_list =& $list;
726
727 foreach ($path as $i => $key) {
728 if (is_numeric($key) && intval($key) > 0 || $key === '0') {
729 $key = intval($key);
730 }
731 if ($i === count($path) - 1) {
732 unset($_list[$key]);
733 } else {
734 if (!isset($_list[$key])) {
735 return $list;
736 }
737 $_list =& $_list[$key];
738 }
739 }
740 return $list;
741 }
742
743 /**
744 * Checks if a particular path is set in an array
745 *
746 * @param mixed $data Data to check on
747 * @param mixed $path A dot-separated string.
748 * @return boolean true if path is found, false otherwise
749 * @access public
750 * @static
751 */
752 function check($data, $path = null) {
753 if (empty($path)) {
754 return $data;
755 }
756 if (!is_array($path)) {
757 $path = explode('.', $path);
758 }
759
760 foreach ($path as $i => $key) {
761 if (is_numeric($key) && intval($key) > 0 || $key === '0') {
762 $key = intval($key);
763 }
764 if ($i === count($path) - 1) {
765 return (is_array($data) && array_key_exists($key, $data));
766 }
767
768 if (!is_array($data) || !array_key_exists($key, $data)) {
769 return false;
770 }
771 $data =& $data[$key];
772 }
773 return true;
774 }
775
776 /**
777 * Computes the difference between a Set and an array, two Sets, or two arrays
778 *
779 * @param mixed $val1 First value
780 * @param mixed $val2 Second value
781 * @return array Returns the key => value pairs that are not common in $val1 and $val2
782 * The expression for this function is ($val1 - $val2) + ($val2 - ($val1 - $val2))
783 * @access public
784 * @static
785 */
786 function diff($val1, $val2 = null) {
787 if (empty($val1)) {
788 return (array)$val2;
789 }
790 if (empty($val2)) {
791 return (array)$val1;
792 }
793 $intersection = array_intersect_key($val1, $val2);
794 while (($key = key($intersection)) !== null) {
795 if ($val1[$key] == $val2[$key]) {
796 unset($val1[$key]);
797 unset($val2[$key]);
798 }
799 next($intersection);
800 }
801
802 return $val1 + $val2;
803 }
804
805 /**
806 * Determines if one Set or array contains the exact keys and values of another.
807 *
808 * @param array $val1 First value
809 * @param array $val2 Second value
810 * @return boolean true if $val1 contains $val2, false otherwise
811 * @access public
812 * @static
813 */
814 function contains($val1, $val2 = null) {
815 if (empty($val1) || empty($val2)) {
816 return false;
817 }
818
819 foreach ($val2 as $key => $val) {
820 if (is_numeric($key)) {
821 Set::contains($val, $val1);
822 } else {
823 if (!isset($val1[$key]) || $val1[$key] != $val) {
824 return false;
825 }
826 }
827 }
828 return true;
829 }
830
831 /**
832 * Counts the dimensions of an array. If $all is set to false (which is the default) it will
833 * only consider the dimension of the first element in the array.
834 *
835 * @param array $array Array to count dimensions on
836 * @param boolean $all Set to true to count the dimension considering all elements in array
837 * @param integer $count Start the dimension count at this number
838 * @return integer The number of dimensions in $array
839 * @access public
840 * @static
841 */
842 function countDim($array = null, $all = false, $count = 0) {
843 if ($all) {
844 $depth = array($count);
845 if (is_array($array) && reset($array) !== false) {
846 foreach ($array as $value) {
847 $depth[] = Set::countDim($value, true, $count + 1);
848 }
849 }
850 $return = max($depth);
851 } else {
852 if (is_array(reset($array))) {
853 $return = Set::countDim(reset($array)) + 1;
854 } else {
855 $return = 1;
856 }
857 }
858 return $return;
859 }
860
861 /**
862 * Normalizes a string or array list.
863 *
864 * @param mixed $list List to normalize
865 * @param boolean $assoc If true, $list will be converted to an associative array
866 * @param string $sep If $list is a string, it will be split into an array with $sep
867 * @param boolean $trim If true, separated strings will be trimmed
868 * @return array
869 * @access public
870 * @static
871 */
872 function normalize($list, $assoc = true, $sep = ',', $trim = true) {
873 if (is_string($list)) {
874 $list = explode($sep, $list);
875 if ($trim) {
876 foreach ($list as $key => $value) {
877 $list[$key] = trim($value);
878 }
879 }
880 if ($assoc) {
881 return Set::normalize($list);
882 }
883 } elseif (is_array($list)) {
884 $keys = array_keys($list);
885 $count = count($keys);
886 $numeric = true;
887
888 if (!$assoc) {
889 for ($i = 0; $i < $count; $i++) {
890 if (!is_int($keys[$i])) {
891 $numeric = false;
892 break;
893 }
894 }
895 }
896 if (!$numeric || $assoc) {
897 $newList = array();
898 for ($i = 0; $i < $count; $i++) {
899 if (is_int($keys[$i])) {
900 $newList[$list[$keys[$i]]] = null;
901 } else {
902 $newList[$keys[$i]] = $list[$keys[$i]];
903 }
904 }
905 $list = $newList;
906 }
907 }
908 return $list;
909 }
910
911 /**
912 * Creates an associative array using a $path1 as the path to build its keys, and optionally
913 * $path2 as path to get the values. If $path2 is not specified, all values will be initialized
914 * to null (useful for Set::merge). You can optionally group the values by what is obtained when
915 * following the path specified in $groupPath.
916 *
917 * @param mixed $data Array or object from where to extract keys and values
918 * @param mixed $path1 As an array, or as a dot-separated string.
919 * @param mixed $path2 As an array, or as a dot-separated string.
920 * @param string $groupPath As an array, or as a dot-separated string.
921 * @return array Combined array
922 * @access public
923 * @static
924 */
925 function combine($data, $path1 = null, $path2 = null, $groupPath = null) {
926 if (empty($data)) {
927 return array();
928 }
929
930 if (is_object($data)) {
931 $data = get_object_vars($data);
932 }
933
934 if (is_array($path1)) {
935 $format = array_shift($path1);
936 $keys = Set::format($data, $format, $path1);
937 } else {
938 $keys = Set::extract($data, $path1);
939 }
940 if (empty($keys)) {
941 return array();
942 }
943
944 if (!empty($path2) && is_array($path2)) {
945 $format = array_shift($path2);
946 $vals = Set::format($data, $format, $path2);
947
948 } elseif (!empty($path2)) {
949 $vals = Set::extract($data, $path2);
950
951 } else {
952 $count = count($keys);
953 for ($i = 0; $i < $count; $i++) {
954 $vals[$i] = null;
955 }
956 }
957
958 if ($groupPath != null) {
959 $group = Set::extract($data, $groupPath);
960 if (!empty($group)) {
961 $c = count($keys);
962 for ($i = 0; $i < $c; $i++) {
963 if (!isset($group[$i])) {
964 $group[$i] = 0;
965 }
966 if (!isset($out[$group[$i]])) {
967 $out[$group[$i]] = array();
968 }
969 $out[$group[$i]][$keys[$i]] = $vals[$i];
970 }
971 return $out;
972 }
973 }
974 if (empty($vals)) {
975 return array();
976 }
977 return array_combine($keys, $vals);
978 }
979
980 /**
981 * Converts an object into an array.
982 * @param object $object Object to reverse
983 * @return array Array representation of given object
984 * @public
985 * @static
986 */
987 function reverse($object) {
988 $out = array();
989 if (is_a($object, 'XmlNode')) {
990 $out = $object->toArray();
991 return $out;
992 } else if (is_object($object)) {
993 $keys = get_object_vars($object);
994 if (isset($keys['_name_'])) {
995 $identity = $keys['_name_'];
996 unset($keys['_name_']);
997 }
998 $new = array();
999 foreach ($keys as $key => $value) {
1000 if (is_array($value)) {
1001 $new[$key] = (array)Set::reverse($value);
1002 } else {
1003 if (isset($value->_name_)) {
1004 $new = array_merge($new, Set::reverse($value));
1005 } else {
1006 $new[$key] = Set::reverse($value);
1007 }
1008 }
1009 }
1010 if (isset($identity)) {
1011 $out[$identity] = $new;
1012 } else {
1013 $out = $new;
1014 }
1015 } elseif (is_array($object)) {
1016 foreach ($object as $key => $value) {
1017 $out[$key] = Set::reverse($value);
1018 }
1019 } else {
1020 $out = $object;
1021 }
1022 return $out;
1023 }
1024
1025 /**
1026 * Collapses a multi-dimensional array into a single dimension, using a delimited array path for
1027 * each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes
1028 * array('0.Foo.Bar' => 'Far').
1029 *
1030 * @param array $data Array to flatten
1031 * @param string $separator String used to separate array key elements in a path, defaults to '.'
1032 * @return array
1033 * @access public
1034 * @static
1035 */
1036 function flatten($data, $separator = '.') {
1037 $result = array();
1038 $path = null;
1039
1040 if (is_array($separator)) {
1041 extract($separator, EXTR_OVERWRITE);
1042 }
1043
1044 if (!is_null($path)) {
1045 $path .= $separator;
1046 }
1047
1048 foreach ($data as $key => $val) {
1049 if (is_array($val)) {
1050 $result += (array)Set::flatten($val, array(
1051 'separator' => $separator,
1052 'path' => $path . $key
1053 ));
1054 } else {
1055 $result[$path . $key] = $val;
1056 }
1057 }
1058 return $result;
1059 }
1060
1061 /**
1062 * Flattens an array for sorting
1063 *
1064 * @param array $results
1065 * @param string $key
1066 * @return array
1067 * @access private
1068 */
1069 function __flatten($results, $key = null) {
1070 $stack = array();
1071 foreach ($results as $k => $r) {
1072 $id = $k;
1073 if (!is_null($key)) {
1074 $id = $key;
1075 }
1076 if (is_array($r) && !empty($r)) {
1077 $stack = array_merge($stack, Set::__flatten($r, $id));
1078 } else {
1079 $stack[] = array('id' => $id, 'value' => $r);
1080 }
1081 }
1082 return $stack;
1083 }
1084
1085 /**
1086 * Sorts an array by any value, determined by a Set-compatible path
1087 *
1088 * @param array $data An array of data to sort
1089 * @param string $path A Set-compatible path to the array value
1090 * @param string $dir Direction of sorting - either ascending (ASC), or descending (DESC)
1091 * @return array Sorted array of data
1092 * @static
1093 */
1094 function sort($data, $path, $dir) {
1095 $originalKeys = array_keys($data);
1096 if (is_numeric(implode('', $originalKeys))) {
1097 $data = array_values($data);
1098 }
1099 $result = Set::__flatten(Set::extract($data, $path));
1100 list($keys, $values) = array(Set::extract($result, '{n}.id'), Set::extract($result, '{n}.value'));
1101
1102 $dir = strtolower($dir);
1103 if ($dir === 'asc') {
1104 $dir = SORT_ASC;
1105 } elseif ($dir === 'desc') {
1106 $dir = SORT_DESC;
1107 }
1108 array_multisort($values, $dir, $keys, $dir);
1109 $sorted = array();
1110 $keys = array_unique($keys);
1111
1112 foreach ($keys as $k) {
1113 $sorted[] = $data[$k];
1114 }
1115 return $sorted;
1116 }
1117
1118 /**
1119 * Allows the application of a callback method to elements of an
1120 * array extracted by a Set::extract() compatible path.
1121 *
1122 * @param mixed $path Set-compatible path to the array value
1123 * @param array $data An array of data to extract from & then process with the $callback.
1124 * @param mixed $callback Callback method to be applied to extracted data.
1125 * See http://ca2.php.net/manual/en/language.pseudo-types.php#language.types.callback for examples
1126 * of callback formats.
1127 * @param array $options Options are:
1128 * - type : can be pass, map, or reduce. Map will handoff the given callback
1129 * to array_map, reduce will handoff to array_reduce, and pass will
1130 * use call_user_func_array().
1131 * @return mixed Result of the callback when applied to extracted data
1132 * @access public
1133 * @static
1134 */
1135 function apply($path, $data, $callback, $options = array()) {
1136 $defaults = array('type' => 'pass');
1137 $options = array_merge($defaults, $options);
1138
1139 $extracted = Set::extract($path, $data);
1140
1141 if ($options['type'] === 'map') {
1142 $result = array_map($callback, $extracted);
1143
1144 } elseif ($options['type'] === 'reduce') {
1145 $result = array_reduce($extracted, $callback);
1146
1147 } elseif ($options['type'] === 'pass') {
1148 $result = call_user_func_array($callback, array($extracted));
1149 } else {
1150 return null;
1151 }
1152
1153 return $result;
1154 }
1155 }