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