From 9060d88f7f6b23872e53ec1dbf7906252ab8f33f Mon Sep 17 00:00:00 2001 From: Stefan Ackermann Date: Fri, 13 Dec 2019 11:41:13 +0100 Subject: [PATCH] add reporting of used variables in a formula --- lib/MathParser/Math.php | 16 ++++++++++++++++ lib/MathParser/Variable.php | 5 +++++ test/MathParserTest.php | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/lib/MathParser/Math.php b/lib/MathParser/Math.php index 30c67f4..3d12899 100644 --- a/lib/MathParser/Math.php +++ b/lib/MathParser/Math.php @@ -96,6 +96,22 @@ public function run(array $stack) return $operator ? $operator->render() : $this->render($stack); } + public function getDistinctVariables(array $stack) + { + $variables = []; + + foreach ($stack as $expression) { + if ($expression instanceof Variable) { + $variableName = $expression->getName(); + if (!in_array($variableName, $variables, true)) { + $variables[] = $variableName; + } + } + } + + return $variables; + } + private function render(array &$stack) { $output = ''; diff --git a/lib/MathParser/Variable.php b/lib/MathParser/Variable.php index 9064439..4e05c2b 100644 --- a/lib/MathParser/Variable.php +++ b/lib/MathParser/Variable.php @@ -14,6 +14,11 @@ public function render($variables = []) } } + public function getName() + { + return $this->value; + } + public function isVariable() { return true; diff --git a/test/MathParserTest.php b/test/MathParserTest.php index 11e113f..a0f5de2 100644 --- a/test/MathParserTest.php +++ b/test/MathParserTest.php @@ -103,6 +103,7 @@ public static function provideVariableData() [['$0 + $2', [0, 41, 13]], 13], [['$a + $b', ['a' => 0, 'b' => 41, 13]], 41], [['$a + $b + $0', ['a' => 0, 'b' => 41, 0 => 13]], 54], + [['$a1 + $b2 + $0', ['a1' => 0, 'b2' => 41, 0 => 13]], 54], [['$0 + $2', [0, 41, 13]], 13], [['$0 + $2', [0, 41, 13]], 13], ]; @@ -110,6 +111,26 @@ public static function provideVariableData() return $data; } + /** + * @return mixed[][] + */ + public static function provideVariableDataWithUsedVars() + { + $data = [ + [['$0', [1]], ['0']], + [['$0 + $0', [1]], ['0']], + [['$0 + $1', [1, 41]], ['0', '1']], + [['$0 + $2', [0, 41, 13]], ['0', '2']], + [['$a + $b', ['a' => 0, 'b' => 41, 13]], ['a', 'b']], + [['$a + $b + $0', ['a' => 0, 'b' => 41, 0 => 13]], ['a', 'b', '0']], + [['$a1 + $b2 + $0', ['a1' => 0, 'b2' => 41, 0 => 13]], ['a1', 'b2', '0']], + [['$0 + $2', [0, 41, 13]], ['0', '2']], + [['10', []], []], + ]; + + return $data; + } + /** * @return mixed[][] */ @@ -194,4 +215,15 @@ public function testInvalidVariableWithRegister($input, $expected) $mathParser->registerVariable(0, $input[1][0]); $mathParser->evaluate($input[0]); } + + /** + * @dataProvider provideVariableDataWithUsedVars + */ + public function testDistinctVariables($input, $expected) + { + $mathParser = new Math(); + $stack = $mathParser->parse($input[0]); + $vars = $mathParser->getDistinctVariables($stack); + $this->assertSame($expected, $vars); + } } \ No newline at end of file