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