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
|
|
|
|