1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Stratadox\CommandHandling; |
4
|
|
|
|
5
|
|
|
use function array_key_exists; |
6
|
|
|
use function class_exists; |
7
|
|
|
use function get_class; |
8
|
|
|
use function is_string; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* The command bus is a handler that can take different types of commands, |
12
|
|
|
* delegating them to their designated command handlers. |
13
|
|
|
*/ |
14
|
|
|
final class CommandBus implements Handler |
15
|
|
|
{ |
16
|
|
|
/** @var Handler[] */ |
17
|
|
|
private $registry; |
18
|
|
|
|
19
|
|
|
/** @throws InvalidBusConfiguration */ |
20
|
|
|
private function __construct(array $registry) |
21
|
|
|
{ |
22
|
|
|
foreach ($registry as $commandClass => $handler) { |
23
|
|
|
$this->mustBeAnExisting($commandClass); |
24
|
|
|
$this->mustBeACompatible($handler); |
25
|
|
|
} |
26
|
|
|
$this->registry = $registry; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** @throws InvalidBusConfiguration */ |
30
|
|
|
public static function handling(array $commands): Handler |
31
|
|
|
{ |
32
|
|
|
return new self($commands); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** @inheritdoc */ |
36
|
|
|
public function handle(object $command): void |
37
|
|
|
{ |
38
|
|
|
$this->mustBeAKnown($command); |
39
|
|
|
$this->registry[get_class($command)]->handle($command); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** @throws InvalidBusConfiguration */ |
43
|
|
|
private function mustBeAnExisting($commandClass): void |
44
|
|
|
{ |
45
|
|
|
if (!is_string($commandClass) || !class_exists($commandClass)) { |
46
|
|
|
throw CommandClassNotFound::tryingToConfigure($commandClass); |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** @throws InvalidBusConfiguration */ |
51
|
|
|
private function mustBeACompatible($commandHandler): void |
52
|
|
|
{ |
53
|
|
|
if (!$commandHandler instanceof Handler) { |
54
|
|
|
throw InvalidCommandHandler::triedToAssign($commandHandler); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @throws CommandNotRecognised */ |
59
|
|
|
private function mustBeAKnown($command): void |
60
|
|
|
{ |
61
|
|
|
if (!array_key_exists(get_class($command), $this->registry)) { |
62
|
|
|
throw CommandNotRecognised::triedToHandle($command); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|