Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
7e9e8871 | 4 | | CiviCRM version 4.7 | |
6a488035 | 5 | +--------------------------------------------------------------------+ |
0f03f337 | 6 | | Copyright CiviCRM LLC (c) 2004-2017 | |
6a488035 TO |
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 | +--------------------------------------------------------------------+ | |
d25dd0ee | 26 | */ |
6a488035 TO |
27 | |
28 | /** | |
ac302523 | 29 | * Provides a collection of static methods for array manipulation. |
6a488035 TO |
30 | * |
31 | * @package CRM | |
0f03f337 | 32 | * @copyright CiviCRM LLC (c) 2004-2017 |
6a488035 TO |
33 | */ |
34 | class CRM_Utils_Array { | |
35 | ||
36 | /** | |
c9e15d2a RS |
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. | |
6a488035 | 41 | * |
6a488035 | 42 | * |
c9e15d2a RS |
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. | |
4d63cfde | 47 | * @param mixed $default |
c9e15d2a | 48 | * (optional) Value to return $list[$key] does not exist. |
6a488035 | 49 | * |
c9e15d2a RS |
50 | * @return mixed |
51 | * Can return any type, since $list might contain anything. | |
6a488035 | 52 | */ |
00be9182 | 53 | public static function value($key, $list, $default = NULL) { |
6a488035 TO |
54 | if (is_array($list)) { |
55 | return array_key_exists($key, $list) ? $list[$key] : $default; | |
56 | } | |
57 | return $default; | |
58 | } | |
59 | ||
60 | /** | |
c9e15d2a | 61 | * Recursively searches an array for a key, returning the first value found. |
6a488035 | 62 | * |
c9e15d2a RS |
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. | |
6a488035 | 65 | * |
c9e15d2a RS |
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. | |
6a488035 | 73 | */ |
00be9182 | 74 | public static function retrieveValueRecursive(&$params, $key) { |
6a488035 TO |
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 | /** | |
c9e15d2a | 94 | * Wraps and slightly changes the behavior of PHP's array_search(). |
6a488035 | 95 | * |
c9e15d2a RS |
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. | |
6a488035 | 99 | * |
6a488035 | 100 | * |
c9e15d2a RS |
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. | |
6a488035 | 108 | */ |
04f72de8 | 109 | public static function key($value, $list) { |
6a488035 TO |
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 | ||
c9e15d2a RS |
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 | * | |
c9e15d2a RS |
135 | * @return string |
136 | * XML fragment representing $list. | |
137 | */ | |
00be9182 | 138 | public static function &xml(&$list, $depth = 1, $seperator = "\n") { |
6a488035 TO |
139 | $xml = ''; |
140 | foreach ($list as $name => $value) { | |
141 | $xml .= str_repeat(' ', $depth * 4); | |
142 | if (is_array($value)) { | |
143 | $xml .= "<{$name}>{$seperator}"; | |
144 | $xml .= self::xml($value, $depth + 1, $seperator); | |
145 | $xml .= str_repeat(' ', $depth * 4); | |
146 | $xml .= "</{$name}>{$seperator}"; | |
147 | } | |
148 | else { | |
149 | // make sure we escape value | |
150 | $value = self::escapeXML($value); | |
151 | $xml .= "<{$name}>$value</{$name}>{$seperator}"; | |
152 | } | |
153 | } | |
154 | return $xml; | |
155 | } | |
156 | ||
c9e15d2a RS |
157 | /** |
158 | * Sanitizes a string for serialization in CRM_Utils_Array::xml(). | |
159 | * | |
160 | * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A' | |
161 | * with a comma. | |
162 | * | |
163 | * @param string $value | |
164 | * String to be sanitized. | |
165 | * | |
166 | * @return string | |
167 | * Sanitized version of $value. | |
168 | */ | |
00be9182 | 169 | public static function escapeXML($value) { |
6a488035 TO |
170 | static $src = NULL; |
171 | static $dst = NULL; | |
172 | ||
173 | if (!$src) { | |
174 | $src = array('&', '<', '>', '\ 1'); | |
175 | $dst = array('&', '<', '>', ','); | |
176 | } | |
177 | ||
178 | return str_replace($src, $dst, $value); | |
179 | } | |
180 | ||
181 | /** | |
c9e15d2a RS |
182 | * Converts a nested array to a flat array. |
183 | * | |
184 | * The nested structure is preserved in the string values of the keys of the | |
185 | * flat array. | |
186 | * | |
187 | * Example nested array: | |
188 | * Array | |
189 | * ( | |
190 | * [foo] => Array | |
191 | * ( | |
192 | * [0] => bar | |
193 | * [1] => baz | |
194 | * [2] => 42 | |
195 | * ) | |
f4aaa82a | 196 | * |
c9e15d2a RS |
197 | * [asdf] => Array |
198 | * ( | |
199 | * [merp] => bleep | |
200 | * [quack] => Array | |
201 | * ( | |
202 | * [0] => 1 | |
203 | * [1] => 2 | |
204 | * [2] => 3 | |
205 | * ) | |
f4aaa82a | 206 | * |
c9e15d2a | 207 | * ) |
f4aaa82a | 208 | * |
c9e15d2a RS |
209 | * [quux] => 999 |
210 | * ) | |
f4aaa82a | 211 | * |
c9e15d2a RS |
212 | * Corresponding flattened array: |
213 | * Array | |
214 | * ( | |
215 | * [foo.0] => bar | |
216 | * [foo.1] => baz | |
217 | * [foo.2] => 42 | |
218 | * [asdf.merp] => bleep | |
219 | * [asdf.quack.0] => 1 | |
220 | * [asdf.quack.1] => 2 | |
221 | * [asdf.quack.2] => 3 | |
222 | * [quux] => 999 | |
223 | * ) | |
224 | * | |
225 | * @param array $list | |
226 | * Array to be flattened. | |
227 | * @param array $flat | |
228 | * Destination array. | |
6a488035 | 229 | * @param string $prefix |
c9e15d2a | 230 | * (optional) String to prepend to keys. |
6a488035 | 231 | * @param string $seperator |
c9e15d2a | 232 | * (optional) String that separates the concatenated keys. |
6a488035 | 233 | */ |
00be9182 | 234 | public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") { |
6a488035 TO |
235 | foreach ($list as $name => $value) { |
236 | $newPrefix = ($prefix) ? $prefix . $seperator . $name : $name; | |
237 | if (is_array($value)) { | |
238 | self::flatten($value, $flat, $newPrefix, $seperator); | |
239 | } | |
240 | else { | |
241 | if (!empty($value)) { | |
242 | $flat[$newPrefix] = $value; | |
243 | } | |
244 | } | |
245 | } | |
246 | } | |
247 | ||
248 | /** | |
c9e15d2a RS |
249 | * Converts an array with path-like keys into a tree of arrays. |
250 | * | |
251 | * This function is the inverse of CRM_Utils_Array::flatten(). | |
252 | * | |
253 | * @param string $delim | |
254 | * A path delimiter | |
255 | * @param array $arr | |
256 | * A one-dimensional array indexed by string keys | |
6a488035 | 257 | * |
c9e15d2a RS |
258 | * @return array |
259 | * Array-encoded tree | |
6a488035 | 260 | */ |
00be9182 | 261 | public function unflatten($delim, &$arr) { |
6a488035 TO |
262 | $result = array(); |
263 | foreach ($arr as $key => $value) { | |
264 | $path = explode($delim, $key); | |
265 | $node = &$result; | |
266 | while (count($path) > 1) { | |
267 | $key = array_shift($path); | |
268 | if (!isset($node[$key])) { | |
269 | $node[$key] = array(); | |
270 | } | |
271 | $node = &$node[$key]; | |
272 | } | |
273 | // last part of path | |
274 | $key = array_shift($path); | |
275 | $node[$key] = $value; | |
276 | } | |
277 | return $result; | |
278 | } | |
279 | ||
280 | /** | |
c9e15d2a RS |
281 | * Merges two arrays. |
282 | * | |
283 | * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge | |
284 | * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both | |
285 | * exist but they are not both arrays, the value from $a1 overrides the | |
286 | * value from $a2 and the value from $a2 is discarded. | |
6a488035 TO |
287 | * |
288 | * @param array $a1 | |
c9e15d2a | 289 | * First array to be merged. |
6a488035 | 290 | * @param array $a2 |
c9e15d2a | 291 | * Second array to be merged. |
6a488035 | 292 | * |
c9e15d2a RS |
293 | * @return array |
294 | * The merged array. | |
6a488035 | 295 | */ |
00be9182 | 296 | public static function crmArrayMerge($a1, $a2) { |
6a488035 TO |
297 | if (empty($a1)) { |
298 | return $a2; | |
299 | } | |
300 | ||
301 | if (empty($a2)) { | |
302 | return $a1; | |
303 | } | |
304 | ||
305 | $a3 = array(); | |
306 | foreach ($a1 as $key => $value) { | |
307 | if (array_key_exists($key, $a2) && | |
308 | is_array($a2[$key]) && is_array($a1[$key]) | |
309 | ) { | |
310 | $a3[$key] = array_merge($a1[$key], $a2[$key]); | |
311 | } | |
312 | else { | |
313 | $a3[$key] = $a1[$key]; | |
314 | } | |
315 | } | |
316 | ||
317 | foreach ($a2 as $key => $value) { | |
318 | if (array_key_exists($key, $a1)) { | |
319 | // already handled in above loop | |
320 | continue; | |
321 | } | |
322 | $a3[$key] = $a2[$key]; | |
323 | } | |
324 | ||
325 | return $a3; | |
326 | } | |
327 | ||
c9e15d2a RS |
328 | /** |
329 | * Determines whether an array contains any sub-arrays. | |
330 | * | |
331 | * @param array $list | |
332 | * The array to inspect. | |
333 | * | |
334 | * @return bool | |
335 | * True if $list contains at least one sub-array, false otherwise. | |
c9e15d2a | 336 | */ |
00be9182 | 337 | public static function isHierarchical(&$list) { |
6a488035 TO |
338 | foreach ($list as $n => $v) { |
339 | if (is_array($v)) { | |
340 | return TRUE; | |
341 | } | |
342 | } | |
343 | return FALSE; | |
344 | } | |
345 | ||
82376c19 | 346 | /** |
54957108 | 347 | * Is array A a subset of array B. |
348 | * | |
349 | * @param array $subset | |
350 | * @param array $superset | |
351 | * | |
a6c01b45 CW |
352 | * @return bool |
353 | * TRUE if $subset is a subset of $superset | |
82376c19 | 354 | */ |
00be9182 | 355 | public static function isSubset($subset, $superset) { |
82376c19 TO |
356 | foreach ($subset as $expected) { |
357 | if (!in_array($expected, $superset)) { | |
358 | return FALSE; | |
359 | } | |
360 | } | |
361 | return TRUE; | |
362 | } | |
363 | ||
6a488035 | 364 | /** |
c9e15d2a | 365 | * Searches an array recursively in an optionally case-insensitive manner. |
6a488035 | 366 | * |
c9e15d2a RS |
367 | * @param string $value |
368 | * Value to search for. | |
369 | * @param array $params | |
370 | * Array to search within. | |
371 | * @param bool $caseInsensitive | |
372 | * (optional) Whether to search in a case-insensitive manner. | |
6a488035 | 373 | * |
c9e15d2a RS |
374 | * @return bool |
375 | * True if $value was found, false otherwise. | |
6a488035 | 376 | */ |
00be9182 | 377 | public static function crmInArray($value, $params, $caseInsensitive = TRUE) { |
6a488035 TO |
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 | /** | |
54957108 | 393 | * Convert associative array names to values and vice-versa. |
6a488035 | 394 | * |
8ff43cf2 | 395 | * This function is used by by import functions and some webforms. |
54957108 | 396 | * |
397 | * @param array $defaults | |
398 | * @param string $property | |
399 | * @param $lookup | |
400 | * @param $reverse | |
401 | * | |
402 | * @return bool | |
6a488035 | 403 | */ |
00be9182 | 404 | public static function lookupValue(&$defaults, $property, $lookup, $reverse) { |
6a488035 TO |
405 | $id = $property . '_id'; |
406 | ||
407 | $src = $reverse ? $property : $id; | |
408 | $dst = $reverse ? $id : $property; | |
409 | ||
410 | if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER))) { | |
411 | return FALSE; | |
412 | } | |
413 | ||
414 | $look = $reverse ? array_flip($lookup) : $lookup; | |
415 | ||
50bfb460 | 416 | // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid |
6a488035 TO |
417 | $newLook = array(); |
418 | foreach ($look as $k => $v) { | |
419 | $newLook[trim($k, ".")] = $v; | |
420 | } | |
421 | ||
422 | $look = $newLook; | |
423 | ||
424 | if (is_array($look)) { | |
425 | if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER))) { | |
426 | return FALSE; | |
427 | } | |
428 | } | |
429 | ||
430 | $tempLook = array_change_key_case($look, CASE_LOWER); | |
431 | ||
432 | $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')]; | |
433 | return TRUE; | |
434 | } | |
435 | ||
436 | /** | |
c9e15d2a RS |
437 | * Checks whether an array is empty. |
438 | * | |
439 | * An array is empty if its values consist only of NULL and empty sub-arrays. | |
440 | * Containing a non-NULL value or non-empty array makes an array non-empty. | |
441 | * | |
442 | * If something other than an array is passed, it is considered to be empty. | |
443 | * | |
444 | * If nothing is passed at all, the default value provided is empty. | |
445 | * | |
446 | * @param array $array | |
447 | * (optional) Array to be checked for emptiness. | |
6a488035 | 448 | * |
d5cc0fc2 | 449 | * @return bool |
c9e15d2a | 450 | * True if the array is empty. |
6a488035 | 451 | */ |
00be9182 | 452 | public static function crmIsEmptyArray($array = array()) { |
6a488035 TO |
453 | if (!is_array($array)) { |
454 | return TRUE; | |
455 | } | |
456 | foreach ($array as $element) { | |
457 | if (is_array($element)) { | |
458 | if (!self::crmIsEmptyArray($element)) { | |
459 | return FALSE; | |
460 | } | |
461 | } | |
462 | elseif (isset($element)) { | |
463 | return FALSE; | |
464 | } | |
465 | } | |
466 | return TRUE; | |
467 | } | |
468 | ||
6a488035 | 469 | /** |
c9e15d2a | 470 | * Sorts an associative array of arrays by an attribute using strnatcmp(). |
6a488035 | 471 | * |
c9e15d2a RS |
472 | * @param array $array |
473 | * Array to be sorted. | |
6db70618 | 474 | * @param string|array $field |
c9e15d2a | 475 | * Name of the attribute used for sorting. |
6a488035 | 476 | * |
f4aaa82a | 477 | * @return array |
c9e15d2a | 478 | * Sorted array |
6a488035 | 479 | */ |
00be9182 | 480 | public static function crmArraySortByField($array, $field) { |
6db70618 TO |
481 | $fields = (array) $field; |
482 | uasort($array, function ($a, $b) use ($fields) { | |
483 | foreach ($fields as $f) { | |
484 | $v = strnatcmp($a[$f], $b[$f]); | |
485 | if ($v !== 0) { | |
486 | return $v; | |
487 | } | |
488 | } | |
489 | return 0; | |
490 | }); | |
6a488035 TO |
491 | return $array; |
492 | } | |
493 | ||
494 | /** | |
c9e15d2a | 495 | * Recursively removes duplicate values from a multi-dimensional array. |
6a488035 | 496 | * |
c9e15d2a RS |
497 | * @param array $array |
498 | * The input array possibly containing duplicate values. | |
6a488035 | 499 | * |
f4aaa82a | 500 | * @return array |
c9e15d2a | 501 | * The input array with duplicate values removed. |
6a488035 | 502 | */ |
00be9182 | 503 | public static function crmArrayUnique($array) { |
6a488035 TO |
504 | $result = array_map("unserialize", array_unique(array_map("serialize", $array))); |
505 | foreach ($result as $key => $value) { | |
506 | if (is_array($value)) { | |
507 | $result[$key] = self::crmArrayUnique($value); | |
508 | } | |
509 | } | |
510 | return $result; | |
511 | } | |
512 | ||
513 | /** | |
c9e15d2a RS |
514 | * Sorts an array and maintains index association (with localization). |
515 | * | |
516 | * Uses Collate from the PECL "intl" package, if available, for UTF-8 | |
517 | * sorting (e.g. list of countries). Otherwise calls PHP's asort(). | |
6a488035 | 518 | * |
c9e15d2a | 519 | * On Debian/Ubuntu: apt-get install php5-intl |
6a488035 | 520 | * |
c9e15d2a RS |
521 | * @param array $array |
522 | * (optional) Array to be sorted. | |
523 | * | |
f4aaa82a | 524 | * @return array |
c9e15d2a | 525 | * Sorted array. |
6a488035 | 526 | */ |
00be9182 | 527 | public static function asort($array = array()) { |
6a488035 TO |
528 | $lcMessages = CRM_Utils_System::getUFLocale(); |
529 | ||
530 | if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) { | |
531 | $collator = new Collator($lcMessages . '.utf8'); | |
532 | $collator->asort($array); | |
533 | } | |
534 | else { | |
c9e15d2a | 535 | // This calls PHP's built-in asort(). |
6a488035 TO |
536 | asort($array); |
537 | } | |
538 | ||
539 | return $array; | |
540 | } | |
541 | ||
542 | /** | |
c9e15d2a RS |
543 | * Unsets an arbitrary list of array elements from an associative array. |
544 | * | |
545 | * @param array $items | |
546 | * The array from which to remove items. | |
f4aaa82a | 547 | * |
fa0ededf CW |
548 | * Additional params: |
549 | * When passed a string, unsets $items[$key]. | |
550 | * When passed an array of strings, unsets $items[$k] for each string $k in the array. | |
6a488035 | 551 | */ |
e7292422 TO |
552 | public static function remove(&$items) { |
553 | foreach (func_get_args() as $n => $key) { | |
554 | // Skip argument 0 ($items) by testing $n for truth. | |
555 | if ($n && is_array($key)) { | |
22e263ad | 556 | foreach ($key as $k) { |
e7292422 TO |
557 | unset($items[$k]); |
558 | } | |
559 | } | |
560 | elseif ($n) { | |
561 | unset($items[$key]); | |
562 | } | |
563 | } | |
564 | } | |
6a488035 TO |
565 | |
566 | /** | |
c9e15d2a | 567 | * Builds an array-tree which indexes the records in an array. |
6a488035 | 568 | * |
c9e15d2a RS |
569 | * @param string[] $keys |
570 | * Properties by which to index. | |
571 | * @param object|array $records | |
572 | * | |
573 | * @return array | |
574 | * Multi-dimensional array, with one layer for each key. | |
6a488035 | 575 | */ |
00be9182 | 576 | public static function index($keys, $records) { |
6a488035 TO |
577 | $final_key = array_pop($keys); |
578 | ||
579 | $result = array(); | |
580 | foreach ($records as $record) { | |
581 | $node = &$result; | |
582 | foreach ($keys as $key) { | |
583 | if (is_array($record)) { | |
928c5201 | 584 | $keyvalue = isset($record[$key]) ? $record[$key] : NULL; |
0db6c3e1 TO |
585 | } |
586 | else { | |
928c5201 | 587 | $keyvalue = isset($record->{$key}) ? $record->{$key} : NULL; |
6a488035 | 588 | } |
17d4d611 | 589 | if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) { |
6a488035 TO |
590 | $node[$keyvalue] = array(); |
591 | } | |
592 | $node = &$node[$keyvalue]; | |
593 | } | |
594 | if (is_array($record)) { | |
e7292422 | 595 | $node[$record[$final_key]] = $record; |
0db6c3e1 TO |
596 | } |
597 | else { | |
e7292422 | 598 | $node[$record->{$final_key}] = $record; |
6a488035 TO |
599 | } |
600 | } | |
601 | return $result; | |
602 | } | |
603 | ||
604 | /** | |
c9e15d2a | 605 | * Iterates over a list of records and returns the value of some property. |
6a488035 TO |
606 | * |
607 | * @param string $prop | |
c9e15d2a RS |
608 | * Property to retrieve. |
609 | * @param array|object $records | |
610 | * A list of records. | |
611 | * | |
612 | * @return array | |
613 | * Keys are the original keys of $records; values are the $prop values. | |
6a488035 | 614 | */ |
00be9182 | 615 | public static function collect($prop, $records) { |
6a488035 | 616 | $result = array(); |
4d34fcfa | 617 | if (is_array($records)) { |
618 | foreach ($records as $key => $record) { | |
619 | if (is_object($record)) { | |
620 | $result[$key] = $record->{$prop}; | |
0db6c3e1 TO |
621 | } |
622 | else { | |
5836c35a | 623 | $result[$key] = self::value($prop, $record); |
4d34fcfa | 624 | } |
6a488035 TO |
625 | } |
626 | } | |
627 | return $result; | |
628 | } | |
629 | ||
2c6fe88a TO |
630 | /** |
631 | * Iterates over a list of objects and executes some method on each. | |
632 | * | |
633 | * Comparison: | |
634 | * - This is like array_map(), except it executes the objects' method | |
635 | * instead of a free-form callable. | |
636 | * - This is like Array::collect(), except it uses a method | |
637 | * instead of a property. | |
638 | * | |
639 | * @param string $method | |
640 | * The method to execute. | |
641 | * @param array|Traversable $objects | |
642 | * A list of objects. | |
643 | * @param array $args | |
644 | * An optional list of arguments to pass to the method. | |
645 | * | |
646 | * @return array | |
647 | * Keys are the original keys of $objects; values are the method results. | |
648 | */ | |
649 | public static function collectMethod($method, $objects, $args = array()) { | |
650 | $result = array(); | |
651 | if (is_array($objects)) { | |
652 | foreach ($objects as $key => $object) { | |
653 | $result[$key] = call_user_func_array(array($object, $method), $args); | |
654 | } | |
655 | } | |
656 | return $result; | |
657 | } | |
658 | ||
6a488035 | 659 | /** |
c9e15d2a | 660 | * Trims delimiters from a string and then splits it using explode(). |
6a488035 | 661 | * |
c9e15d2a RS |
662 | * This method works mostly like PHP's built-in explode(), except that |
663 | * surrounding delimiters are trimmed before explode() is called. | |
664 | * | |
665 | * Also, if an array or NULL is passed as the $values parameter, the value is | |
666 | * returned unmodified rather than being passed to explode(). | |
667 | * | |
668 | * @param array|null|string $values | |
669 | * The input string (or an array, or NULL). | |
6a488035 | 670 | * @param string $delim |
c9e15d2a RS |
671 | * (optional) The boundary string. |
672 | * | |
673 | * @return array|null | |
674 | * An array of strings produced by explode(), or the unmodified input | |
675 | * array, or NULL. | |
6a488035 | 676 | */ |
00be9182 | 677 | public static function explodePadded($values, $delim = CRM_Core_DAO::VALUE_SEPARATOR) { |
fe18a93c | 678 | if ($values === NULL) { |
6a488035 TO |
679 | return NULL; |
680 | } | |
fe18a93c CW |
681 | // If we already have an array, no need to continue |
682 | if (is_array($values)) { | |
683 | return $values; | |
684 | } | |
62bcdea6 CW |
685 | // Empty string -> empty array |
686 | if ($values === '') { | |
687 | return array(); | |
688 | } | |
fe18a93c | 689 | return explode($delim, trim((string) $values, $delim)); |
6a488035 TO |
690 | } |
691 | ||
692 | /** | |
c9e15d2a RS |
693 | * Joins array elements with a string, adding surrounding delimiters. |
694 | * | |
695 | * This method works mostly like PHP's built-in implode(), but the generated | |
696 | * string is surrounded by delimiter characters. Also, if NULL is passed as | |
697 | * the $values parameter, NULL is returned. | |
6a488035 | 698 | * |
fe18a93c | 699 | * @param mixed $values |
c9e15d2a RS |
700 | * Array to be imploded. If a non-array is passed, it will be cast to an |
701 | * array. | |
6a488035 | 702 | * @param string $delim |
c9e15d2a RS |
703 | * Delimiter to be used for implode() and which will surround the output |
704 | * string. | |
705 | * | |
fe18a93c | 706 | * @return string|NULL |
c9e15d2a | 707 | * The generated string, or NULL if NULL was passed as $values parameter. |
6a488035 | 708 | */ |
00be9182 | 709 | public static function implodePadded($values, $delim = CRM_Core_DAO::VALUE_SEPARATOR) { |
6a488035 TO |
710 | if ($values === NULL) { |
711 | return NULL; | |
712 | } | |
fe18a93c CW |
713 | // If we already have a string, strip $delim off the ends so it doesn't get added twice |
714 | if (is_string($values)) { | |
715 | $values = trim($values, $delim); | |
716 | } | |
717 | return $delim . implode($delim, (array) $values) . $delim; | |
6a488035 TO |
718 | } |
719 | ||
720 | /** | |
c9e15d2a RS |
721 | * Modifies a key in an array while preserving the key order. |
722 | * | |
723 | * By default when an element is added to an array, it is added to the end. | |
724 | * This method allows for changing an existing key while preserving its | |
725 | * position in the array. | |
726 | * | |
727 | * The array is both modified in-place and returned. | |
728 | * | |
729 | * @param array $elementArray | |
730 | * Array to manipulate. | |
731 | * @param string $oldKey | |
732 | * Old key to be replaced. | |
733 | * @param string $newKey | |
734 | * Replacement key string. | |
6a488035 | 735 | * |
c9e15d2a RS |
736 | * @throws Exception |
737 | * Throws a generic Exception if $oldKey is not found in $elementArray. | |
6a488035 TO |
738 | * |
739 | * @return array | |
c9e15d2a | 740 | * The manipulated array. |
6a488035 | 741 | */ |
00be9182 | 742 | public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) { |
6a488035 TO |
743 | $keys = array_keys($elementArray); |
744 | if (FALSE === $index = array_search($oldKey, $keys)) { | |
745 | throw new Exception(sprintf('key "%s" does not exit', $oldKey)); | |
746 | } | |
747 | $keys[$index] = $newKey; | |
748 | $elementArray = array_combine($keys, array_values($elementArray)); | |
749 | return $elementArray; | |
750 | } | |
bd7b39e7 | 751 | |
d424ffde | 752 | /** |
c9e15d2a RS |
753 | * Searches array keys by regex, returning the value of the first match. |
754 | * | |
755 | * Given a regular expression and an array, this method searches the keys | |
756 | * of the array using the regular expression. The first match is then used | |
757 | * to index into the array, and the associated value is retrieved and | |
758 | * returned. If no matches are found, or if something other than an array | |
759 | * is passed, then a default value is returned. Unless otherwise specified, | |
760 | * the default value is NULL. | |
761 | * | |
762 | * @param string $regexKey | |
763 | * The regular expression to use when searching for matching keys. | |
764 | * @param array $list | |
765 | * The array whose keys will be searched. | |
766 | * @param mixed $default | |
767 | * (optional) The default value to return if the regex does not match an | |
768 | * array key, or if something other than an array is passed. | |
769 | * | |
770 | * @return mixed | |
771 | * The value found. | |
bd7b39e7 | 772 | */ |
00be9182 | 773 | public static function valueByRegexKey($regexKey, $list, $default = NULL) { |
bd7b39e7 PJ |
774 | if (is_array($list) && $regexKey) { |
775 | $matches = preg_grep($regexKey, array_keys($list)); | |
776 | $key = reset($matches); | |
777 | return ($key && array_key_exists($key, $list)) ? $list[$key] : $default; | |
778 | } | |
779 | return $default; | |
780 | } | |
17deafad TO |
781 | |
782 | /** | |
c9e15d2a | 783 | * Generates the Cartesian product of zero or more vectors. |
17deafad | 784 | * |
c9e15d2a RS |
785 | * @param array $dimensions |
786 | * List of dimensions to multiply. | |
787 | * Each key is a dimension name; each value is a vector. | |
788 | * @param array $template | |
789 | * (optional) A base set of values included in every output. | |
790 | * | |
791 | * @return array | |
792 | * Each item is a distinct combination of values from $dimensions. | |
17deafad | 793 | * |
d5cc0fc2 | 794 | * For example, the product of |
795 | * { | |
17deafad TO |
796 | * fg => {red, blue}, |
797 | * bg => {white, black} | |
d5cc0fc2 | 798 | * } |
799 | * would be | |
800 | * { | |
17deafad TO |
801 | * {fg => red, bg => white}, |
802 | * {fg => red, bg => black}, | |
803 | * {fg => blue, bg => white}, | |
804 | * {fg => blue, bg => black} | |
d5cc0fc2 | 805 | * } |
17deafad | 806 | */ |
00be9182 | 807 | public static function product($dimensions, $template = array()) { |
17deafad TO |
808 | if (empty($dimensions)) { |
809 | return array($template); | |
810 | } | |
811 | ||
812 | foreach ($dimensions as $key => $value) { | |
813 | $firstKey = $key; | |
814 | $firstValues = $value; | |
815 | break; | |
816 | } | |
817 | unset($dimensions[$key]); | |
818 | ||
819 | $results = array(); | |
820 | foreach ($firstValues as $firstValue) { | |
821 | foreach (self::product($dimensions, $template) as $result) { | |
822 | $result[$firstKey] = $firstValue; | |
823 | $results[] = $result; | |
824 | } | |
825 | } | |
826 | ||
827 | return $results; | |
828 | } | |
eb20fbf0 TO |
829 | |
830 | /** | |
fe482240 | 831 | * Get the first element of an array. |
eb20fbf0 TO |
832 | * |
833 | * @param array $array | |
834 | * @return mixed|NULL | |
835 | */ | |
00be9182 | 836 | public static function first($array) { |
eb20fbf0 TO |
837 | foreach ($array as $value) { |
838 | return $value; | |
839 | } | |
840 | return NULL; | |
841 | } | |
768c558c TO |
842 | |
843 | /** | |
844 | * Extract any $keys from $array and copy to a new array. | |
845 | * | |
846 | * Note: If a $key does not appear in $array, then it will | |
847 | * not appear in the result. | |
848 | * | |
849 | * @param array $array | |
77855840 TO |
850 | * @param array $keys |
851 | * List of keys to copy. | |
768c558c TO |
852 | * @return array |
853 | */ | |
00be9182 | 854 | public static function subset($array, $keys) { |
768c558c TO |
855 | $result = array(); |
856 | foreach ($keys as $key) { | |
857 | if (isset($array[$key])) { | |
858 | $result[$key] = $array[$key]; | |
859 | } | |
860 | } | |
861 | return $result; | |
862 | } | |
a335f6b2 | 863 | |
b7ceb253 CW |
864 | /** |
865 | * Transform an associative array of key=>value pairs into a non-associative array of arrays. | |
866 | * This is necessary to preserve sort order when sending an array through json_encode. | |
867 | * | |
868 | * @param array $associative | |
869 | * @param string $keyName | |
870 | * @param string $valueName | |
871 | * @return array | |
872 | */ | |
00be9182 | 873 | public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') { |
b7ceb253 CW |
874 | $output = array(); |
875 | foreach ($associative as $key => $val) { | |
876 | $output[] = array($keyName => $key, $valueName => $val); | |
877 | } | |
878 | return $output; | |
879 | } | |
96025800 | 880 | |
06d253f5 | 881 | /** |
882 | * Diff multidimensional arrays | |
50bfb460 | 883 | * (array_diff does not support multidimensional array) |
06d253f5 | 884 | * |
885 | * @param array $array1 | |
886 | * @param array $array2 | |
887 | * @return array | |
888 | */ | |
889 | public static function multiArrayDiff($array1, $array2) { | |
890 | $arrayDiff = array(); | |
891 | foreach ($array1 as $mKey => $mValue) { | |
892 | if (array_key_exists($mKey, $array2)) { | |
893 | if (is_array($mValue)) { | |
894 | $recursiveDiff = self::multiArrayDiff($mValue, $array2[$mKey]); | |
895 | if (count($recursiveDiff)) { | |
896 | $arrayDiff[$mKey] = $recursiveDiff; | |
897 | } | |
898 | } | |
899 | else { | |
900 | if ($mValue != $array2[$mKey]) { | |
901 | $arrayDiff[$mKey] = $mValue; | |
902 | } | |
903 | } | |
904 | } | |
905 | else { | |
906 | $arrayDiff[$mKey] = $mValue; | |
907 | } | |
908 | } | |
909 | return $arrayDiff; | |
910 | } | |
5793f1d9 | 911 | |
5bc7c754 TO |
912 | /** |
913 | * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns. | |
914 | * | |
915 | * @param array $matrix | |
916 | * All matrix data, as a list of rows. | |
917 | * @param array $columns | |
918 | * List of column names. | |
919 | * @return array | |
920 | */ | |
921 | public static function filterColumns($matrix, $columns) { | |
922 | $newRows = array(); | |
923 | foreach ($matrix as $pos => $oldRow) { | |
924 | $newRow = array(); | |
925 | foreach ($columns as $column) { | |
926 | $newRow[$column] = CRM_Utils_Array::value($column, $oldRow); | |
927 | } | |
928 | $newRows[$pos] = $newRow; | |
929 | } | |
930 | return $newRows; | |
931 | } | |
932 | ||
952d7eb1 | 933 | /** |
69f9c562 | 934 | * Rewrite the keys in an array. |
952d7eb1 TO |
935 | * |
936 | * @param array $array | |
69f9c562 CW |
937 | * @param string|callable $indexBy |
938 | * Either the value to key by, or a function($key, $value) that returns the new key. | |
952d7eb1 TO |
939 | * @return array |
940 | */ | |
69f9c562 | 941 | public static function rekey($array, $indexBy) { |
952d7eb1 TO |
942 | $result = array(); |
943 | foreach ($array as $key => $value) { | |
69f9c562 | 944 | $newKey = is_callable($indexBy) ? $indexBy($key, $value) : $value[$indexBy]; |
952d7eb1 TO |
945 | $result[$newKey] = $value; |
946 | } | |
947 | return $result; | |
948 | } | |
949 | ||
4f24efcc TO |
950 | /** |
951 | * Copy all properties of $other into $array (recursively). | |
952 | * | |
953 | * @param array|ArrayAccess $array | |
954 | * @param array $other | |
955 | */ | |
956 | public static function extend(&$array, $other) { | |
957 | foreach ($other as $key => $value) { | |
958 | if (is_array($value)) { | |
959 | self::extend($array[$key], $value); | |
960 | } | |
961 | else { | |
962 | $array[$key] = $value; | |
963 | } | |
964 | } | |
965 | } | |
966 | ||
393f41dd TO |
967 | /** |
968 | * Get a single value from an array-tre. | |
969 | * | |
970 | * @param array $arr | |
971 | * Ex: array('foo'=>array('bar'=>123)). | |
972 | * @param array $pathParts | |
973 | * Ex: array('foo',bar'). | |
974 | * @return mixed|NULL | |
975 | * Ex 123. | |
976 | */ | |
977 | public static function pathGet($arr, $pathParts) { | |
978 | $r = $arr; | |
979 | foreach ($pathParts as $part) { | |
980 | if (!isset($r[$part])) { | |
981 | return NULL; | |
982 | } | |
983 | $r = $r[$part]; | |
984 | } | |
985 | return $r; | |
986 | } | |
987 | ||
988 | /** | |
989 | * Set a single value in an array tree. | |
990 | * | |
991 | * @param array $arr | |
992 | * Ex: array('foo'=>array('bar'=>123)). | |
993 | * @param array $pathParts | |
994 | * Ex: array('foo',bar'). | |
995 | * @param $value | |
996 | * Ex: 456. | |
997 | */ | |
998 | public static function pathSet(&$arr, $pathParts, $value) { | |
999 | $r = &$arr; | |
1000 | $last = array_pop($pathParts); | |
1001 | foreach ($pathParts as $part) { | |
1002 | if (!isset($r[$part])) { | |
1003 | $r[$part] = array(); | |
1004 | } | |
1005 | $r = &$r[$part]; | |
1006 | } | |
1007 | $r[$last] = $value; | |
1008 | } | |
1009 | ||
2c6fe88a TO |
1010 | /** |
1011 | * Convert a simple dictionary into separate key+value records. | |
1012 | * | |
1013 | * @param array $array | |
1014 | * Ex: array('foo' => 'bar'). | |
1015 | * @param string $keyField | |
1016 | * Ex: 'key'. | |
1017 | * @param string $valueField | |
1018 | * Ex: 'value'. | |
1019 | * @return array | |
1020 | * Ex: array( | |
1021 | * 0 => array('key' => 'foo', 'value' => 'bar') | |
1022 | * ). | |
1023 | */ | |
1024 | public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') { | |
1025 | $result = array(); | |
1026 | foreach ($array as $key => $value) { | |
1027 | $result[] = array( | |
1028 | $keyField => $key, | |
1029 | $valueField => $value, | |
1030 | ); | |
1031 | } | |
1032 | return $result; | |
1033 | } | |
1034 | ||
6c28d4be | 1035 | /** |
1036 | * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values | |
1037 | * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4) | |
1038 | * | |
e5ad0335 E |
1039 | * @deprecated use convertCheckboxInputToArray instead (after testing) |
1040 | * https://github.com/civicrm/civicrm-core/pull/8169 | |
1041 | * | |
6c28d4be | 1042 | * @param array $array |
6c28d4be | 1043 | */ |
1044 | public static function formatArrayKeys(&$array) { | |
38c304a5 | 1045 | if (!is_array($array)) { |
1046 | return; | |
1047 | } | |
6c28d4be | 1048 | $keys = array_keys($array, 1); |
1049 | if (count($keys) > 1 || | |
1050 | (count($keys) == 1 && | |
f6cc7d47 | 1051 | (current($keys) > 1 || |
1052 | is_string(current($keys)) || | |
1053 | (current($keys) == 1 && $array[1] == 1) // handle (0 => 4), (1 => 1) | |
6c28d4be | 1054 | ) |
1055 | ) | |
1056 | ) { | |
1057 | $array = $keys; | |
1058 | } | |
1059 | } | |
1060 | ||
e5ad0335 E |
1061 | /** |
1062 | * Convert the data format coming in from checkboxes to an array of values. | |
1063 | * | |
1064 | * The input format from check boxes looks like | |
1065 | * array('value1' => 1, 'value2' => 1). This function converts those values to | |
1066 | * array(''value1', 'value2). | |
1067 | * | |
1068 | * The function will only alter the array if all values are equal to 1. | |
1069 | * | |
1070 | * @param array $input | |
1071 | * | |
1072 | * @return array | |
1073 | */ | |
1074 | public static function convertCheckboxFormatToArray($input) { | |
1075 | if (isset($input[0])) { | |
1076 | return $input; | |
1077 | } | |
1078 | $keys = array_keys($input, 1); | |
1079 | if ((count($keys) == count($input))) { | |
1080 | return $keys; | |
1081 | } | |
1082 | return $input; | |
1083 | } | |
1084 | ||
589e0f03 SL |
1085 | /** |
1086 | * Ensure that array is encoded in utf8 format. | |
1087 | * | |
1088 | * @param array $array | |
1089 | * | |
1090 | * @return array $array utf8-encoded. | |
1091 | */ | |
a83e8a28 SL |
1092 | public static function encode_items($array) { |
1093 | foreach ($array as $key => $value) { | |
1094 | if (is_array($value)) { | |
1095 | $array[$key] = self::encode_items($value); | |
1096 | } | |
48b4ad1f | 1097 | elseif (is_string($value)) { |
e46fbdd3 | 1098 | $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8'); |
a83e8a28 | 1099 | } |
48b4ad1f SL |
1100 | else { |
1101 | $array[$key] = $value; | |
1102 | } | |
a83e8a28 SL |
1103 | } |
1104 | return $array; | |
1105 | } | |
1106 | ||
bc854509 | 1107 | /** |
1108 | * Build tree of elements. | |
1109 | * | |
1110 | * @param array $elements | |
1111 | * @param int|null $parentId | |
1112 | * | |
1113 | * @return array | |
1114 | */ | |
b733747a CW |
1115 | public static function buildTree($elements, $parentId = NULL) { |
1116 | $branch = array(); | |
1117 | ||
1118 | foreach ($elements as $element) { | |
1119 | if ($element['parent_id'] == $parentId) { | |
1120 | $children = self::buildTree($elements, $element['id']); | |
1121 | if ($children) { | |
1122 | $element['children'] = $children; | |
1123 | } | |
1124 | $branch[] = $element; | |
1125 | } | |
1126 | } | |
1127 | ||
1128 | return $branch; | |
1129 | } | |
1130 | ||
bc854509 | 1131 | /** |
1132 | * Find search string in tree. | |
1133 | * | |
1134 | * @param string $search | |
1135 | * @param array $tree | |
1136 | * @param string $field | |
1137 | * | |
1138 | * @return array|null | |
1139 | */ | |
b733747a CW |
1140 | public static function findInTree($search, $tree, $field = 'id') { |
1141 | foreach ($tree as $item) { | |
1142 | if ($item[$field] == $search) { | |
1143 | return $item; | |
1144 | } | |
1145 | if (!empty($item['children'])) { | |
1146 | $found = self::findInTree($search, $item['children']); | |
1147 | if ($found) { | |
1148 | return $found; | |
1149 | } | |
1150 | } | |
1151 | } | |
1152 | return NULL; | |
1153 | } | |
1154 | ||
6a488035 | 1155 | } |