From 29c5b5006ccb5cb308b9467ca25813b29be8cfc6 Mon Sep 17 00:00:00 2001 From: franksl Date: Tue, 26 Nov 2019 15:00:24 +0100 Subject: Logicandcompare (#50) * TokenFactory: allowing multicharacter tokens * Added logical and compare operators: <, <=, >, >=, ==, !=, ||, && * Fixed operator priorities * Error messages fixes * Fixed operators priority The priorities are assigned by following the php language standard (https://www.php.net/manual/en/language.operators.precedence.php) I've assigned precedence in steps of 10 units by following the linked page: 230 clone new 220 ** 210 ++ -- ~ (int) (float) (string) (array) (object) (bool) @ 200 instanceof 190 ! 180 * / % 170 + - . 160 << >> 150 < <= > >= 140 == != === !== <> <=> 130 & 120 ^ 110 | 100 && 90 || 80 ?? 70 ? : 60 = += -= *= **= /= .= %= &= |= ^= <<= >>= 50 yield from 40 yield 30 and 20 xor 10 or * Added if() function * Cache key fix There are cases where the cache key creation raised an error, for example while evaluating the expression "if(cos(2), cos(2), 0)", because the if() function was passing a float to the MathExecutor:execute() method. --- src/NXP/MathExecutor.php | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) (limited to 'src/NXP/MathExecutor.php') diff --git a/src/NXP/MathExecutor.php b/src/NXP/MathExecutor.php index 6325d35..2a5f9fb 100644 --- a/src/NXP/MathExecutor.php +++ b/src/NXP/MathExecutor.php @@ -223,13 +223,14 @@ class MathExecutor */ public function execute($expression) { - if (!array_key_exists($expression, $this->cache)) { + $cachekey = (string)$expression; + if (!array_key_exists($cachekey, $this->cache)) { $lexer = new Lexer($this->tokenFactory); $tokensStream = $lexer->stringToTokensStream($expression); $tokens = $lexer->buildReversePolishNotation($tokensStream); - $this->cache[$expression] = $tokens; + $this->cache[$cachekey] = $tokens; } else { - $tokens = $this->cache[$expression]; + $tokens = $this->cache[$cachekey]; } $calculator = new Calculator(); $result = $calculator->calculate($tokens, $this->variables); @@ -263,6 +264,14 @@ class MathExecutor 'NXP\Classes\Token\TokenMultiply', 'NXP\Classes\Token\TokenDivision', 'NXP\Classes\Token\TokenDegree', + 'NXP\Classes\Token\TokenAnd', + 'NXP\Classes\Token\TokenOr', + 'NXP\Classes\Token\TokenEqual', + 'NXP\Classes\Token\TokenUnequal', + 'NXP\Classes\Token\TokenGreaterThanOrEqual', + 'NXP\Classes\Token\TokenGreaterThan', + 'NXP\Classes\Token\TokenLessThanOrEqual', + 'NXP\Classes\Token\TokenLessThan', ]; } @@ -296,6 +305,18 @@ class MathExecutor 'avg' => function ($arg1, $arg2) { return ($arg1 + $arg2) / 2; }, + 'if' => function ($expr, $trueval, $falseval) { + if ($expr === true || $expr === false) { + $exres = $expr; + } else { + $exres = $this->execute($expr); + } + if ($exres) { + return $this->execute($trueval); + } else { + return $this->execute($falseval); + } + } ]; } -- cgit v1.2.3