Completed
Push — develop ( d322ef...d5777f )
by Baptiste
07:26
created

ContainerAwareCommandBus::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\CommandBusBundle;
5
6
use Innmind\CommandBusBundle\Exception\InvalidArgumentException;
7
use Innmind\CommandBus\{
8
    CommandBusInterface,
9
    CommandBus,
10
    Exception\InvalidArgumentException as InvalidCommandException
11
};
12
use Innmind\Immutable\{
13
    Map,
14
    MapInterface
15
};
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
18
final class ContainerAwareCommandBus implements CommandBusInterface
19
{
20
    private $container;
21
    private $handlers;
22
    private $bus;
23
24
    public function __construct(
25
        ContainerInterface $container,
26
        MapInterface $handlers
27
    ) {
28
        if (
29
            (string) $handlers->keyType() !== 'string' ||
30
            (string) $handlers->valueType() !== 'string'
31
        ) {
32
            throw new InvalidArgumentException;
33
        }
34
35
        $this->container = $container;
36
        $this->handlers = $handlers;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function handle($command)
43
    {
44
        if (!is_object($command)) {
45
            throw new InvalidCommandException;
46
        }
47
48
        if (!$this->bus instanceof CommandBusInterface) {
49
            $this->initialize();
50
        }
51
52
        $this->bus->handle($command);
53
    }
54
55
    private function initialize()
56
    {
57
        $handlers = $this
58
            ->handlers
59
            ->reduce(
60
                new Map('string', 'callable'),
61
                function(Map $carry, string $class, string $service): Map {
62
                    return $carry->put(
63
                        $class,
64
                        $this->container->get($service)
65
                    );
66
                }
67
            );
68
        $this->bus = new CommandBus($handlers);
69
    }
70
}
71