Throw an IncorrectNumberOfFunctionParametersException if a function gets 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 <brucekwells@gmail.com>
This commit is contained in:
parent
08b432e09d
commit
9538001a42
2 changed files with 19 additions and 1 deletions
|
@ -15,6 +15,8 @@ class CustomFunction
|
||||||
*/
|
*/
|
||||||
public $function;
|
public $function;
|
||||||
|
|
||||||
|
private bool $isVariadic;
|
||||||
|
private int $totalParamCount;
|
||||||
private int $requiredParamCount;
|
private int $requiredParamCount;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -26,7 +28,10 @@ class CustomFunction
|
||||||
{
|
{
|
||||||
$this->name = $name;
|
$this->name = $name;
|
||||||
$this->function = $function;
|
$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();
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -40,6 +45,9 @@ class CustomFunction
|
||||||
if ($paramCountInStack < $this->requiredParamCount) {
|
if ($paramCountInStack < $this->requiredParamCount) {
|
||||||
throw new IncorrectNumberOfFunctionParametersException($this->name);
|
throw new IncorrectNumberOfFunctionParametersException($this->name);
|
||||||
}
|
}
|
||||||
|
if ($paramCountInStack > $this->totalParamCount && ! $this->isVariadic) {
|
||||||
|
throw new IncorrectNumberOfFunctionParametersException($this->name);
|
||||||
|
}
|
||||||
$args = [];
|
$args = [];
|
||||||
|
|
||||||
if ($paramCountInStack > 0) {
|
if ($paramCountInStack > 0) {
|
||||||
|
|
|
@ -674,6 +674,16 @@ class MathTest extends TestCase
|
||||||
$calculator->execute('myfunc(1)');
|
$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
|
public function testFunctionIf() : void
|
||||||
{
|
{
|
||||||
$calculator = new MathExecutor();
|
$calculator = new MathExecutor();
|
||||||
|
|
Loading…
Reference in a new issue