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 +--------------------------------------------------------------------+
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
22 namespace Civi\Api4\Utils
;
27 * Checks if a field is in the Select array or matches a wildcard pattern in the Select array
29 * @param string $field
30 * @param array $selects
33 public static function isFieldSelected($field, $selects) {
34 if (in_array($field, $selects) ||
(in_array('*', $selects) && strpos($field, '.') === FALSE)) {
37 foreach ($selects as $item) {
38 if (strpos($item, '*') !== FALSE && self
::getMatchingFields($item, [$field])) {
46 * Filters a list of fieldnames by matching a pattern which may contain * wildcards.
48 * For fieldnames joined with a dot (e.g. email.contact_id), wildcards are only allowed after the last dot.
50 * @param string $pattern
51 * @param array $fieldNames
54 public static function getMatchingFields($pattern, $fieldNames) {
55 // If the pattern is "select all" then we return all base fields (excluding those with a dot)
56 if ($pattern === '*') {
57 return array_values(array_filter($fieldNames, function($field) {
58 return strpos($field, '.') === FALSE;
61 $dot = strrpos($pattern, '.');
62 $prefix = $dot === FALSE ?
'' : substr($pattern, 0, $dot +
1);
63 $search = $dot === FALSE ?
$pattern : substr($pattern, $dot +
1);
64 $search = '/^' . str_replace('\*', '.*', preg_quote($search, '/')) . '$/';
65 return array_values(array_filter($fieldNames, function($field) use ($search, $prefix) {
66 // Exclude fields that don't have the same join prefix
67 if (($prefix !== '' && strpos($field, $prefix) !== 0) ||
substr_count($prefix, '.') !== substr_count($field, '.')) {
70 // Now strip the prefix and compare field name to the pattern
71 return preg_match($search, substr($field, strlen($prefix)));