Merge pull request #20602 from ixiam/dev#PreserveActivityTabFilter
[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 static $params = [];
25
26 /**
27 * @var array[]
28 */
29 protected $args = [];
30
31 /**
32 * Used for categorizing functions in the UI
33 *
34 * @var string
35 */
36 protected static $category;
37
38 const CATEGORY_AGGREGATE = 'aggregate',
39 CATEGORY_COMPARISON = 'comparison',
40 CATEGORY_DATE = 'date',
41 CATEGORY_MATH = 'math',
42 CATEGORY_STRING = 'string';
43
44 /**
45 * Parse the argument string into an array of function arguments
46 */
47 protected function initialize() {
48 $arg = trim(substr($this->expr, strpos($this->expr, '(') + 1, -1));
49 foreach ($this->getParams() as $idx => $param) {
50 $prefix = $this->captureKeyword($param['prefix'], $arg);
51 $this->args[$idx] = [
52 'prefix' => $prefix,
53 'expr' => [],
54 'suffix' => NULL,
55 ];
56 if ($param['expr'] && isset($prefix) || in_array('', $param['prefix']) || !$param['optional']) {
57 $this->args[$idx]['expr'] = $this->captureExpressions($arg, $param['expr'], $param['must_be'], $param['cant_be']);
58 $this->args[$idx]['suffix'] = $this->captureKeyword($param['suffix'], $arg);
59 }
60 }
61 }
62
63 /**
64 * Shift a keyword off the beginning of the argument string and return it.
65 *
66 * @param array $keywords
67 * Whitelist of keywords
68 * @param string $arg
69 * @return mixed|null
70 */
71 private function captureKeyword($keywords, &$arg) {
72 foreach (array_filter($keywords) as $key) {
73 if (strpos($arg, $key . ' ') === 0) {
74 $arg = ltrim(substr($arg, strlen($key)));
75 return $key;
76 }
77 }
78 return NULL;
79 }
80
81 /**
82 * Shifts 0 or more expressions off the argument string and returns them
83 *
84 * @param string $arg
85 * @param int $limit
86 * @param array $mustBe
87 * @param array $cantBe
88 * @return array
89 * @throws \API_Exception
90 */
91 private function captureExpressions(&$arg, $limit, $mustBe, $cantBe) {
92 $captured = [];
93 $arg = ltrim($arg);
94 while ($arg) {
95 $item = $this->captureExpression($arg);
96 $arg = ltrim(substr($arg, strlen($item)));
97 $expr = SqlExpression::convert($item, FALSE, $mustBe, $cantBe);
98 $this->fields = array_merge($this->fields, $expr->getFields());
99 $captured[] = $expr;
100 // Keep going if we have a comma indicating another expression follows
101 if (count($captured) < $limit && substr($arg, 0, 1) === ',') {
102 $arg = ltrim(substr($arg, 1));
103 }
104 else {
105 break;
106 }
107 }
108 return $captured;
109 }
110
111 /**
112 * Scans the beginning of a string for an expression; stops when it hits delimiter
113 *
114 * @param $arg
115 * @return string
116 */
117 private function captureExpression($arg) {
118 $chars = str_split($arg);
119 $isEscaped = $quote = NULL;
120 $item = '';
121 $quotes = ['"', "'"];
122 $brackets = [
123 ')' => '(',
124 ];
125 $enclosures = array_fill_keys($brackets, 0);
126 foreach ($chars as $index => $char) {
127 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
128 // Open quotes - we'll ignore everything inside
129 if (!$quote) {
130 $quote = $char;
131 }
132 // Close quotes
133 elseif ($char === $quote) {
134 $quote = NULL;
135 }
136 }
137 if (!$quote) {
138 // Delineates end of expression
139 if (($char == ',' || $char == ' ') && !array_filter($enclosures)) {
140 return $item;
141 }
142 // Open brackets - we'll ignore delineators inside
143 if (isset($enclosures[$char])) {
144 $enclosures[$char]++;
145 }
146 // Close brackets
147 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
148 $enclosures[$brackets[$char]]--;
149 }
150 }
151 $item .= $char;
152 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
153 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) % 2);
154 }
155 return $item;
156 }
157
158 /**
159 * Render the expression for insertion into the sql query
160 *
161 * @param array $fieldList
162 * @return string
163 */
164 public function render(array $fieldList): string {
165 $output = '';
166 $params = $this->getParams();
167 foreach ($this->args as $index => $arg) {
168 $rendered = $this->renderArg($arg, $params[$index], $fieldList);
169 if (strlen($rendered)) {
170 $output .= (strlen($output) ? ' ' : '') . $rendered;
171 }
172 }
173 return $this->getName() . '(' . $output . ')';
174 }
175
176 /**
177 * @param array $arg
178 * @param array $param
179 * @param array $fieldList
180 * @return string
181 */
182 private function renderArg($arg, $param, $fieldList): string {
183 // Supply api_default
184 if (!isset($arg['prefix']) && !isset($arg['suffix']) && empty($arg['expr']) && !empty($param['api_default'])) {
185 $arg = [
186 'prefix' => $param['api_default']['prefix'] ?? reset($param['prefix']),
187 'expr' => array_map([parent::class, 'convert'], $param['api_default']['expr'] ?? []),
188 'suffix' => $param['api_default']['suffix'] ?? reset($param['suffix']),
189 ];
190 }
191 $rendered = $arg['prefix'] ?? '';
192 foreach ($arg['expr'] ?? [] as $idx => $expr) {
193 if (strlen($rendered) || $idx) {
194 $rendered .= $idx ? ', ' : ' ';
195 }
196 $rendered .= $expr->render($fieldList);
197 }
198 if (isset($arg['suffix'])) {
199 $rendered .= (strlen($rendered) ? ' ' : '') . $arg['suffix'];
200 }
201 return $rendered;
202 }
203
204 /**
205 * @inheritDoc
206 */
207 public function getAlias(): string {
208 return $this->alias ?? $this->getName() . ':' . implode('_', $this->fields);
209 }
210
211 /**
212 * Get the name of this sql function.
213 * @return string
214 */
215 public static function getName(): string {
216 $className = static::class;
217 return substr($className, strrpos($className, 'SqlFunction') + 11);
218 }
219
220 /**
221 * Get the param metadata for this sql function.
222 * @return array
223 */
224 public static function getParams(): array {
225 $params = [];
226 foreach (static::$params as $param) {
227 // Merge in defaults to ensure each param has these properties
228 $params[] = $param + [
229 'prefix' => [],
230 'expr' => 1,
231 'suffix' => [],
232 'optional' => FALSE,
233 'must_be' => [],
234 'cant_be' => ['SqlWild'],
235 'api_default' => NULL,
236 ];
237 }
238 return $params;
239 }
240
241 /**
242 * Get the arguments passed to this sql function instance.
243 * @return array[]
244 */
245 public function getArgs(): array {
246 return $this->args;
247 }
248
249 /**
250 * @return string
251 */
252 public static function getCategory(): string {
253 return static::$category;
254 }
255
256 /**
257 * @return string
258 */
259 abstract public static function getTitle(): string;
260
261 }