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

SimpleCommandHandlerMap::stringEndsWith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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