Skip to content

Commit

Permalink
add reporting of used variables in a formula
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Ackermann committed Dec 13, 2019
1 parent 7d6d32c commit 9060d88
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/MathParser/Math.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '';
Expand Down
5 changes: 5 additions & 0 deletions lib/MathParser/Variable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ public function render($variables = [])
}
}

public function getName()
{
return $this->value;
}

public function isVariable()
{
return true;
Expand Down
32 changes: 32 additions & 0 deletions test/MathParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,34 @@ 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],
];

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[][]
*/
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 9060d88

Please sign in to comment.