Passed
Push — master ( 30d3d2...4e3abd )
by Jesse
01:56
created

MatchPublisher::events()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CardGame\EventHandler;
4
5
use function assert;
6
use Stratadox\CardGame\DomainEvent;
7
use Stratadox\CardGame\Match\Event\MatchHasBegun;
8
use Stratadox\CardGame\Match\Event\StartedMatchForProposal;
9
use Stratadox\CardGame\ReadModel\Match\OngoingMatch;
10
use Stratadox\CardGame\ReadModel\Match\OngoingMatches;
11
12
final class MatchPublisher implements EventHandler
13
{
14
    private $proposalFor = [];
15
    private $playersFor = [];
16
    private $matches;
17
18
    public function __construct(OngoingMatches $matches)
19
    {
20
        $this->matches = $matches;
21
    }
22
23
    public function events(): iterable
24
    {
25
        return [
26
            StartedMatchForProposal::class,
27
            MatchHasBegun::class,
28
        ];
29
    }
30
31
    public function handle(DomainEvent $event): void
32
    {
33
        if ($event instanceof StartedMatchForProposal) {
34
            $this->setupMatch($event);
35
        } else {
36
            assert($event instanceof MatchHasBegun);
37
            $this->startMatch($event);
38
        }
39
    }
40
41
    private function setupMatch(StartedMatchForProposal $event): void
42
    {
43
        $this->proposalFor[(string) $event->aggregateId()] = $event->proposal();
44
        $this->playersFor[(string) $event->aggregateId()] = $event->players();
45
    }
46
47
    private function startMatch(MatchHasBegun $event): void
48
    {
49
        $this->matches->addFromProposal(
50
            $this->proposalFor[(string) $event->aggregateId()],
51
            new OngoingMatch(
52
                $event->aggregateId(),
53
                $event->whoBegins(),
54
                ...$this->playersFor[(string) $event->aggregateId()]
55
            )
56
        );
57
    }
58
}
59