aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormadman-81 <50033071+madman-81@users.noreply.github.com>2022-08-04 15:07:41 +0300
committerGitHub <noreply@github.com>2022-08-04 15:07:41 +0300
commit9538001a42988507a29aa55eef7f59f0462665ab (patch)
tree02669ab470de08a26d4d694a515c7e40edb055eb
parent08b432e09dd05b0b793a2379e8e380582c9877dc (diff)
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>
-rw-r--r--src/NXP/Classes/CustomFunction.php10
-rw-r--r--tests/MathTest.php10
2 files changed, 19 insertions, 1 deletions
diff --git a/src/NXP/Classes/CustomFunction.php b/src/NXP/Classes/CustomFunction.php
index 6e9ffc5..43c5b55 100644
--- a/src/NXP/Classes/CustomFunction.php
+++ b/src/NXP/Classes/CustomFunction.php
@@ -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) {
diff --git a/tests/MathTest.php b/tests/MathTest.php
index 94a14d4..59ce207 100644
--- a/tests/MathTest.php
+++ b/tests/MathTest.php
@@ -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();