Merge pull request #19165 from eileenmcnaughton/pdf
[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 $captured++;
101 // Keep going if we have a comma indicating another expression follows
102 if (count($captured) < $limit && substr($arg, 0, 1) === ',') {
103 $arg = ltrim(substr($arg, 1));
104 }
105 else {
106 break;
107 }
108 }
109 return $captured;
110 }
111
112 /**
113 * Scans the beginning of a string for an expression; stops when it hits delimiter
114 *
115 * @param $arg
116 * @return string
117 */
118 private function captureExpression($arg) {
119 $chars = str_split($arg);
120 $isEscaped = $quote = NULL;
121 $item = '';
122 $quotes = ['"', "'"];
123 $brackets = [
124 ')' => '(',
125 ];
126 $enclosures = array_fill_keys($brackets, 0);
127 foreach ($chars as $index => $char) {
128 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
129 // Open quotes - we'll ignore everything inside
130 if (!$quote) {
131 $quote = $char;
132 }
133 // Close quotes
134 elseif ($char === $quote) {
135 $quote = NULL;
136 }
137 }
138 if (!$quote) {
139 // Delineates end of expression
140 if (($char == ',' || $char == ' ') && !array_filter($enclosures)) {
141 return $item;
142 }
143 // Open brackets - we'll ignore delineators inside
144 if (isset($enclosures[$char])) {
145 $enclosures[$char]++;
146 }
147 // Close brackets
148 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
149 $enclosures[$brackets[$char]]--;
150 }
151 }
152 $item .= $char;
153 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
154 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) % 2);
155 }
156 return $item;
157 }
158
159 /**
160 * Render the expression for insertion into the sql query
161 *
162 * @param array $fieldList
163 * @return string
164 */
165 public function render(array $fieldList): string {
166 $output = '';
167 $params = $this->getParams();
168 foreach ($this->args as $index => $arg) {
169 $rendered = $this->renderArg($arg, $params[$index], $fieldList);
170 if (strlen($rendered)) {
171 $output .= (strlen($output) ? ' ' : '') . $rendered;
172 }
173 }
174 return $this->getName() . '(' . $output . ')';
175 }
176
177 /**
178 * @param array $arg
179 * @param array $param
180 * @param array $fieldList
181 * @return string
182 */
183 private function renderArg($arg, $param, $fieldList): string {
184 // Supply api_default
185 if (!isset($arg['prefix']) && !isset($arg['suffix']) && empty($arg['expr']) && !empty($param['api_default'])) {
186 $arg = [
187 'prefix' => $param['api_default']['prefix'] ?? reset($param['prefix']),
188 'expr' => array_map([parent::class, 'convert'], $param['api_default']['expr'] ?? []),
189 'suffix' => $param['api_default']['suffix'] ?? reset($param['suffix']),
190 ];
191 }
192 $rendered = $arg['prefix'] ?? '';
193 foreach ($arg['expr'] ?? [] as $idx => $expr) {
194 if (strlen($rendered) || $idx) {
195 $rendered .= $idx ? ', ' : ' ';
196 }
197 $rendered .= $expr->render($fieldList);
198 }
199 if (isset($arg['suffix'])) {
200 $rendered .= (strlen($rendered) ? ' ' : '') . $arg['suffix'];
201 }
202 return $rendered;
203 }
204
205 /**
206 * @inheritDoc
207 */
208 public function getAlias(): string {
209 return $this->alias ?? $this->getName() . ':' . implode('_', $this->fields);
210 }
211
212 /**
213 * Get the name of this sql function.
214 * @return string
215 */
216 public static function getName(): string {
217 $className = static::class;
218 return substr($className, strrpos($className, 'SqlFunction') + 11);
219 }
220
221 /**
222 * Get the param metadata for this sql function.
223 * @return array
224 */
225 public static function getParams(): array {
226 $params = [];
227 foreach (static::$params as $param) {
228 // Merge in defaults to ensure each param has these properties
229 $params[] = $param + [
230 'prefix' => [],
231 'expr' => 1,
232 'suffix' => [],
233 'optional' => FALSE,
234 'must_be' => [],
235 'cant_be' => ['SqlWild'],
236 'api_default' => NULL,
237 ];
238 }
239 return $params;
240 }
241
242 /**
243 * Get the arguments passed to this sql function instance.
244 * @return array[]
245 */
246 public function getArgs(): array {
247 return $this->args;
248 }
249
250 /**
251 * @return string
252 */
253 public static function getCategory(): string {
254 return static::$category;
255 }
256
257 /**
258 * @return string
259 */
260 abstract public static function getTitle(): string;
261
262 }