Compare commits

..

4 Commits

3 changed files with 49 additions and 4 deletions

View File

@ -2,6 +2,8 @@
namespace NoccyLabs\React\CommandBus;
use ReflectionFunction;
use ReflectionNamedType;
use React\Promise\Deferred;
use React\Promise\Promise;
use React\Promise\PromiseInterface;
@ -17,10 +19,13 @@ class Command
/** @var callable $handler The handler */
private $handler;
public function __construct(string $name, callable $handler)
private ?array $signature;
public function __construct(string $name, callable $handler, ?array $signature = null)
{
$this->name = $name;
$this->handler = $handler;
$this->signature = $signature;
}
public function getName(): string
@ -38,5 +43,36 @@ 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->allowsNull() ? "?" : "") . $type->getName();
} else {
$type = null;
}
}
if ($parameter->isDefaultValueAvailable()) $type = "{$type}=".\json_encode($parameter->getDefaultValue(),\JSON_UNESCAPED_SLASHES);
if ($type !== null) $args[$name] = $type;
}
return $args;
}
public function getSignature(): array
{
return $this->signature ?? $this->parameters();
}
}

View File

@ -8,9 +8,8 @@ use Evenement\EventEmitterTrait;
* A collection of commands that can be executed via CommandBusInterface
*
*/
trait CommandResolverTrait implements EventEmitterInterface
trait CommandResolverTrait
{
use EventEmitterTrait;
const EVENT_REGISTERED = 'registered';
const EVENT_UNREGISTERED = 'unregistered';

View File

@ -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=false'
];
$this->assertEquals($expect, $command->parameters());
}
}