3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
12 namespace Civi\Api4\Query
;
15 * Base class for all Sql functions.
17 * @package Civi\Api4\Query
19 abstract class SqlFunction
extends SqlExpression
{
27 * Used for categorizing functions in the UI
31 protected static $category;
33 const CATEGORY_AGGREGATE
= 'aggregate',
34 CATEGORY_COMPARISON
= 'comparison',
35 CATEGORY_DATE
= 'date',
36 CATEGORY_MATH
= 'math',
37 CATEGORY_STRING
= 'string';
40 * Parse the argument string into an array of function arguments
42 protected function initialize() {
43 $arg = trim(substr($this->expr
, strpos($this->expr
, '(') +
1, -1));
44 foreach ($this->getParams() as $idx => $param) {
46 if ($param['prefix']) {
47 $prefix = $this->captureKeyword([$param['prefix']], $arg);
49 if (!$prefix && isset($param['api_default'])) {
51 'prefix' => $param['api_default']['prefix'] ??
[$param['prefix']],
52 'expr' => array_map([parent
::class, 'convert'], $param['api_default']['expr']),
53 'suffix' => $param['api_default']['suffix'] ??
[],
57 if (!$prefix && !$param['optional']) {
58 throw new \
API_Exception("Missing {$param['prefix']} for SQL function " . static::getName());
61 elseif ($param['flag_before']) {
62 $prefix = $this->captureKeyword(array_keys($param['flag_before']), $arg);
65 'prefix' => (array) $prefix,
69 if ($param['max_expr'] && (!$param['prefix'] ||
$param['prefix'] === $prefix)) {
70 $exprs = $this->captureExpressions($arg, $param['must_be'], $param['cant_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());
74 $this->args
[$idx]['expr'] = $exprs;
76 $this->args
[$idx]['suffix'] = (array) $this->captureKeyword(array_keys($param['flag_after']), $arg);
82 * Change $dataType according to output of function
84 * @see \Civi\Api4\Utils\FormattingUtil::formatOutputValues
85 * @param string $value
86 * @param string $dataType
89 public function formatOutputValue($value, &$dataType) {
90 if (static::$dataType) {
91 $dataType = static::$dataType;
97 * Shift a keyword off the beginning of the argument string and return it.
99 * @param array $keywords
100 * Whitelist of keywords
104 private function captureKeyword($keywords, &$arg) {
105 foreach ($keywords as $key) {
106 if (strpos($arg, $key . ' ') === 0) {
107 $arg = ltrim(substr($arg, strlen($key)));
115 * Shifts 0 or more expressions off the argument string and returns them
118 * @param array $mustBe
119 * @param array $cantBe
121 * @throws \API_Exception
123 private function captureExpressions(&$arg, $mustBe, $cantBe) {
127 $item = $this->captureExpression($arg);
128 $arg = ltrim(substr($arg, strlen($item)));
129 $expr = SqlExpression
::convert($item, FALSE, $mustBe, $cantBe);
130 $this->fields
= array_merge($this->fields
, $expr->getFields());
132 // Keep going if we have a comma indicating another expression follows
133 if (substr($arg, 0, 1) === ',') {
134 $arg = ltrim(substr($arg, 1));
144 * Scans the beginning of a string for an expression; stops when it hits delimiter
149 private function captureExpression($arg) {
150 $chars = str_split($arg);
151 $isEscaped = $quote = NULL;
153 $quotes = ['"', "'"];
157 $enclosures = array_fill_keys($brackets, 0);
158 foreach ($chars as $index => $char) {
159 if (!$isEscaped && in_array($char, $quotes, TRUE)) {
160 // Open quotes - we'll ignore everything inside
165 elseif ($char === $quote) {
170 // Delineates end of expression
171 if (($char == ',' ||
$char == ' ') && !array_filter($enclosures)) {
174 // Open brackets - we'll ignore delineators inside
175 if (isset($enclosures[$char])) {
176 $enclosures[$char]++
;
179 if (isset($brackets[$char]) && $enclosures[$brackets[$char]]) {
180 $enclosures[$brackets[$char]]--;
184 // We are escaping the next char if this is a backslash not preceded by an odd number of backslashes
185 $isEscaped = $char === '\\' && ((strlen($item) - strlen(rtrim($item, '\\'))) %
2);
191 * Render the expression for insertion into the sql query
193 * @param array $fieldList
196 public function render(array $fieldList): string {
198 $params = $this->getParams();
199 foreach ($this->args
as $index => $arg) {
200 $rendered = $this->renderArg($arg, $params[$index], $fieldList);
201 if (strlen($rendered)) {
202 $output .= (strlen($output) ?
' ' : '') . $rendered;
205 return $this->getName() . '(' . $output . ')';
210 * @param array $param
211 * @param array $fieldList
214 private function renderArg($arg, $param, $fieldList): string {
215 $rendered = implode(' ', $arg['prefix']);
216 foreach ($arg['expr'] ??
[] as $idx => $expr) {
217 if (strlen($rendered) ||
$idx) {
218 $rendered .= $idx ?
', ' : ' ';
220 $rendered .= $expr->render($fieldList);
222 if ($arg['suffix']) {
223 $rendered .= (strlen($rendered) ?
' ' : '') . implode(' ', $arg['suffix']);
231 public function getAlias(): string {
232 return $this->alias ??
$this->getName() . ':' . implode('_', $this->fields
);
236 * Get the name of this sql function.
239 public static function getName(): string {
240 $className = static::class;
241 return substr($className, strrpos($className, 'SqlFunction') +
11);
245 * Get the param metadata for this sql function.
248 final public static function getParams(): array {
250 foreach (static::params() as $param) {
251 // Merge in defaults to ensure each param has these properties
252 $params[] = $param +
[
260 'cant_be' => ['SqlWild'],
261 'api_default' => NULL,
267 abstract protected static function params(): array;
270 * Get the arguments passed to this sql function instance.
273 public function getArgs(): array {
280 public static function getCategory(): string {
281 return static::$category;
287 abstract public static function getTitle(): string;