Completed
Pull Request — master (#5)
by Nicolas
10:36 queued 09:37
created

SimpleCommandHandlerMap   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 47
ccs 17
cts 18
cp 0.9444
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A map() 0 4 1
A add() 0 12 2
A stringEndsWith() 0 4 1
A getCommandClass() 0 6 1
1
<?php declare(strict_types=1);
2
3
namespace BSP\CommandBus;
4
5
use BSP\CommandBus\Contracts\CommandHandlerMap;
6
7
final class SimpleCommandHandlerMap implements CommandHandlerMap
8
{
9
    private $map = [];
10
11
    /**
12
     * @param iterable<string, callable> $handlers
13
     */
14 4
    public function __construct(iterable $handlers)
15
    {
16 4
        foreach ($handlers as $handler) {
17 2
            $this->add($handler);
18
        }
19 4
    }
20
21
    /**
22
     * @inheritDoc
23
     */
24 4
    public function map(): array
25
    {
26 4
        return $this->map;
27
    }
28
29 3
    public function add(object $handler): void
30
    {
31 3
        $handlerClass = \get_class($handler);
32
33 3
        if (false === $this->stringEndsWith($handlerClass, 'CommandHandler')) {
34
            return;
35
        }
36
37 3
        $commandClass = $this->getCommandClass($handlerClass);
38
39 3
        $this->map[$commandClass] = $handler;
40 3
    }
41
42 3
    private function stringEndsWith(string $string, string $endWith): bool
43
    {
44 3
        return substr($string, -strlen($endWith)) !== $endWith;
45
    }
46
47 3
    private function getCommandClass(string $commandHandlerClass): string
48
    {
49 3
        $commandHandlerClassLength = strlen('Handler');
50
51 3
        return substr_replace($commandHandlerClass, '', -$commandHandlerClassLength, $commandHandlerClassLength);
52
    }
53
}
54