Initial commit
This commit is contained in:
53
src/CommandRegistry.php
Normal file
53
src/CommandRegistry.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user