DummyCommandHandler::handle()   A
last analyzed

Complexity

Conditions 3
Paths 24

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 3
b 0
f 0
nc 24
nop 1
dl 0
loc 17
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing\TestUtilities\TestingAggregates;
6
7
use EventSauce\EventSourcing\AggregateRootRepository;
8
use function get_class;
9
10
/**
11
 * @testAsset
12
 */
13
class DummyCommandHandler
14
{
15
    private array $commandToMethodMap = [
16
        PerformDummyTask::class => 'performDummyTask',
17
        IgnoredCommand::class => 'dontDoAnything',
18
        ExceptionInducingCommand::class => 'throwAnException',
19
        DummyIncrementCommand::class => 'increment',
20
    ];
21
22
    /**
23
     * @phpstan-var AggregateRootRepository<DummyAggregate>
24
     */
25
    private AggregateRootRepository $repository;
26
27
    /**
28
     * @phpstan-param AggregateRootRepository<DummyAggregate> $repository
29
     */
30
    public function __construct(AggregateRootRepository $repository)
31
    {
32
        $this->repository = $repository;
33
    }
34
35
    /**
36
     * @throws DummyException
37
     */
38
    public function handle(DummyCommand $command): void
39
    {
40
        try {
41
            if ($command instanceof InitiatorCommand) {
42
                $aggregate = DummyAggregate::create($command->aggregateRootId());
43
44
                return;
45
            }
46
47
            /** @var DummyAggregate $aggregate */
48
            $aggregate = $this->repository->retrieve($command->aggregateRootId());
49
            /** @var string $method */
50
            $method = $this->commandToMethodMap[get_class($command)];
51
            $aggregate->{$method}();
52
        } finally {
53
            if (isset($aggregate)) {
54
                $this->repository->persist($aggregate);
55
            }
56
        }
57
    }
58
}
59