ILIAS  release_5-1 Revision 5.0.0-5477-g43f3e3fab5f
ilDclExpressionParser Class Reference

Class ilDclExpressionParser. More...

+ Collaboration diagram for ilDclExpressionParser:

Public Member Functions

 __construct ($expression, ilDataCollectionRecord $record, ilDataCollectionField $field)
 
 parse ()
 Parse expression and return result. More...
 

Static Public Member Functions

static getOperators ()
 
static getFunctions ()
 

Data Fields

const N_DECIMALS = 1
 
const SCIENTIFIC_NOTATION_UPPER = 1000000000000
 
const SCIENTIFIC_NOTATION_LOWER = 0.000000001
 

Protected Member Functions

 formatScientific ($value)
 
 isMathToken ($token)
 Check if a given token is a math expression. More...
 
 calculateFunctions ($token)
 Execute any math functions inside a token. More...
 
 getFunctionArgs ($index, array $data)
 Helper method to return the function and its arguments from a preg_replace_all $result array. More...
 
 substituteFieldValues (array $tokens)
 Given an array of tokens, replace each token that is a placeholder (e.g. More...
 
 parseMath (array $tokens)
 Parse a math expression. More...
 
 calculateFunction ($function, array $args=array())
 Calculate a function with its arguments. More...
 
 calculate ($operator, $left, $right)
 

Protected Attributes

 $record
 
 $field
 
 $expression
 

Static Protected Attributes

static $operators
 
static $cache_tokens = array()
 
static $cache_fields = array()
 
static $cache_math_tokens = array()
 
static $cache_math_function_tokens = array()
 
static $functions
 

Detailed Description

Constructor & Destructor Documentation

◆ __construct()

ilDclExpressionParser::__construct (   $expression,
ilDataCollectionRecord  $record,
ilDataCollectionField  $field 
)
Parameters
string$expression
ilDataCollectionRecord$record
ilDataCollectionField$field

Definition at line 68 of file class.ilDclExpressionParser.php.

References $expression, $field, and $record.

Member Function Documentation

◆ calculate()

ilDclExpressionParser::calculate (   $operator,
  $left,
  $right 
)
protected
Parameters
string$operator
float$left
float$right
Returns
float|number
Exceptions
ilException

Definition at line 416 of file class.ilDclExpressionParser.php.

416 {
417 switch ($operator) {
418 case '+':
419 $result = $left + $right;
420 break;
421 case '-':
422 $result = $left - $right;
423 break;
424 case '*':
425 $result = $left * $right;
426 break;
427 case '/':
428 $result = ($right == 0) ? 0 : $left / $right;
429 break;
430 case '^':
431 $result = pow($left, $right);
432 break;
433 default:
434 throw new ilException("Unrecognized operator '$operator'");
435 }
436
437 return $result;
438 }
$result
Base class for ILIAS Exception handling.

References $result.

Referenced by parseMath().

+ Here is the caller graph for this function:

◆ calculateFunction()

ilDclExpressionParser::calculateFunction (   $function,
array  $args = array() 
)
protected

Calculate a function with its arguments.

Parameters
$functionFunction name to calculate
array$argsArguments of function
Returns
float|int|number
Exceptions
ilException

Definition at line 390 of file class.ilDclExpressionParser.php.

390 {
391 switch ($function) {
392 case 'AVERAGE':
393 $count = count($args);
394
395 return ($count) ? array_sum($args) / $count : 0;
396 case 'SUM':
397 return array_sum($args);
398 case 'MIN':
399 return min($args);
400 case 'MAX':
401 return max($args);
402 default:
403 throw new ilException("Unrecognized function '$function'");
404 }
405 }

Referenced by calculateFunctions().

+ Here is the caller graph for this function:

◆ calculateFunctions()

ilDclExpressionParser::calculateFunctions (   $token)
protected

Execute any math functions inside a token.

Parameters
string$token
Returns
string

Definition at line 187 of file class.ilDclExpressionParser.php.

187 {
188 if (isset(self::$cache_math_function_tokens[$this->field->getId()][$token])) {
189 $result = self::$cache_math_function_tokens[$this->field->getId()][$token];
190 if ($result === false) {
191 return $token;
192 }
193 } else {
194 $pattern = '#';
195 foreach (self::getFunctions() as $function) {
196 $pattern .= "($function)\\(([^)]*)\\)|";
197 }
198 if (!preg_match_all(rtrim($pattern, '|') . '#', $token, $result)) {
199 // No functions found inside token, just return token again
200 self::$cache_math_function_tokens[$this->field->getId()][$token] = false;
201
202 return $token;
203 }
204 }
205 // Function found inside token, calculate!
206 foreach ($result[0] as $k => $to_replace) {
207 $function_args = $this->getFunctionArgs($k, $result);
208 $function = $function_args['function'];
209 $args = $this->substituteFieldValues($function_args['args']);
210 $token = str_replace($to_replace, $this->calculateFunction($function, $args), $token);
211 }
212
213 return $token;
214 }
substituteFieldValues(array $tokens)
Given an array of tokens, replace each token that is a placeholder (e.g.
getFunctionArgs($index, array $data)
Helper method to return the function and its arguments from a preg_replace_all $result array.
calculateFunction($function, array $args=array())
Calculate a function with its arguments.

References $result, calculateFunction(), getFunctionArgs(), and substituteFieldValues().

Referenced by parse().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ formatScientific()

ilDclExpressionParser::formatScientific (   $value)
protected
Parameters
$value
Returns
string

Definition at line 125 of file class.ilDclExpressionParser.php.

125 {
126 if (abs($value) >= self::SCIENTIFIC_NOTATION_UPPER) {
127 return sprintf("%e", $value);
128 }
129 if (abs($value) <= self::SCIENTIFIC_NOTATION_LOWER && $value != 0 ) {
130 return sprintf("%e", $value);
131 }
132 if (is_float($value)) {
133 return $value;
134 }
135
136 return $value;
137 }

Referenced by parse().

+ Here is the caller graph for this function:

◆ getFunctionArgs()

ilDclExpressionParser::getFunctionArgs (   $index,
array  $data 
)
protected

Helper method to return the function and its arguments from a preg_replace_all $result array.

Parameters
$index
array$data
Returns
array

Definition at line 225 of file class.ilDclExpressionParser.php.

225 {
226 $return = array(
227 'function' => '',
228 'args' => array(),
229 );
230 for ($i = 1; $i < count($data); $i ++) {
231 $_data = $data[$i];
232 if ($_data[$index]) {
233 $function = $_data[$index];
234 $args = explode(';', $data[$i + 1][$index]);
235 $return['function'] = $function;
236 $return['args'] = $args;
237 break;
238 }
239 }
240
241 return $return;
242 }
$data

References $data.

Referenced by calculateFunctions().

+ Here is the caller graph for this function:

◆ getFunctions()

static ilDclExpressionParser::getFunctions ( )
static
Returns
array

Definition at line 151 of file class.ilDclExpressionParser.php.

151 {
152 return self::$functions;
153 }

References $functions.

Referenced by ilDataCollectionFieldEditGUI\initForm(), and isMathToken().

+ Here is the caller graph for this function:

◆ getOperators()

static ilDclExpressionParser::getOperators ( )
static
Returns
array

Definition at line 143 of file class.ilDclExpressionParser.php.

143 {
144 return self::$operators;
145 }

References $operators.

Referenced by ilDclTokenizer\getMathTokens(), and ilDataCollectionFieldEditGUI\initForm().

+ Here is the caller graph for this function:

◆ isMathToken()

ilDclExpressionParser::isMathToken (   $token)
protected

Check if a given token is a math expression.

Parameters
string$token
Returns
bool

Definition at line 163 of file class.ilDclExpressionParser.php.

163 {
164 if (isset(self::$cache_math_tokens[$this->field->getId()][$token])) {
165 return self::$cache_math_tokens[$this->field->getId()][$token];
166 } else {
167 if (strpos($token, '"') === 0) {
168 return false;
169 }
170 $operators = array_keys(self::getOperators());
172 $result = (bool)preg_match('#(\\' . implode("|\\", $operators) . '|' . implode('|', $functions) . ')#', $token);
173 self::$cache_math_tokens[$this->field->getId()][$token] = $result;
174
175 return $result;
176 }
177 }

References $functions, $operators, $result, and getFunctions().

Referenced by parse().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ parse()

ilDclExpressionParser::parse ( )

Parse expression and return result.

This method loops the tokens and checks if Token is of type string or math. Concatenates results to produce resulting string of parsed expression.

Exceptions
ilException
Returns
string

Definition at line 83 of file class.ilDclExpressionParser.php.

83 {
84 if (isset(self::$cache_tokens[$this->field->getId()])) {
85 $tokens = self::$cache_tokens[$this->field->getId()];
86 } else {
87 $tokens = ilDclTokenizer::getTokens($this->expression);
88 self::$cache_tokens[$this->field->getId()] = $tokens;
89 }
90 // ilUtil::sendInfo( "<pre>" . print_r($tokens, 1) . "</pre>");
91 $parsed = '';
92 foreach ($tokens as $token) {
93 if (empty($token)) {
94 continue;
95 }
96 if ($this->isMathToken($token)) {
97 $token = $this->calculateFunctions($token);
98 $math_tokens = ilDclTokenizer::getMathTokens($token);
99 $value = $this->parseMath($this->substituteFieldValues($math_tokens));
100
101 $value = $this->formatScientific($value);
102
103 $parsed .= $value;
104 } else {
105 // Token is a string, either a field placeholder [[Field name]] or a string starting with "
106 if (strpos($token, '"') === 0) {
107 $parsed .= strip_tags(trim($token, '"'));
108 } elseif (strpos($token, '[[') === 0) {
109 $parsed .= trim(strip_tags($this->substituteFieldValue($token)));
110 } else {
111 throw new ilException("Unrecognized string token: '$token'");
112 }
113 }
114 }
115
116 return $parsed;
117 }
calculateFunctions($token)
Execute any math functions inside a token.
parseMath(array $tokens)
Parse a math expression.
isMathToken($token)
Check if a given token is a math expression.
static getMathTokens($math_expression)
Generate tokens for a math expression.
static getTokens($expression)
Split expression by & (ignore escaped &-symbols with backslash)

References calculateFunctions(), formatScientific(), ilDclTokenizer\getMathTokens(), ilDclTokenizer\getTokens(), isMathToken(), parseMath(), and substituteFieldValues().

+ Here is the call graph for this function:

◆ parseMath()

ilDclExpressionParser::parseMath ( array  $tokens)
protected

Parse a math expression.

Parameters
array$tokens
Returns
null
Exceptions
Exception

Definition at line 309 of file class.ilDclExpressionParser.php.

309 {
311 $precedence = 0;
312 $stack = new ilDclStack();
313 $precedences = new ilDclStack();
314 $in_bracket = false;
315 foreach ($tokens as $token) {
316 if (empty($token) OR is_null($token)) {
317 $token = 0;
318 }
319 if (is_numeric($token) OR $token === '(') {
320 $stack->push($token);
321 if ($token === '(') {
322 $in_bracket = true;
323 }
324 } elseif (in_array($token, array_keys($operators))) {
325 $new_precedence = $operators[$token]['precedence'];
326 if ($new_precedence > $precedence || $in_bracket) {
327 // Precedence of operator is higher, push operator on stack
328 $stack->push($token);
329 $precedences->push($new_precedence);
330 $precedence = $new_precedence;
331 } else {
332 // Precedence is equal or lower, calculate result on stack
333 while ($new_precedence <= $precedence && $stack->count() > 1) {
334 $right = (float)$stack->pop();
335 $operator = $stack->pop();
336 $left = (float)$stack->pop();
337 $result = $this->calculate($operator, $left, $right);
338 $stack->push($result);
339 $precedence = $precedences->pop();
340 }
341 $stack->push($token);
342 $precedence = $new_precedence;
343 $precedences->push($new_precedence);
344 }
345 } elseif ($token === ')') {
346 // Need to calculate stack back to opening bracket
347 $_tokens = array();
348 $elem = $stack->pop();
349 while ($elem !== '(' && !$stack->isEmpty()) {
350 $_tokens[] = $elem;
351 $elem = $stack->pop();
352 }
353 // Get result within brackets recursive and push to stack
354 $stack->push($this->parseMath(array_reverse($_tokens)));
355 $in_bracket = false;
356 } else {
357 throw new ilException("Unrecognized token '$token'");
358 }
359 // $stack->debug();
360 }
361 // If one element is left on stack, we are done. Otherwise calculate
362 if ($stack->count() == 1) {
363 $result = $stack->pop();
364
365 return (ctype_digit((string)$result)) ? $result : number_format($result, self::N_DECIMALS, '.', "'");
366 } else {
367
368 while ($stack->count() >= 2) {
369 $right = $stack->pop();
370 $operator = $stack->pop();
371 $left = $stack->count() ? $stack->pop() : 0;
372 $stack->push($this->calculate($operator, $left, $right));
373 }
374 $result = $stack->pop();
375
376 return $result;
377 }
378 }
calculate($operator, $left, $right)
Class ilDclStack.

References $operators, $result, calculate(), and parseMath().

Referenced by parse(), and parseMath().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ substituteFieldValues()

ilDclExpressionParser::substituteFieldValues ( array  $tokens)
protected

Given an array of tokens, replace each token that is a placeholder (e.g.

[[Field name]]) with it's value

Parameters
array$tokens
Returns
array

Definition at line 252 of file class.ilDclExpressionParser.php.

252 {
253 $replaced = array();
254 foreach ($tokens as $token) {
255 if (strpos($token, '[[') === 0) {
256 $replaced[] = $this->substituteFieldValue($token);
257 } else {
258 $replaced[] = $token;
259 }
260 }
261
262 return $replaced;
263 }

Referenced by calculateFunctions(), and parse().

+ Here is the caller graph for this function:

Field Documentation

◆ $cache_fields

ilDclExpressionParser::$cache_fields = array()
staticprotected

Definition at line 43 of file class.ilDclExpressionParser.php.

◆ $cache_math_function_tokens

ilDclExpressionParser::$cache_math_function_tokens = array()
staticprotected

Definition at line 51 of file class.ilDclExpressionParser.php.

◆ $cache_math_tokens

ilDclExpressionParser::$cache_math_tokens = array()
staticprotected

Definition at line 47 of file class.ilDclExpressionParser.php.

◆ $cache_tokens

ilDclExpressionParser::$cache_tokens = array()
staticprotected

Definition at line 39 of file class.ilDclExpressionParser.php.

◆ $expression

ilDclExpressionParser::$expression
protected

Definition at line 25 of file class.ilDclExpressionParser.php.

Referenced by __construct().

◆ $field

ilDclExpressionParser::$field
protected

Definition at line 21 of file class.ilDclExpressionParser.php.

Referenced by __construct().

◆ $functions

ilDclExpressionParser::$functions
staticprotected
Initial value:
= array(
'SUM',
'AVERAGE',
'MIN',
'MAX',
)

Definition at line 55 of file class.ilDclExpressionParser.php.

Referenced by getFunctions(), and isMathToken().

◆ $operators

ilDclExpressionParser::$operators
staticprotected
Initial value:
= array(
'+' => array( 'precedence' => 1 ),
'-' => array( 'precedence' => 1 ),
'*' => array( 'precedence' => 2 ),
'/' => array( 'precedence' => 2 ),
'^' => array( 'precedence' => 3 ),
)

Definition at line 29 of file class.ilDclExpressionParser.php.

Referenced by getOperators(), isMathToken(), and parseMath().

◆ $record

ilDclExpressionParser::$record
protected

Definition at line 17 of file class.ilDclExpressionParser.php.

Referenced by __construct().

◆ N_DECIMALS

const ilDclExpressionParser::N_DECIMALS = 1

Definition at line 11 of file class.ilDclExpressionParser.php.

◆ SCIENTIFIC_NOTATION_LOWER

const ilDclExpressionParser::SCIENTIFIC_NOTATION_LOWER = 0.000000001

Definition at line 13 of file class.ilDclExpressionParser.php.

◆ SCIENTIFIC_NOTATION_UPPER

const ilDclExpressionParser::SCIENTIFIC_NOTATION_UPPER = 1000000000000

Definition at line 12 of file class.ilDclExpressionParser.php.


The documentation for this class was generated from the following file: