Merge pull request #17963 from civicrm/5.28
[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 = $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 default:
162 throw new NotImplementedException("Unsupported operator: '$operator' cannot be used with array data");
163 }
164 }
165
166 /**
167 * @param $values
168 * @return array
169 */
170 protected function sortArray($values) {
171 if ($this->getOrderBy()) {
172 usort($values, [$this, 'sortCompare']);
173 }
174 return $values;
175 }
176
177 private function sortCompare($a, $b) {
178 foreach ($this->getOrderBy() as $field => $dir) {
179 $modifier = $dir == 'ASC' ? 1 : -1;
180 if (isset($a[$field]) && isset($b[$field])) {
181 if ($a[$field] == $b[$field]) {
182 continue;
183 }
184 return (strnatcasecmp($a[$field], $b[$field]) * $modifier);
185 }
186 elseif (isset($a[$field]) || isset($b[$field])) {
187 return ((isset($a[$field]) ? 1 : -1) * $modifier);
188 }
189 }
190 return 0;
191 }
192
193 /**
194 * @param $values
195 * @return array
196 */
197 protected function selectArray($values) {
198 if ($this->getSelect() === ['row_count']) {
199 $values = [['row_count' => count($values)]];
200 }
201 elseif ($this->getSelect()) {
202 // Return only fields specified by SELECT
203 foreach ($values as &$value) {
204 $value = array_intersect_key($value, array_flip($this->getSelect()));
205 }
206 }
207 else {
208 // With no SELECT specified, return all values that are keyed by plain field name; omit those with :pseudoconstant suffixes
209 foreach ($values as &$value) {
210 $value = array_filter($value, function($key) {
211 return strpos($key, ':') === FALSE;
212 }, ARRAY_FILTER_USE_KEY);
213 }
214 }
215 return $values;
216 }
217
218 /**
219 * @param $values
220 * @return array
221 */
222 protected function limitArray($values) {
223 if ($this->getOffset() || $this->getLimit()) {
224 $values = array_slice($values, $this->getOffset() ?: 0, $this->getLimit() ?: NULL);
225 }
226 return $values;
227 }
228
229 }