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 * Numeric sql expression
17 class SqlEquation
extends SqlExpression
{
27 public static $arithmeticOperators = [
37 public static $comparisonOperators = [
51 protected function initialize() {
52 $arg = trim(substr($this->expr
, strpos($this->expr
, '(') +
1, -1));
53 $permitted = ['SqlField', 'SqlString', 'SqlNumber', 'SqlNull'];
54 $operators = array_merge(self
::$arithmeticOperators, self
::$comparisonOperators);
55 while (strlen($arg)) {
56 $this->args
= array_merge($this->args
, $this->captureExpressions($arg, $permitted, 1));
57 $op = $this->captureKeyword($operators, $arg);
65 * Render the expression for insertion into the sql query
67 * @param array $fieldList
70 public function render(array $fieldList): string {
72 foreach ($this->args
as $arg) {
74 if (is_string($arg)) {
77 // Surround fields with COALESCE to handle null values
78 elseif (is_a($arg, SqlField
::class)) {
79 $output[] = 'COALESCE(' . $arg->render($fieldList) . ', 0)';
82 $output[] = $arg->render($fieldList);
85 return '(' . implode(' ', $output) . ')';
89 * Returns the alias to use for SELECT AS.
93 public function getAlias(): string {
94 return $this->alias ?? \CRM_Utils_String
::munge(trim($this->expr
, ' ()'), '_', 256);
98 * Change $dataType according to operator used in equation
100 * @see \Civi\Api4\Utils\FormattingUtil::formatOutputValues
101 * @param string $value
102 * @param string $dataType
105 public function formatOutputValue($value, &$dataType) {
106 foreach (self
::$comparisonOperators as $op) {
107 if (strpos($this->expr
, " $op ")) {
108 $dataType = 'Boolean';
111 foreach (self
::$arithmeticOperators as $op) {
112 if (strpos($this->expr
, " $op ")) {
119 public static function getTitle(): string {
120 return ts('Equation');