Merge pull request #21152 from eileenmcnaughton/batch_order
[civicrm-core.git] / Civi / Api4 / Query / SqlFunction.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\Api4\Query;
13
14 /**
15 * Base class for all Sql functions.
16 *
17 * @package Civi\Api4\Query
18 */
19 abstract class SqlFunction extends SqlExpression {
20
21 /**
22 * @var array[]
23 */
24 protected $args = [];
25
26 /**
27 * Used for categorizing functions in the UI
28 *
29 * @var string
30 */
31 protected static $category;
32
33 const CATEGORY_AGGREGATE = 'aggregate',
34 CATEGORY_COMPARISON = 'comparison',
35 CATEGORY_DATE = 'date',
36 CATEGORY_MATH = 'math',
37 CATEGORY_STRING = 'string';
38
39 /**
40 * Parse the argument string into an array of function arguments
41 */
42 protected function initialize() {
43 $arg = trim(substr($this->expr, strpos($this->expr, '(') + 1, -1));
44 foreach ($this->getParams() as $idx => $param) {
45 $prefix = NULL;
46 if ($param['name']) {
47 $prefix = $this->captureKeyword([$param['name']], $arg);
48 // Supply api_default
49 if (!$prefix && isset($param['api_default'])) {
50 $this->args[$idx] = [
51 'prefix' => [$param['name']],
52 'expr' => array_map([parent::class, 'convert'], $param['api_default']['expr']),
53 'suffix' => [],
54 ];
55 continue;
56 }
57 if (!$prefix && !$param['optional']) {
58 throw new \API_Exception("Missing {$param['name']} for SQL function " . static::getName());
59 }
60 }
61 elseif ($param['flag_before']) {
62 $prefix = $this->captureKeyword(array_keys($param['flag_before']), $arg);
63 }
64 $this->args[$idx] = [
65 'prefix' => (array) $prefix,
66 'expr' => [],
67 'suffix' => [],
68 ];
69 if ($param['max_expr'] && (!$param['name'] || $param['name'] === $prefix)) {
70 $exprs = $this->captureExpressions($arg, $param['must_be']);
71 if (count($exprs) < $param['min_expr'] || count($exprs) > $param['max_expr']) {
72 throw new \API_Exception('Incorrect number of arguments for SQL function ' . static::getName());
73 }
74 $this->args[$idx]['expr'] = $exprs;
75
76 $this->args[$idx]['suffix'] = (array) $this->captureKeyword(array_keys($param['flag_after']), $arg);
77 }
78 }
79 }
80
81 /**
82 * Change $dataType according to output of function
83 *
84 * @see \Civi\Api4\Utils\FormattingUtil::formatOutputValues
85 * @param string $value
86 * @param string $dataType
87 * @return string
88 */
89 public function formatOutputValue($value, &$dataType) {
90 if (static::$dataType) {
91 $dataType = static::$dataType;
92 }
93 return $value;
94 }
95
96 /**
97 * Shift a keyword off the beginning of the argument string and return it.
98 *
99 * @param array $keywords
100 * Whitelist of keywords
101 * @param string $arg
102 * @return mixed|null
103 */
104 private function captureKeyword($keywords, &$arg) {
105 foreach ($keywords as $key) {
106 if (strpos($arg, $key . ' ') === 0) {
107 $arg = ltrim(substr($arg, strlen($key)));
108 return $key;
109 }
110 }
111 return NULL;
112 }
113
114 /**
115 * Shifts 0 or more expressions off the argument string and returns them
116 *
117 * @param string $arg
118 * @param array $mustBe
119 * @return array
120 * @throws \API_Exception
121 */
122 private function captureExpressions(&$arg, $mustBe) {
123 $captured = [];
124 $arg = ltrim($arg);
125 while ($arg) {
126 $item = $this->captureExpression($arg);
127 $arg = ltrim(substr($arg, strlen($item)));
128 $expr = SqlExpression::convert($item, FALSE, $mustBe);
129 $this->fields = array_merge($this->fields, $expr->getFields());
130 $captured[] = $expr;
131 // Keep going if we have a comma indicating another expression follows
132 if (substr($arg, 0, 1) === ',') {
133 $arg = ltrim(substr($arg, 1));
134 }
135 else {
136 break;
137 }
138 }
139 return $captured;
140 }
141
142 /**
143 * Scans the beginning of a string for an expression; stops when it hits delimiter
144 *
145 * @param $arg
146 * @return string
147 */
148 private function captureExpression($arg) {
149 $isEscaped = $quote = NULL;
150 $item = '';
151 $quotes = ['"', "'"];
152 $brackets = [
153 ')' => '(',
154 ];
155 $enclosures = array_fill_keys($brackets, 0);
156 foreach (str_split($arg) as $char) {
157 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
158 // Open quotes - we'll ignore everything inside
159 if (!$quote) {
160 $quote = $char;
161 }
162 // Close quotes
163 elseif ($char === $quote) {
164 $quote = NULL;
165 }
166 }
167 if (!$quote) {
168 // Delineates end of expression
169 if (($char == ',' || $char == ' ') && !array_filter($enclosures)) {
170 return $item;
171 }
172 // Open brackets - we'll ignore delineators inside
173 if (isset($enclosures[$char])) {
174 $enclosures[$char]++;
175 }
176 // Close brackets
177 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
178 $enclosures[$brackets[$char]]--;
179 }
180 }
181 $item .= $char;
182 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
183 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) % 2);
184 }
185 return $item;
186 }
187
188 /**
189 * Render the expression for insertion into the sql query
190 *
191 * @param array $fieldList
192 * @return string
193 */
194 public function render(array $fieldList): string {
195 $output = '';
196 foreach ($this->args as $arg) {
197 $rendered = $this->renderArg($arg, $fieldList);
198 if (strlen($rendered)) {
199 $output .= (strlen($output) ? ' ' : '') . $rendered;
200 }
201 }
202 return $this->getName() . '(' . $output . ')';
203 }
204
205 /**
206 * @param array $arg
207 * @param array $fieldList
208 * @return string
209 */
210 private function renderArg($arg, $fieldList): string {
211 $rendered = implode(' ', $arg['prefix']);
212 foreach ($arg['expr'] ?? [] as $idx => $expr) {
213 if (strlen($rendered) || $idx) {
214 $rendered .= $idx ? ', ' : ' ';
215 }
216 $rendered .= $expr->render($fieldList);
217 }
218 if ($arg['suffix']) {
219 $rendered .= (strlen($rendered) ? ' ' : '') . implode(' ', $arg['suffix']);
220 }
221 return $rendered;
222 }
223
224 /**
225 * @inheritDoc
226 */
227 public function getAlias(): string {
228 return $this->alias ?? $this->getName() . ':' . implode('_', $this->fields);
229 }
230
231 /**
232 * Get the name of this sql function.
233 * @return string
234 */
235 public static function getName(): string {
236 $className = static::class;
237 return substr($className, strrpos($className, 'SqlFunction') + 11);
238 }
239
240 /**
241 * Get the param metadata for this sql function.
242 * @return array
243 */
244 final public static function getParams(): array {
245 $params = [];
246 foreach (static::params() as $param) {
247 // Merge in defaults to ensure each param has these properties
248 $params[] = $param + [
249 'name' => NULL,
250 'min_expr' => 1,
251 'max_expr' => 1,
252 'flag_before' => [],
253 'flag_after' => [],
254 'optional' => FALSE,
255 'must_be' => ['SqlField', 'SqlFunction', 'SqlString', 'SqlNumber', 'SqlNull'],
256 'api_default' => NULL,
257 ];
258 }
259 return $params;
260 }
261
262 abstract protected static function params(): array;
263
264 /**
265 * Get the arguments passed to this sql function instance.
266 * @return array[]
267 */
268 public function getArgs(): array {
269 return $this->args;
270 }
271
272 /**
273 * @return string
274 */
275 public static function getCategory(): string {
276 return static::$category;
277 }
278
279 /**
280 * @return string
281 */
282 abstract public static function getTitle(): string;
283
284 /**
285 * @return string
286 */
287 abstract public static function getDescription(): string;
288
289 }