SimpleCommandHandlerMap::add()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 9.8666
cc 2
nc 2
nop 1
crap 2
1
<?php declare(strict_types=1);
2
3
namespace BSP\CommandBus;
4
5
use BSP\CommandBus\Contracts\CommandHandlerMap;
6
use BSP\CommandBus\Exception\CommandHandlerClassNameDoesNotEndWithHandler;
7
8
final class SimpleCommandHandlerMap implements CommandHandlerMap
9
{
10
    private $map = [];
11
12
    /**
13
     * @param iterable<string, callable> $handlers
14
     */
15 5
    public function __construct(iterable $handlers)
16
    {
17 5
        foreach ($handlers as $handler) {
18 3
            $this->add($handler);
19
        }
20 4
    }
21
22
    /**
23
     * @inheritDoc
24
     */
25 4
    public function map(): array
26
    {
27 4
        return $this->map;
28
    }
29
30 4
    public function add(object $handler): void
31
    {
32 4
        $handlerClass = \get_class($handler);
33
34 4
        if (false === $this->stringEndsWith($handlerClass, 'Handler')) {
35 1
            throw new CommandHandlerClassNameDoesNotEndWithHandler();
36
        }
37
38 3
        $commandClass = $this->getCommandClass($handlerClass);
39
40 3
        $this->map[$commandClass] = $handler;
41 3
    }
42
43 4
    private function stringEndsWith(string $string, string $endWith): bool
44
    {
45 4
        $text = substr($string, -strlen($endWith));
46
47 4
        return $text === $endWith;
48
    }
49
50 3
    private function getCommandClass(string $commandHandlerClass): string
51
    {
52 3
        $commandHandlerClassLength = strlen('Handler');
53
54 3
        return substr_replace($commandHandlerClass, '', -$commandHandlerClassLength, $commandHandlerClassLength);
55
    }
56
}
57