Merge pull request #4789 from totten/master-test-tx
[civicrm-core.git] / CRM / Utils / Array.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Provides a collection of static methods for array manipulation.
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 */
34 class CRM_Utils_Array {
35
36 /**
37 * Returns $list[$key] if such element exists, or a default value otherwise.
38 *
39 * If $list is not actually an array at all, then the default value is
40 * returned.
41 *
42 * @access public
43 *
44 * @param string $key
45 * Key value to look up in the array.
46 * @param array $list
47 * Array from which to look up a value.
48 * @param mixed $default
49 * (optional) Value to return $list[$key] does not exist.
50 *
51 * @return mixed
52 * Can return any type, since $list might contain anything.
53 */
54 static function value($key, $list, $default = NULL) {
55 if (is_array($list)) {
56 return array_key_exists($key, $list) ? $list[$key] : $default;
57 }
58 return $default;
59 }
60
61 /**
62 * Recursively searches an array for a key, returning the first value found.
63 *
64 * If $params[$key] does not exist and $params contains arrays, descend into
65 * each array in a depth-first manner, in array iteration order.
66 *
67 * @param array $params
68 * The array to be searched.
69 * @param string $key
70 * The key to search for.
71 *
72 * @return mixed
73 * The value of the key, or null if the key is not found.
74 * @access public
75 */
76 static function retrieveValueRecursive(&$params, $key) {
77 if (!is_array($params)) {
78 return NULL;
79 }
80 elseif ($value = CRM_Utils_Array::value($key, $params)) {
81 return $value;
82 }
83 else {
84 foreach ($params as $subParam) {
85 if (is_array($subParam) &&
86 $value = self::retrieveValueRecursive($subParam, $key)
87 ) {
88 return $value;
89 }
90 }
91 }
92 return NULL;
93 }
94
95 /**
96 * Wraps and slightly changes the behavior of PHP's array_search().
97 *
98 * This function reproduces the behavior of array_search() from PHP prior to
99 * version 4.2.0, which was to return NULL on failure. This function also
100 * checks that $list is an array before attempting to search it.
101 *
102 * @access public
103 *
104 * @param mixed $value
105 * The value to search for.
106 * @param array $list
107 * The array to be searched.
108 *
109 * @return int|string|null
110 * Returns the key, which could be an int or a string, or NULL on failure.
111 */
112 static function key($value, &$list) {
113 if (is_array($list)) {
114 $key = array_search($value, $list);
115
116 // array_search returns key if found, false otherwise
117 // it may return values like 0 or empty string which
118 // evaluates to false
119 // hence we must use identical comparison operator
120 return ($key === FALSE) ? NULL : $key;
121 }
122 return NULL;
123 }
124
125 /**
126 * Builds an XML fragment representing an array.
127 *
128 * Depending on the nature of the keys of the array (and its sub-arrays,
129 * if any) the XML fragment may not be valid.
130 *
131 * @param array $list
132 * The array to be serialized.
133 * @param int $depth
134 * (optional) Indentation depth counter.
135 * @param string $seperator
136 * (optional) String to be appended after open/close tags.
137 *
138 * @access public
139 *
140 * @return string
141 * XML fragment representing $list.
142 */
143 static function &xml(&$list, $depth = 1, $seperator = "\n") {
144 $xml = '';
145 foreach ($list as $name => $value) {
146 $xml .= str_repeat(' ', $depth * 4);
147 if (is_array($value)) {
148 $xml .= "<{$name}>{$seperator}";
149 $xml .= self::xml($value, $depth + 1, $seperator);
150 $xml .= str_repeat(' ', $depth * 4);
151 $xml .= "</{$name}>{$seperator}";
152 }
153 else {
154 // make sure we escape value
155 $value = self::escapeXML($value);
156 $xml .= "<{$name}>$value</{$name}>{$seperator}";
157 }
158 }
159 return $xml;
160 }
161
162 /**
163 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
164 *
165 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
166 * with a comma.
167 *
168 * @param string $value
169 * String to be sanitized.
170 *
171 * @return string
172 * Sanitized version of $value.
173 */
174 static function escapeXML($value) {
175 static $src = NULL;
176 static $dst = NULL;
177
178 if (!$src) {
179 $src = array('&', '<', '>', '\ 1');
180 $dst = array('&amp;', '&lt;', '&gt;', ',');
181 }
182
183 return str_replace($src, $dst, $value);
184 }
185
186 /**
187 * Converts a nested array to a flat array.
188 *
189 * The nested structure is preserved in the string values of the keys of the
190 * flat array.
191 *
192 * Example nested array:
193 * Array
194 * (
195 * [foo] => Array
196 * (
197 * [0] => bar
198 * [1] => baz
199 * [2] => 42
200 * )
201 *
202 * [asdf] => Array
203 * (
204 * [merp] => bleep
205 * [quack] => Array
206 * (
207 * [0] => 1
208 * [1] => 2
209 * [2] => 3
210 * )
211 *
212 * )
213 *
214 * [quux] => 999
215 * )
216 *
217 * Corresponding flattened array:
218 * Array
219 * (
220 * [foo.0] => bar
221 * [foo.1] => baz
222 * [foo.2] => 42
223 * [asdf.merp] => bleep
224 * [asdf.quack.0] => 1
225 * [asdf.quack.1] => 2
226 * [asdf.quack.2] => 3
227 * [quux] => 999
228 * )
229 *
230 * @param array $list
231 * Array to be flattened.
232 * @param array $flat
233 * Destination array.
234 * @param string $prefix
235 * (optional) String to prepend to keys.
236 * @param string $seperator
237 * (optional) String that separates the concatenated keys.
238 *
239 * @access public
240 */
241 static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
242 foreach ($list as $name => $value) {
243 $newPrefix = ($prefix) ? $prefix . $seperator . $name : $name;
244 if (is_array($value)) {
245 self::flatten($value, $flat, $newPrefix, $seperator);
246 }
247 else {
248 if (!empty($value)) {
249 $flat[$newPrefix] = $value;
250 }
251 }
252 }
253 }
254
255 /**
256 * Converts an array with path-like keys into a tree of arrays.
257 *
258 * This function is the inverse of CRM_Utils_Array::flatten().
259 *
260 * @param string $delim
261 * A path delimiter
262 * @param array $arr
263 * A one-dimensional array indexed by string keys
264 *
265 * @return array
266 * Array-encoded tree
267 *
268 * @access public
269 */
270 function unflatten($delim, &$arr) {
271 $result = array();
272 foreach ($arr as $key => $value) {
273 $path = explode($delim, $key);
274 $node = &$result;
275 while (count($path) > 1) {
276 $key = array_shift($path);
277 if (!isset($node[$key])) {
278 $node[$key] = array();
279 }
280 $node = &$node[$key];
281 }
282 // last part of path
283 $key = array_shift($path);
284 $node[$key] = $value;
285 }
286 return $result;
287 }
288
289 /**
290 * Merges two arrays.
291 *
292 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
293 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
294 * exist but they are not both arrays, the value from $a1 overrides the
295 * value from $a2 and the value from $a2 is discarded.
296 *
297 * @param array $a1
298 * First array to be merged.
299 * @param array $a2
300 * Second array to be merged.
301 *
302 * @return array
303 * The merged array.
304 * @access public
305 */
306 static function crmArrayMerge($a1, $a2) {
307 if (empty($a1)) {
308 return $a2;
309 }
310
311 if (empty($a2)) {
312 return $a1;
313 }
314
315 $a3 = array();
316 foreach ($a1 as $key => $value) {
317 if (array_key_exists($key, $a2) &&
318 is_array($a2[$key]) && is_array($a1[$key])
319 ) {
320 $a3[$key] = array_merge($a1[$key], $a2[$key]);
321 }
322 else {
323 $a3[$key] = $a1[$key];
324 }
325 }
326
327 foreach ($a2 as $key => $value) {
328 if (array_key_exists($key, $a1)) {
329 // already handled in above loop
330 continue;
331 }
332 $a3[$key] = $a2[$key];
333 }
334
335 return $a3;
336 }
337
338 /**
339 * Determines whether an array contains any sub-arrays.
340 *
341 * @param array $list
342 * The array to inspect.
343 *
344 * @return bool
345 * True if $list contains at least one sub-array, false otherwise.
346 * @access public
347 */
348 static function isHierarchical(&$list) {
349 foreach ($list as $n => $v) {
350 if (is_array($v)) {
351 return TRUE;
352 }
353 }
354 return FALSE;
355 }
356
357 /**
358 * @param $subset
359 * @param $superset
360 * @return bool TRUE if $subset is a subset of $superset
361 */
362 static function isSubset($subset, $superset) {
363 foreach ($subset as $expected) {
364 if (!in_array($expected, $superset)) {
365 return FALSE;
366 }
367 }
368 return TRUE;
369 }
370
371 /**
372 * Searches an array recursively in an optionally case-insensitive manner.
373 *
374 * @param string $value
375 * Value to search for.
376 * @param array $params
377 * Array to search within.
378 * @param bool $caseInsensitive
379 * (optional) Whether to search in a case-insensitive manner.
380 *
381 * @return bool
382 * True if $value was found, false otherwise.
383 *
384 * @access public
385 */
386 static function crmInArray($value, $params, $caseInsensitive = TRUE) {
387 foreach ($params as $item) {
388 if (is_array($item)) {
389 $ret = crmInArray($value, $item, $caseInsensitive);
390 }
391 else {
392 $ret = ($caseInsensitive) ? strtolower($item) == strtolower($value) : $item == $value;
393 if ($ret) {
394 return $ret;
395 }
396 }
397 }
398 return FALSE;
399 }
400
401 /**
402 * This function is used to convert associative array names to values
403 * and vice-versa.
404 *
405 * This function is used by both the web form layer and the api. Note that
406 * the api needs the name => value conversion, also the view layer typically
407 * requires value => name conversion
408 */
409 static function lookupValue(&$defaults, $property, $lookup, $reverse) {
410 $id = $property . '_id';
411
412 $src = $reverse ? $property : $id;
413 $dst = $reverse ? $id : $property;
414
415 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER))) {
416 return FALSE;
417 }
418
419 $look = $reverse ? array_flip($lookup) : $lookup;
420
421 //trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
422 $newLook = array();
423 foreach ($look as $k => $v) {
424 $newLook[trim($k, ".")] = $v;
425 }
426
427 $look = $newLook;
428
429 if (is_array($look)) {
430 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER))) {
431 return FALSE;
432 }
433 }
434
435 $tempLook = array_change_key_case($look, CASE_LOWER);
436
437 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
438 return TRUE;
439 }
440
441 /**
442 * Checks whether an array is empty.
443 *
444 * An array is empty if its values consist only of NULL and empty sub-arrays.
445 * Containing a non-NULL value or non-empty array makes an array non-empty.
446 *
447 * If something other than an array is passed, it is considered to be empty.
448 *
449 * If nothing is passed at all, the default value provided is empty.
450 *
451 * @param array $array
452 * (optional) Array to be checked for emptiness.
453 *
454 * @return boolean
455 * True if the array is empty.
456 * @access public
457 */
458 static function crmIsEmptyArray($array = array()) {
459 if (!is_array($array)) {
460 return TRUE;
461 }
462 foreach ($array as $element) {
463 if (is_array($element)) {
464 if (!self::crmIsEmptyArray($element)) {
465 return FALSE;
466 }
467 }
468 elseif (isset($element)) {
469 return FALSE;
470 }
471 }
472 return TRUE;
473 }
474
475 /**
476 * Sorts an associative array of arrays by an attribute using strnatcmp().
477 *
478 * @param array $array
479 * Array to be sorted.
480 * @param string $field
481 * Name of the attribute used for sorting.
482 *
483 * @return array
484 * Sorted array
485 */
486 static function crmArraySortByField($array, $field) {
487 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
488 uasort($array, create_function('$a,$b', $code));
489 return $array;
490 }
491
492 /**
493 * Recursively removes duplicate values from a multi-dimensional array.
494 *
495 * @param array $array
496 * The input array possibly containing duplicate values.
497 *
498 * @return array
499 * The input array with duplicate values removed.
500 */
501 static function crmArrayUnique($array) {
502 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
503 foreach ($result as $key => $value) {
504 if (is_array($value)) {
505 $result[$key] = self::crmArrayUnique($value);
506 }
507 }
508 return $result;
509 }
510
511 /**
512 * Sorts an array and maintains index association (with localization).
513 *
514 * Uses Collate from the PECL "intl" package, if available, for UTF-8
515 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
516 *
517 * On Debian/Ubuntu: apt-get install php5-intl
518 *
519 * @param array $array
520 * (optional) Array to be sorted.
521 *
522 * @return array
523 * Sorted array.
524 */
525 static function asort($array = array()) {
526 $lcMessages = CRM_Utils_System::getUFLocale();
527
528 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
529 $collator = new Collator($lcMessages . '.utf8');
530 $collator->asort($array);
531 }
532 else {
533 // This calls PHP's built-in asort().
534 asort($array);
535 }
536
537 return $array;
538 }
539
540 /**
541 * Unsets an arbitrary list of array elements from an associative array.
542 *
543 * @param array $items
544 * The array from which to remove items.
545 *
546 * @internal param string|\string[] $key When passed a string, unsets $items[$key].* When passed a string, unsets $items[$key].
547 * When passed an array of strings, unsets $items[$k] for each string $k
548 * in the array.
549 */
550 static function remove(&$items) {
551 foreach (func_get_args() as $n => $key) {
552 // Skip argument 0 ($items) by testing $n for truth.
553 if ($n && is_array($key)) {
554 foreach($key as $k) {
555 unset($items[$k]);
556 }
557 }
558 elseif ($n) {
559 unset($items[$key]);
560 }
561 }
562 }
563
564 /**
565 * Builds an array-tree which indexes the records in an array.
566 *
567 * @param string[] $keys
568 * Properties by which to index.
569 * @param object|array $records
570 *
571 * @return array
572 * Multi-dimensional array, with one layer for each key.
573 */
574 static function index($keys, $records) {
575 $final_key = array_pop($keys);
576
577 $result = array();
578 foreach ($records as $record) {
579 $node = &$result;
580 foreach ($keys as $key) {
581 if (is_array($record)) {
582 $keyvalue = isset($record[$key]) ? $record[$key] : NULL;
583 } else {
584 $keyvalue = isset($record->{$key}) ? $record->{$key} : NULL;
585 }
586 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
587 $node[$keyvalue] = array();
588 }
589 $node = &$node[$keyvalue];
590 }
591 if (is_array($record)) {
592 $node[ $record[$final_key] ] = $record;
593 } else {
594 $node[ $record->{$final_key} ] = $record;
595 }
596 }
597 return $result;
598 }
599
600 /**
601 * Iterates over a list of records and returns the value of some property.
602 *
603 * @param string $prop
604 * Property to retrieve.
605 * @param array|object $records
606 * A list of records.
607 *
608 * @return array
609 * Keys are the original keys of $records; values are the $prop values.
610 */
611 static function collect($prop, $records) {
612 $result = array();
613 if (is_array($records)) {
614 foreach ($records as $key => $record) {
615 if (is_object($record)) {
616 $result[$key] = $record->{$prop};
617 } else {
618 $result[$key] = $record[$prop];
619 }
620 }
621 }
622 return $result;
623 }
624
625 /**
626 * Trims delimiters from a string and then splits it using explode().
627 *
628 * This method works mostly like PHP's built-in explode(), except that
629 * surrounding delimiters are trimmed before explode() is called.
630 *
631 * Also, if an array or NULL is passed as the $values parameter, the value is
632 * returned unmodified rather than being passed to explode().
633 *
634 * @param array|null|string $values
635 * The input string (or an array, or NULL).
636 * @param string $delim
637 * (optional) The boundary string.
638 *
639 * @return array|null
640 * An array of strings produced by explode(), or the unmodified input
641 * array, or NULL.
642 */
643 static function explodePadded($values, $delim = CRM_Core_DAO::VALUE_SEPARATOR) {
644 if ($values === NULL) {
645 return NULL;
646 }
647 // If we already have an array, no need to continue
648 if (is_array($values)) {
649 return $values;
650 }
651 return explode($delim, trim((string) $values, $delim));
652 }
653
654 /**
655 * Joins array elements with a string, adding surrounding delimiters.
656 *
657 * This method works mostly like PHP's built-in implode(), but the generated
658 * string is surrounded by delimiter characters. Also, if NULL is passed as
659 * the $values parameter, NULL is returned.
660 *
661 * @param mixed $values
662 * Array to be imploded. If a non-array is passed, it will be cast to an
663 * array.
664 * @param string $delim
665 * Delimiter to be used for implode() and which will surround the output
666 * string.
667 *
668 * @return string|NULL
669 * The generated string, or NULL if NULL was passed as $values parameter.
670 */
671 static function implodePadded($values, $delim = CRM_Core_DAO::VALUE_SEPARATOR) {
672 if ($values === NULL) {
673 return NULL;
674 }
675 // If we already have a string, strip $delim off the ends so it doesn't get added twice
676 if (is_string($values)) {
677 $values = trim($values, $delim);
678 }
679 return $delim . implode($delim, (array) $values) . $delim;
680 }
681
682 /**
683 * Modifies a key in an array while preserving the key order.
684 *
685 * By default when an element is added to an array, it is added to the end.
686 * This method allows for changing an existing key while preserving its
687 * position in the array.
688 *
689 * The array is both modified in-place and returned.
690 *
691 * @param array $elementArray
692 * Array to manipulate.
693 * @param string $oldKey
694 * Old key to be replaced.
695 * @param string $newKey
696 * Replacement key string.
697 *
698 * @throws Exception
699 * Throws a generic Exception if $oldKey is not found in $elementArray.
700 *
701 * @return array
702 * The manipulated array.
703 */
704 static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
705 $keys = array_keys($elementArray);
706 if (FALSE === $index = array_search($oldKey, $keys)) {
707 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
708 }
709 $keys[$index] = $newKey;
710 $elementArray = array_combine($keys, array_values($elementArray));
711 return $elementArray;
712 }
713
714 /*
715 * Searches array keys by regex, returning the value of the first match.
716 *
717 * Given a regular expression and an array, this method searches the keys
718 * of the array using the regular expression. The first match is then used
719 * to index into the array, and the associated value is retrieved and
720 * returned. If no matches are found, or if something other than an array
721 * is passed, then a default value is returned. Unless otherwise specified,
722 * the default value is NULL.
723 *
724 * @param string $regexKey
725 * The regular expression to use when searching for matching keys.
726 * @param array $list
727 * The array whose keys will be searched.
728 * @param mixed $default
729 * (optional) The default value to return if the regex does not match an
730 * array key, or if something other than an array is passed.
731 *
732 * @return mixed
733 * The value found.
734 */
735 /**
736 * @param $regexKey
737 * @param $list
738 * @param null $default
739 *
740 * @return null
741 */
742 static function valueByRegexKey($regexKey, $list, $default = NULL) {
743 if (is_array($list) && $regexKey) {
744 $matches = preg_grep($regexKey, array_keys($list));
745 $key = reset($matches);
746 return ($key && array_key_exists($key, $list)) ? $list[$key] : $default;
747 }
748 return $default;
749 }
750
751 /**
752 * Generates the Cartesian product of zero or more vectors.
753 *
754 * @param array $dimensions
755 * List of dimensions to multiply.
756 * Each key is a dimension name; each value is a vector.
757 * @param array $template
758 * (optional) A base set of values included in every output.
759 *
760 * @return array
761 * Each item is a distinct combination of values from $dimensions.
762 *
763 * For example, the product of
764 * {
765 * fg => {red, blue},
766 * bg => {white, black}
767 * }
768 * would be
769 * {
770 * {fg => red, bg => white},
771 * {fg => red, bg => black},
772 * {fg => blue, bg => white},
773 * {fg => blue, bg => black}
774 * }
775 */
776 static function product($dimensions, $template = array()) {
777 if (empty($dimensions)) {
778 return array($template);
779 }
780
781 foreach ($dimensions as $key => $value) {
782 $firstKey = $key;
783 $firstValues = $value;
784 break;
785 }
786 unset($dimensions[$key]);
787
788 $results = array();
789 foreach ($firstValues as $firstValue) {
790 foreach (self::product($dimensions, $template) as $result) {
791 $result[$firstKey] = $firstValue;
792 $results[] = $result;
793 }
794 }
795
796 return $results;
797 }
798
799 /**
800 * Get the first element of an array
801 *
802 * @param array $array
803 * @return mixed|NULL
804 */
805 static function first($array) {
806 foreach ($array as $value) {
807 return $value;
808 }
809 return NULL;
810 }
811
812 /**
813 * Extract any $keys from $array and copy to a new array.
814 *
815 * Note: If a $key does not appear in $array, then it will
816 * not appear in the result.
817 *
818 * @param array $array
819 * @param array $keys list of keys to copy
820 * @return array
821 */
822 static function subset($array, $keys) {
823 $result = array();
824 foreach ($keys as $key) {
825 if (isset($array[$key])) {
826 $result[$key] = $array[$key];
827 }
828 }
829 return $result;
830 }
831
832 /**
833 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
834 * This is necessary to preserve sort order when sending an array through json_encode.
835 *
836 * @param array $associative
837 * @param string $keyName
838 * @param string $valueName
839 * @return array
840 */
841 static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
842 $output = array();
843 foreach ($associative as $key => $val) {
844 $output[] = array($keyName => $key, $valueName => $val);
845 }
846 return $output;
847 }
848 }
849