Skip to content

Commit

Permalink
also accept null as variable input
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Ackermann committed Jan 13, 2020
1 parent 3ead01b commit 0cd0864
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 8 deletions.
2 changes: 1 addition & 1 deletion lib/MathParser/Expressions/Number.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Number extends Expression
{
public function __construct($value)
{
parent::__construct(+$value);
parent::__construct($value);
}

public function operate(array &$stack)
Expand Down
14 changes: 7 additions & 7 deletions lib/MathParser/Math.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public function parse($string)

public function registerVariable($name, $value)
{
$this->assertVariableIsNumber($value);
$this->assertVariableIsNumberOrNull($value);

$this->variables[$name] = $value;
}
Expand Down Expand Up @@ -198,7 +198,7 @@ public function clearVariables()
*/
public function setVariables(array $variables)
{
$this->assertVariablesAreNumbers($variables);
$this->assertVariablesAreNumbersOrNull($variables);
$this->variables = $variables;
}

Expand All @@ -211,17 +211,17 @@ private function substituteVariables(array &$stack, array $variables)
}
}

private function assertVariablesAreNumbers(array $variables)
private function assertVariablesAreNumbersOrNull(array $variables)
{
foreach ($variables as $variable) {
$this->assertVariableIsNumber($variable);
$this->assertVariableIsNumberOrNull($variable);
}
}

private function assertVariableIsNumber($variable)
private function assertVariableIsNumberOrNull($variable)
{
if (!is_int($variable) && !is_float($variable)) {
throw new \InvalidArgumentException('provided variable is not a number');
if (!is_int($variable) && !is_float($variable) && !($variable === null)) {
throw new \InvalidArgumentException('provided variable is not a number or null. found: ' . $variable);
}
}
}
1 change: 1 addition & 0 deletions test/MathParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public static function provideVariableData()
[['$a1 + $b2 + $0', ['a1' => 0, 'b2' => 41, 0 => 13]], 54],
[['$0 + $2', [0, 41, 13]], 13],
[['$0 + $2', [0, 41, 13]], 13],
[['$0 + $2', [null, 41, 13]], null],
];

return $data;
Expand Down

0 comments on commit 0cd0864

Please sign in to comment.