source: Dev/branches/cakephp/cake/libs/set.php @ 126

Last change on this file since 126 was 126, checked in by fpvanagthoven, 14 years ago

Cakephp branch.

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