4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 namespace Civi\Api4\Utils
;
18 * Checks if a field is in the Select array or matches a wildcard pattern in the Select array
20 * @param string $field
21 * @param array $selects
24 public static function isFieldSelected($field, $selects) {
25 if (in_array($field, $selects) ||
(in_array('*', $selects) && strpos($field, '.') === FALSE)) {
28 foreach ($selects as $item) {
29 if (strpos($item, '*') !== FALSE && self
::getMatchingFields($item, [$field])) {
37 * Filters a list of fieldnames by matching a pattern which may contain * wildcards.
39 * For fieldnames joined with a dot (e.g. email.contact_id), wildcards are only allowed after the last dot.
41 * @param string $pattern
42 * @param array $fieldNames
45 public static function getMatchingFields($pattern, $fieldNames) {
46 // If the pattern is "select all" then we return all base fields (excluding those with a dot)
47 if ($pattern === '*') {
48 return array_values(array_filter($fieldNames, function($field) {
49 return strpos($field, '.') === FALSE;
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, '.')) {
61 // Now strip the prefix and compare field name to the pattern
62 return preg_match($search, substr($field, strlen($prefix)));