54 lines
1.2 KiB
PHP
54 lines
1.2 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 EventEmitterInterface
|
||
|
{
|
||
|
use EventEmitterTrait;
|
||
|
|
||
|
const EVENT_REGISTERED = 'registered';
|
||
|
const EVENT_UNREGISTERED = 'unregistered';
|
||
|
|
||
|
/** @var array<string,Command> */
|
||
|
private array $commands = [];
|
||
|
|
||
|
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 unregister(string $command): void
|
||
|
{
|
||
|
if (!array_key_exists($command, $this->commands)) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
unset($this->commands[$command]);
|
||
|
|
||
|
$this->emit(self::EVENT_UNREGISTERED, [ $command ]);
|
||
|
}
|
||
|
|
||
|
public function find(string $command): ?Command
|
||
|
{
|
||
|
return $this->commands[$command] ?? null;
|
||
|
}
|
||
|
|
||
|
public function getNames(): array
|
||
|
{
|
||
|
return array_keys($this->commands);
|
||
|
}
|
||
|
}
|
||
|
|