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:
madman-81 2022-08-04 14:07:41 +02:00 committed by GitHub
parent 08b432e09d
commit 9538001a42
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 1 deletions

View file

@ -15,6 +15,8 @@ class CustomFunction
*/
public $function;
private bool $isVariadic;
private int $totalParamCount;
private int $requiredParamCount;
/**
@ -26,7 +28,10 @@ class CustomFunction
{
$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();
}
@ -40,6 +45,9 @@ class CustomFunction
if ($paramCountInStack < $this->requiredParamCount) {
throw new IncorrectNumberOfFunctionParametersException($this->name);
}
if ($paramCountInStack > $this->totalParamCount && ! $this->isVariadic) {
throw new IncorrectNumberOfFunctionParametersException($this->name);
}
$args = [];
if ($paramCountInStack > 0) {

View file

@ -674,6 +674,16 @@ class MathTest extends TestCase
$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();