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