Merge pull request #20600 from ixiam/dev#SettingsTraitCheckboxes
[civicrm-core.git] / Civi / Api4 / Utils / SelectUtil.php
CommitLineData
39e0f675
CW
1<?php
2
3/*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
7 | This work is published under the GNU AGPLv3 license with some |
8 | permitted exceptions and without any warranty. For full license |
9 | and copyright information, see https://civicrm.org/licensing |
10 +--------------------------------------------------------------------+
11 */
12
39e0f675
CW
13namespace Civi\Api4\Utils;
14
15class SelectUtil {
16
17 /**
18 * Checks if a field is in the Select array or matches a wildcard pattern in the Select array
19 *
20 * @param string $field
21 * @param array $selects
22 * @return bool
23 */
24 public static function isFieldSelected($field, $selects) {
25 if (in_array($field, $selects) || (in_array('*', $selects) && strpos($field, '.') === FALSE)) {
26 return TRUE;
27 }
28 foreach ($selects as $item) {
29 if (strpos($item, '*') !== FALSE && self::getMatchingFields($item, [$field])) {
30 return TRUE;
31 }
32 }
33 return FALSE;
34 }
35
36 /**
54a08b17
CW
37 * Filters a list of fieldnames by matching a pattern which may contain * wildcards.
38 *
39 * For fieldnames joined with a dot (e.g. email.contact_id), wildcards are only allowed after the last dot.
40 *
39e0f675
CW
41 * @param string $pattern
42 * @param array $fieldNames
43 * @return array
44 */
45 public static function getMatchingFields($pattern, $fieldNames) {
54a08b17 46 // If the pattern is "select all" then we return all base fields (excluding those with a dot)
39e0f675 47 if ($pattern === '*') {
54a08b17
CW
48 return array_values(array_filter($fieldNames, function($field) {
49 return strpos($field, '.') === FALSE;
50 }));
39e0f675 51 }
54a08b17
CW
52 $dot = strrpos($pattern, '.');
53 $prefix = $dot === FALSE ? '' : substr($pattern, 0, $dot + 1);
54 $search = $dot === FALSE ? $pattern : substr($pattern, $dot + 1);
55 $search = '/^' . str_replace('\*', '.*', preg_quote($search, '/')) . '$/';
56 return array_values(array_filter($fieldNames, function($field) use ($search, $prefix) {
57 // Exclude fields that don't have the same join prefix
58 if (($prefix !== '' && strpos($field, $prefix) !== 0) || substr_count($prefix, '.') !== substr_count($field, '.')) {
59 return FALSE;
60 }
61 // Now strip the prefix and compare field name to the pattern
62 return preg_match($search, substr($field, strlen($prefix)));
39e0f675
CW
63 }));
64 }
65
66}