*/ class Calculator { /** * Calculate array of tokens in reverse polish notation * @param array $tokens Array of tokens * @param array $variables Array of variables * @return number Result * @throws \NXP\Exception\IncorrectExpressionException * @throws \NXP\Exception\UnknownVariableException */ public function calculate($tokens, $variables) { $stack = []; foreach ($tokens as $token) { if ($token instanceof TokenNumber || $token instanceof TokenStringDoubleQuoted || $token instanceof TokenStringSingleQuoted) { $stack[] = $token; } else if ($token instanceof TokenVariable) { $variable = $token->getValue(); if (!array_key_exists($variable, $variables)) { throw new UnknownVariableException($variable); } $value = $variables[$variable]; $stack[] = new TokenNumber($value); } else if ($token instanceof InterfaceOperator || $token instanceof TokenFunction) { $stack[] = $token->execute($stack); } } $result = array_pop($stack); if ($result === null || ! empty($stack)) { throw new IncorrectExpressionException(); } return $result->getValue(); } }