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