Merge pull request #16267 from jitendrapurohit/dev-1471
[civicrm-core.git] / Civi / Api4 / Utils / SelectUtil.php
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
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 * $Id$
18 *
19 */
20
21
22 namespace Civi\Api4\Utils;
23
24 class SelectUtil {
25
26 /**
27 * Checks if a field is in the Select array or matches a wildcard pattern in the Select array
28 *
29 * @param string $field
30 * @param array $selects
31 * @return bool
32 */
33 public static function isFieldSelected($field, $selects) {
34 if (in_array($field, $selects) || (in_array('*', $selects) && strpos($field, '.') === FALSE)) {
35 return TRUE;
36 }
37 foreach ($selects as $item) {
38 if (strpos($item, '*') !== FALSE && self::getMatchingFields($item, [$field])) {
39 return TRUE;
40 }
41 }
42 return FALSE;
43 }
44
45 /**
46 * @param string $pattern
47 * @param array $fieldNames
48 * @return array
49 */
50 public static function getMatchingFields($pattern, $fieldNames) {
51 if ($pattern === '*') {
52 return $fieldNames;
53 }
54 $pattern = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/';
55 return array_values(array_filter($fieldNames, function($field) use ($pattern) {
56 return preg_match($pattern, $field);
57 }));
58 }
59
60 }