From 00def17f0e9183544813427cddbdaed851986309 Mon Sep 17 00:00:00 2001 From: Bruce Wells Date: Wed, 12 Sep 2018 11:55:31 -0400 Subject: Support for double quoted strings Changed array() to [] syntax. Added variable in question to unknown variable exception. Added getVar and getVars accessor functions. Added getOperators and getFunctions accessor functions for completeness. Extended all Exceptions off MathExecutorException. --- src/NXP/MathExecutor.php | 59 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 6 deletions(-) (limited to 'src/NXP/MathExecutor.php') diff --git a/src/NXP/MathExecutor.php b/src/NXP/MathExecutor.php index 5cb4bca..56cefe5 100644 --- a/src/NXP/MathExecutor.php +++ b/src/NXP/MathExecutor.php @@ -15,6 +15,7 @@ use NXP\Classes\Calculator; use NXP\Classes\Lexer; use NXP\Classes\Token; use NXP\Classes\TokenFactory; +use NXP\Exception\UnknownVariableException; /** * Class MathExecutor @@ -27,7 +28,7 @@ class MathExecutor * * @var array */ - private $variables = array(); + private $variables = []; /** * @var TokenFactory @@ -37,7 +38,7 @@ class MathExecutor /** * @var array */ - private $cache = array(); + private $cache = []; /** * Base math operators @@ -75,10 +76,36 @@ class MathExecutor $this->tokenFactory->addFunction('max', 'max', 2); $this->tokenFactory->addFunction('avg', function($arg1, $arg2) { return ($arg1 + $arg2) / 2; }, 2); - $this->setVars(array( + $this->setVars([ 'pi' => 3.14159265359, 'e' => 2.71828182846 - )); + ]); + } + + /** + * Get all vars + * + * @return array + */ + public function getVars() + { + return $this->variables; + } + + /** + * Get a specific var + * + * @param string $variable + * @return integer|float + * @throws UnknownVariableException + */ + public function getVar($variable) + { + if (! isset($this->variables[$variable])) { + throw new UnknownVariableException("Variable ({$variable}) not set"); + } + + return $this->variables[$variable]; } /** @@ -86,7 +113,6 @@ class MathExecutor * * @param string $variable * @param integer|float $value - * @throws \Exception * @return MathExecutor */ public function setVar($variable, $value) @@ -134,7 +160,7 @@ class MathExecutor */ public function removeVars() { - $this->variables = array(); + $this->variables = []; return $this; } @@ -152,6 +178,16 @@ class MathExecutor return $this; } + /** + * Get all registered operators to executor + * + * @return array of operator class names + */ + public function getOperators() + { + return $this->tokenFactory->getOperators(); + } + /** * Add function to executor * @@ -167,6 +203,17 @@ class MathExecutor return $this; } + /** + * Get all registered functions + * + * @return array containing callback and places indexed by + * function name + */ + public function getFunctions() + { + return $this->tokenFactory->getFunctions(); + } + /** * Execute expression * -- cgit v1.2.3