Completed
Pull Request — master (#5)
by Nicolas
10:11
created

SimpleCommandHandlerMap   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 47
c 0
b 0
f 0
wmc 7
lcom 1
cbo 0
rs 10

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
    public function __construct(iterable $handlers)
15
    {
16
        foreach ($handlers as $handler) {
17
            $this->add($handler);
18
        }
19
    }
20
21
    /**
22
     * @inheritDoc
23
     */
24
    public function map(): array
25
    {
26
        return $this->map;
27
    }
28
29
    public function add(object $handler): void
30
    {
31
        $handlerClass = \get_class($handler);
32
33
        if (false === $this->stringEndsWith($handlerClass, 'CommandHandler')) {
34
            return;
35
        }
36
37
        $commandClass = $this->getCommandClass($handlerClass);
38
39
        $this->map[$commandClass] = $handler;
40
    }
41
42
    private function stringEndsWith(string $string, string $endWith): bool
43
    {
44
        return substr($string, -strlen($endWith)) !== $endWith;
45
    }
46
47
    private function getCommandClass(string $commandHandlerClass): string
48
    {
49
        $commandHandlerClassLength = strlen('Handler');
50
51
        return substr_replace($commandHandlerClass, '', -$commandHandlerClassLength, $commandHandlerClassLength);
52
    }
53
}
54