Passed
Push — master ( 23e253...b3bed4 )
by Mr
02:58
created

CommandRouter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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