|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the daikon-cqrs/boot project. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Daikon\Boot\MessageBus; |
|
10
|
|
|
|
|
11
|
|
|
use Daikon\EventSourcing\Aggregate\Command\CommandInterface; |
|
12
|
|
|
use Daikon\Interop\Assertion; |
|
13
|
|
|
use Daikon\Interop\RuntimeException; |
|
14
|
|
|
use Daikon\MessageBus\EnvelopeInterface; |
|
15
|
|
|
use Daikon\MessageBus\Channel\Subscription\MessageHandler\MessageHandlerInterface; |
|
16
|
|
|
|
|
17
|
|
|
final class CommandRouter implements MessageHandlerInterface |
|
18
|
|
|
{ |
|
19
|
|
|
private array $spawnedHandlers; |
|
20
|
|
|
|
|
21
|
|
|
private array $handlerMap; |
|
22
|
|
|
|
|
23
|
3 |
|
public function __construct(array $handlerMap = []) |
|
24
|
|
|
{ |
|
25
|
3 |
|
$this->handlerMap = $handlerMap; |
|
26
|
3 |
|
$this->spawnedHandlers = []; |
|
27
|
3 |
|
} |
|
28
|
|
|
|
|
29
|
3 |
|
public function handle(EnvelopeInterface $envelope): void |
|
30
|
|
|
{ |
|
31
|
|
|
/** @var CommandInterface $command */ |
|
32
|
3 |
|
$command = $envelope->getMessage(); |
|
33
|
3 |
|
Assertion::implementsInterface($command, CommandInterface::class); |
|
34
|
|
|
|
|
35
|
2 |
|
$commandFqcn = get_class($command); |
|
36
|
2 |
|
if (!isset($this->handlerMap[$commandFqcn])) { |
|
37
|
1 |
|
throw new RuntimeException("No handler assigned to given command '$commandFqcn'."); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
1 |
|
if (!isset($this->spawnedHandlers[$commandFqcn])) { |
|
41
|
1 |
|
$this->spawnedHandlers[$commandFqcn] = $this->handlerMap[$commandFqcn](); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
1 |
|
$this->spawnedHandlers[$commandFqcn]->handle($envelope); |
|
45
|
1 |
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|