diff --git a/src/JsonRPC/ProcedureHandler.php b/src/JsonRPC/ProcedureHandler.php index 4f2f0de..ef04606 100644 --- a/src/JsonRPC/ProcedureHandler.php +++ b/src/JsonRPC/ProcedureHandler.php @@ -44,6 +44,13 @@ class ProcedureHandler */ protected $beforeMethodName = ''; + /** + * Procedure arguments transformation method to call + * + * @var string + */ + protected $argsTransformMethod = ''; + /** * Register a new procedure * @@ -107,6 +114,17 @@ public function withBeforeMethod($methodName) return $this; } + /** + * Procedure arguments transformation method to call. + * @param $methodName + * @return $this + */ + public function withArgsTransformMethod($methodName) + { + $this->argsTransformMethod = $methodName; + return $this; + } + /** * Register multiple procedures from array * @@ -218,6 +236,12 @@ public function executeMethod($class, $method, $params) $reflection->getNumberOfParameters() ); + /** + * Execute procedure arguments transformation method before invoking + * the procedure. + */ + $arguments = $this->executeArgsTransformMethod($instance, $method, $arguments); + return $reflection->invokeArgs($instance, $arguments); } @@ -234,6 +258,25 @@ public function executeBeforeMethod($object, $method) } } + /** + * Execute procedure arguments transformation method before invoking + * the procedure. + * @param mixed $object + * @param string $method + * @param array $arguments + * @return array + */ + public function executeArgsTransformMethod($object, $method, $arguments) + { + if ($this->argsTransformMethod !== '' && method_exists($object, $this->argsTransformMethod)) { + $arguments = call_user_func_array([$object, $this->argsTransformMethod], [$method, $arguments]); + if ($arguments === false) { + throw new BadFunctionCallException('Unable to transform procedure arguments!'); + } + } + return $arguments; + } + /** * Get procedure arguments * diff --git a/tests/ProcedureHandlerTest.php b/tests/ProcedureHandlerTest.php index 42977d7..f267499 100644 --- a/tests/ProcedureHandlerTest.php +++ b/tests/ProcedureHandlerTest.php @@ -36,6 +36,22 @@ public function myProcedure() } } +class ClassWithArgsTransformMethod +{ + public static string $foobar = ''; + + public function transform($procedure, $args): array + { + $args[0] .= self::$foobar; + return $args; + } + + public function getAll($arg1) + { + return $arg1; + } +} + class ProcedureHandlerTest extends TestCase { public function testProcedureNotFound() @@ -161,4 +177,13 @@ public function testBeforeMethod() $handler->withBeforeMethod('before'); $this->assertEquals('myProcedure', $handler->executeProcedure('myProcedure')); } + + public function testArgTranformMethod() + { + $handler = new ProcedureHandler(); + ClassWithArgsTransformMethod::$foobar = 'o'; + $handler->withObject(new ClassWithArgsTransformMethod()); + $handler->withArgsTransformMethod('transform'); + $this->assertEquals('hello', $handler->executeProcedure('getAll', ['hell'])); + } }