fd515b9a4b712a71b0076538840fa55f6c5c825e
[civicrm-core.git] / Civi / Api4 / Generic / Traits / ArrayQueryActionTrait.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 */
18
19
20 namespace Civi\Api4\Generic\Traits;
21
22 use Civi\API\Exception\NotImplementedException;
23
24 /**
25 * Helper functions for performing api queries on arrays of data.
26 *
27 * @package Civi\Api4\Generic
28 */
29 trait ArrayQueryActionTrait {
30
31 /**
32 * @param array $values
33 * List of all rows to be filtered
34 * @param \Civi\Api4\Generic\Result $result
35 * Object to store result
36 */
37 protected function queryArray($values, $result) {
38 $values = $this->filterArray($values);
39 $values = $this->sortArray($values);
40 // Set total count before applying limit
41 $result->rowCount = count($values);
42 $values = $this->limitArray($values);
43 $values = $this->selectArray($values);
44 $result->exchangeArray($values);
45 }
46
47 /**
48 * @param array $values
49 * @return array
50 */
51 protected function filterArray($values) {
52 if ($this->getWhere()) {
53 $values = array_filter($values, [$this, 'evaluateFilters']);
54 }
55 return array_values($values);
56 }
57
58 /**
59 * @param array $row
60 * @return bool
61 */
62 private function evaluateFilters($row) {
63 $where = array_values($this->getWhere());
64 $allConditions = in_array($where[0], ['AND', 'OR', 'NOT']) ? $where : ['AND', $where];
65 return $this->walkFilters($row, $allConditions);
66 }
67
68 /**
69 * @param array $row
70 * @param array $filters
71 * @return bool
72 * @throws \Civi\API\Exception\NotImplementedException
73 */
74 private function walkFilters($row, $filters) {
75 switch ($filters[0]) {
76 case 'AND':
77 case 'NOT':
78 $result = TRUE;
79 foreach ($filters[1] as $filter) {
80 if (!$this->walkFilters($row, $filter)) {
81 $result = FALSE;
82 break;
83 }
84 }
85 return $result == ($filters[0] == 'AND');
86
87 case 'OR':
88 $result = !count($filters[1]);
89 foreach ($filters[1] as $filter) {
90 if ($this->walkFilters($row, $filter)) {
91 return TRUE;
92 }
93 }
94 return $result;
95
96 default:
97 return $this->filterCompare($row, $filters);
98 }
99 }
100
101 /**
102 * @param array $row
103 * @param array $condition
104 * @return bool
105 * @throws \Civi\API\Exception\NotImplementedException
106 */
107 private function filterCompare($row, $condition) {
108 if (!is_array($condition)) {
109 throw new NotImplementedException('Unexpected where syntax; expecting array.');
110 }
111 $value = $row[$condition[0]] ?? NULL;
112 $operator = $condition[1];
113 $expected = $condition[2] ?? NULL;
114 switch ($operator) {
115 case '=':
116 case '!=':
117 case '<>':
118 $equal = $value == $expected;
119 // PHP is too imprecise about comparing the number 0
120 if ($expected === 0 || $expected === '0') {
121 $equal = ($value === 0 || $value === '0');
122 }
123 // PHP is too imprecise about comparing empty strings
124 if ($expected === '') {
125 $equal = ($value === '');
126 }
127 return $equal == ($operator == '=');
128
129 case 'IS NULL':
130 case 'IS NOT NULL':
131 return is_null($value) == ($operator == 'IS NULL');
132
133 case '>':
134 return $value > $expected;
135
136 case '>=':
137 return $value >= $expected;
138
139 case '<':
140 return $value < $expected;
141
142 case '<=':
143 return $value <= $expected;
144
145 case 'BETWEEN':
146 case 'NOT BETWEEN':
147 $between = ($value >= $expected[0] && $value <= $expected[1]);
148 return $between == ($operator == 'BETWEEN');
149
150 case 'LIKE':
151 case 'NOT LIKE':
152 $pattern = '/^' . str_replace('%', '.*', preg_quote($expected, '/')) . '$/i';
153 return !preg_match($pattern, $value) == ($operator != 'LIKE');
154
155 case 'IN':
156 return in_array($value, $expected);
157
158 case 'NOT IN':
159 return !in_array($value, $expected);
160
161 case 'CONTAINS':
162 if (is_array($value)) {
163 return in_array($expected, $value);
164 }
165 elseif (is_string($value) || is_numeric($value)) {
166 return strpos((string) $value, (string) $expected) !== FALSE;
167 }
168 return $value == $expected;
169
170 default:
171 throw new NotImplementedException("Unsupported operator: '$operator' cannot be used with array data");
172 }
173 }
174
175 /**
176 * @param $values
177 * @return array
178 */
179 protected function sortArray($values) {
180 if ($this->getOrderBy()) {
181 usort($values, [$this, 'sortCompare']);
182 }
183 return $values;
184 }
185
186 private function sortCompare($a, $b) {
187 foreach ($this->getOrderBy() as $field => $dir) {
188 $modifier = $dir == 'ASC' ? 1 : -1;
189 if (isset($a[$field]) && isset($b[$field])) {
190 if ($a[$field] == $b[$field]) {
191 continue;
192 }
193 return (strnatcasecmp($a[$field], $b[$field]) * $modifier);
194 }
195 elseif (isset($a[$field]) || isset($b[$field])) {
196 return ((isset($a[$field]) ? 1 : -1) * $modifier);
197 }
198 }
199 return 0;
200 }
201
202 /**
203 * @param $values
204 * @return array
205 */
206 protected function selectArray($values) {
207 if ($this->getSelect() === ['row_count']) {
208 $values = [['row_count' => count($values)]];
209 }
210 elseif ($this->getSelect()) {
211 // Return only fields specified by SELECT
212 foreach ($values as &$value) {
213 $value = array_intersect_key($value, array_flip($this->getSelect()));
214 }
215 }
216 else {
217 // With no SELECT specified, return all values that are keyed by plain field name; omit those with :pseudoconstant suffixes
218 foreach ($values as &$value) {
219 $value = array_filter($value, function($key) {
220 return strpos($key, ':') === FALSE;
221 }, ARRAY_FILTER_USE_KEY);
222 }
223 }
224 return $values;
225 }
226
227 /**
228 * @param $values
229 * @return array
230 */
231 protected function limitArray($values) {
232 if ($this->getOffset() || $this->getLimit()) {
233 $values = array_slice($values, $this->getOffset() ?: 0, $this->getLimit() ?: NULL);
234 }
235 return $values;
236 }
237
238 }