Merge pull request #16946 from civicrm/5.24
[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 * Filters a list of fieldnames by matching a pattern which may contain * wildcards.
47 *
48 * For fieldnames joined with a dot (e.g. email.contact_id), wildcards are only allowed after the last dot.
49 *
50 * @param string $pattern
51 * @param array $fieldNames
52 * @return array
53 */
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;
59 }));
60 }
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, '.')) {
68 return FALSE;
69 }
70 // Now strip the prefix and compare field name to the pattern
71 return preg_match($search, substr($field, strlen($prefix)));
72 }));
73 }
74
75 }