CommandBus::addCommandHandler()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Infrastructure\Common\CommandHandler;
6
7
use App\Infrastructure\Common\CommandHandler\Exception\HandlerNotFoundException;
8
9
/**
10
 * Class CommandBus.
11
 */
12
class CommandBus
13
{
14
    /**
15
     * @var array
16
     */
17
    private $handlers = [];
18
19
    /**
20
     * @param object $command
21
     *
22
     * @throws HandlerNotFoundException
23
     */
24
    public function handle(object $command): void
25
    {
26
        $handler = $this->commandToHandler(\get_class($command));
27
        /* @var CommandBusAbstract $handler */
28
        $handler($command);
29
    }
30
31
    public function addCommandHandler(object $handler): void
32
    {
33
        $this->handlers[\get_class($handler)] = $handler;
34
    }
35
36
    /**
37
     * @param string $command
38
     *
39
     * @return CommandHandlerInterface
40
     *
41
     * @throws HandlerNotFoundException
42
     */
43
    private function commandToHandler(string $command): CommandHandlerInterface
44
    {
45
        $commandHandler = explode('\\', $command);
46
        $commandHandler[count($commandHandler) - 1] = str_replace('Command', 'Handler', $commandHandler[count($commandHandler) - 1]);
47
        $commandHandler = implode('\\', $commandHandler);
48
        $handler = $this->handlers[$commandHandler];
49
50
        if (!$handler instanceof CommandHandlerInterface) {
51
            throw new HandlerNotFoundException('Handler not found from: '.$command);
52
        }
53
54
        return $handler;
55
    }
56
}
57