* Calling registerClass() on CommandRegistry will result in all
methods having the #[RpcCallable("command-here")] attribute
being registered as commands.
* Commands can be unregistered by calling unregisterClass().
90 lines
2.4 KiB
PHP
90 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\React\CommandBus;
|
|
|
|
use Evenement\EventEmitterInterface;
|
|
use Evenement\EventEmitterTrait;
|
|
|
|
/**
|
|
* A collection of commands that can be executed via CommandBusInterface
|
|
*
|
|
*/
|
|
class CommandRegistry implements CommandResolverInterface, EventEmitterInterface
|
|
{
|
|
use EventEmitterTrait;
|
|
|
|
const EVENT_REGISTERED = 'registered';
|
|
const EVENT_UNREGISTERED = 'unregistered';
|
|
|
|
/** @var array<string,Command> The registered commands and callbacks */
|
|
private array $commands = [];
|
|
/** @var array<string,array<string>> Commands registered by scanning a class */
|
|
private array $classCommands = [];
|
|
|
|
public function register(string $command, callable $handler): void
|
|
{
|
|
$isNew = !array_key_exists($command, $this->commands);
|
|
|
|
$this->commands[$command] = new Command($command, $handler);
|
|
|
|
if ($isNew) {
|
|
$this->emit(self::EVENT_REGISTERED, [ $command ]);
|
|
}
|
|
}
|
|
|
|
public function registerClass(object $target): void
|
|
{
|
|
$a = function (\ReflectionMethod $r, string $a) {
|
|
$attrs = $r->getAttributes($a);
|
|
if (!$attrs) return null;
|
|
return array_shift($attrs)->newInstance();
|
|
};
|
|
|
|
$r = new \ReflectionObject($target);
|
|
|
|
$name = get_class($target);
|
|
$this->classCommands[$name] = [];
|
|
|
|
foreach ($r->getMethods() as $method) {
|
|
$methodRpc = $a($method, Attributes\RpcCallable::class);
|
|
if ($methodRpc) {
|
|
$this->register($methodRpc->name, $method->getClosure($target));
|
|
$this->classCommands[$name][] = $methodRpc->name;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
public function unregister(string $command): void
|
|
{
|
|
if (!array_key_exists($command, $this->commands)) {
|
|
return;
|
|
}
|
|
|
|
unset($this->commands[$command]);
|
|
|
|
$this->emit(self::EVENT_UNREGISTERED, [ $command ]);
|
|
}
|
|
|
|
public function unregisterClass(object $target): void
|
|
{
|
|
$name = get_class($target);
|
|
if (!isset($this->classCommands[$name])) return;
|
|
foreach ($this->classCommands[$name] as $command) {
|
|
$this->unregister($command);
|
|
}
|
|
unset($this->classCommands[$name]);
|
|
}
|
|
|
|
public function findCommand(string $command): ?Command
|
|
{
|
|
return $this->commands[$command] ?? null;
|
|
}
|
|
|
|
public function getCommandNames(): array
|
|
{
|
|
return array_keys($this->commands);
|
|
}
|
|
}
|
|
|