71 lines
1.8 KiB
PHP
71 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\React\CommandBus;
|
|
|
|
use ReflectionFunction;
|
|
use ReflectionNamedType;
|
|
use React\Promise\Deferred;
|
|
use React\Promise\Promise;
|
|
use React\Promise\PromiseInterface;
|
|
|
|
/**
|
|
*
|
|
*/
|
|
class Command
|
|
{
|
|
/** @var string $name The command name */
|
|
private string $name;
|
|
|
|
/** @var callable $handler The handler */
|
|
private $handler;
|
|
|
|
public function __construct(string $name, callable $handler)
|
|
{
|
|
$this->name = $name;
|
|
$this->handler = $handler;
|
|
}
|
|
|
|
public function getName(): string
|
|
{
|
|
return $this->name;
|
|
}
|
|
|
|
public function call(Context $context): PromiseInterface
|
|
{
|
|
return new Promise(function (callable $resolve) use ($context) {
|
|
$args = $context->toMethodParameters($this->handler);
|
|
$resolve(call_user_func($this->handler, ...$args));
|
|
//$resolve(call_user_func($this->handler, $context));
|
|
return;
|
|
});
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
}
|
|
|