diff options
author | Javier Marín <javier@marinros.com> | 2020-07-26 05:27:26 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-07-26 05:27:26 +0300 |
commit | c1e07f254a4e952868be8240080661628aef8e69 (patch) | |
tree | b7ff2fa4c478a9ccc2fd0d17c64d54732f3391fb /src/NXP/Classes/Calculator.php | |
parent | aa8ffe19f2eb6f194b3e6ee1aac4c2706659e6b9 (diff) |
Handler for not found variables (#68)
* Added handler to define not found variables
Added support for string variables
Fixed strings and ints comparison error
* Check if variables have scalar types (int, float, string and bool)
Better $onVarNotFound logic
Diffstat (limited to 'src/NXP/Classes/Calculator.php')
-rw-r--r-- | src/NXP/Classes/Calculator.php | 14 |
1 files changed, 11 insertions, 3 deletions
diff --git a/src/NXP/Classes/Calculator.php b/src/NXP/Classes/Calculator.php index bcb4b4e..49142df 100644 --- a/src/NXP/Classes/Calculator.php +++ b/src/NXP/Classes/Calculator.php @@ -49,7 +49,7 @@ class Calculator * @throws IncorrectExpressionException * @throws UnknownVariableException */ - public function calculate(array $tokens, array $variables) + public function calculate(array $tokens, array $variables, callable $onVarNotFound = null) { /** @var Token[] $stack */ $stack = []; @@ -58,10 +58,18 @@ class Calculator $stack[] = $token; } elseif ($token->type === Token::Variable) { $variable = $token->value; - if (!array_key_exists($variable, $variables)) { + + $value = null; + if (array_key_exists($variable, $variables)) { + $value = $variables[$variable]; + } elseif ($onVarNotFound) { + $value = call_user_func($onVarNotFound, $variable); + } + + if (!isset($value)) { throw new UnknownVariableException($variable); } - $value = $variables[$variable]; + $stack[] = new Token(Token::Literal, $value); } elseif ($token->type === Token::Function) { if (!array_key_exists($token->value, $this->functions)) { |