Add support for registering classes with CommandRegistry

* 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().
This commit is contained in:
noccy committed 2025-04-07 00:06:55 +02:00
1 parent 6671ec3eac
commit 070f607187
5 files changed
+53 -4

No files matched your search

+37 -1
View File
@@ -1,6 +1,7 @@
<?php
namespace NoccyLabs\React\CommandBus;
use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
@@ -15,8 +16,10 @@ class CommandRegistry implements CommandResolverInterface, EventEmitterInterface
const EVENT_REGISTERED = 'registered';
const EVENT_UNREGISTERED = 'unregistered';
/** @var array<string,Command> */
/** @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
{
@@ -29,6 +32,29 @@ class CommandRegistry implements CommandResolverInterface, EventEmitterInterface
}
}
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)) {
@@ -40,6 +66,16 @@ class CommandRegistry implements CommandResolverInterface, EventEmitterInterface
$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;