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