Skip to content

Commit

Permalink
Throw an IncorrectNumberOfFunctionParametersException if a function g…
Browse files Browse the repository at this point in the history
…ets more arguments than it supports (#117)

* Throw an IncorrectNumberOfFunctionParametersException if a function gets more arguments than it supports

* Update CustomFunction.php

Code Style

Co-authored-by: Bruce Wells <[email protected]>
  • Loading branch information
madman-81 and phpfui authored Aug 4, 2022
1 parent 08b432e commit 9538001
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/NXP/Classes/CustomFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class CustomFunction
*/
public $function;

private bool $isVariadic;
private int $totalParamCount;
private int $requiredParamCount;

/**
Expand All @@ -26,7 +28,10 @@ public function __construct(string $name, callable $function)
{
$this->name = $name;
$this->function = $function;
$this->requiredParamCount = (new ReflectionFunction($function))->getNumberOfRequiredParameters();
$reflection = (new ReflectionFunction($function));
$this->isVariadic = $reflection->isVariadic();
$this->totalParamCount = $reflection->getNumberOfParameters();
$this->requiredParamCount = $reflection->getNumberOfRequiredParameters();

}

Expand All @@ -40,6 +45,9 @@ public function execute(array &$stack, int $paramCountInStack) : Token
if ($paramCountInStack < $this->requiredParamCount) {
throw new IncorrectNumberOfFunctionParametersException($this->name);
}
if ($paramCountInStack > $this->totalParamCount && ! $this->isVariadic) {
throw new IncorrectNumberOfFunctionParametersException($this->name);
}
$args = [];

if ($paramCountInStack > 0) {
Expand Down
10 changes: 10 additions & 0 deletions tests/MathTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,16 @@ public function testFunctionIncorrectNumberOfParameters() : void
$calculator->execute('myfunc(1)');
}

public function testFunctionIncorrectNumberOfParametersTooMany() : void
{
$calculator = new MathExecutor();
$this->expectException(IncorrectNumberOfFunctionParametersException::class);
$calculator->addFunction('myfunc', static function($arg1, $arg2) {
return $arg1 + $arg2;
});
$calculator->execute('myfunc(1,2,3)');
}

public function testFunctionIf() : void
{
$calculator = new MathExecutor();
Expand Down

0 comments on commit 9538001

Please sign in to comment.