Add Command->parameters() method to introspect arguments
This commit is contained in:
parent
bf8e95561e
commit
474ccbb012
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
@ -26,4 +26,14 @@ class CommandTest extends \PHPUnit\Framework\TestCase
|
||||
$this->assertEquals(true, $hit);
|
||||
}
|
||||
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user