diff --git a/src/Command.php b/src/Command.php index 383ba4d..790ada8 100644 --- a/src/Command.php +++ b/src/Command.php @@ -2,6 +2,8 @@ namespace NoccyLabs\React\CommandBus; +use ReflectionFunction; +use ReflectionNamedType; use React\Promise\Deferred; use React\Promise\Promise; use React\Promise\PromiseInterface; @@ -38,5 +40,31 @@ class Command }); } + public function parameters(): array + { + $refl = new ReflectionFunction($this->handler); + $args = []; + + foreach ($refl->getParameters() as $parameter) { + $name = $parameter->getName(); + $type = null; + if (!$parameter->hasType()) { + $type = 'any'; + } else { + $type = $parameter->getType(); + if ($type instanceof ReflectionNamedType && $type->isBuiltin()) { + $type = $type->getName(); + } else { + $type = null; + } + } + + if ($parameter->isOptional()) $type = "?{$type}"; + if ($type !== null) $args[$name] = $type; + } + + return $args; + } + } diff --git a/tests/CommandTest.php b/tests/CommandTest.php index decba24..54d30f0 100644 --- a/tests/CommandTest.php +++ b/tests/CommandTest.php @@ -26,4 +26,14 @@ class CommandTest extends \PHPUnit\Framework\TestCase $this->assertEquals(true, $hit); } -} \ No newline at end of file + public function testCommandReflection() + { + $command = new Command("test", function (string $a, ?int $b, bool $c = false) { }); + $expect = [ + 'a' => 'string', + 'b' => 'int', + 'c' => '?bool' + ]; + $this->assertEquals($expect, $command->parameters()); + } +}