|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Stratadox\CardGame\EventHandler; |
|
4
|
|
|
|
|
5
|
|
|
use Stratadox\CardGame\Match\MatchId; |
|
6
|
|
|
use Stratadox\CardGame\ReadModel\Proposal\MatchProposal; |
|
7
|
|
|
use Stratadox\CardGame\ReadModel\Proposal\MatchProposals; |
|
8
|
|
|
use function assert; |
|
9
|
|
|
use Stratadox\CardGame\DomainEvent; |
|
10
|
|
|
use Stratadox\CardGame\Match\Event\MatchStarted; |
|
11
|
|
|
use Stratadox\CardGame\Match\Event\StartedMatchForProposal; |
|
12
|
|
|
use Stratadox\CardGame\ReadModel\Match\OngoingMatch; |
|
13
|
|
|
use Stratadox\CardGame\ReadModel\Match\OngoingMatches; |
|
14
|
|
|
|
|
15
|
|
|
final class MatchPublisher implements EventHandler |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var MatchProposal[] */ |
|
18
|
|
|
private $proposalFor = []; |
|
19
|
|
|
/** @var OngoingMatches */ |
|
20
|
|
|
private $matches; |
|
21
|
|
|
/** @var MatchProposals */ |
|
22
|
|
|
private $proposals; |
|
23
|
|
|
|
|
24
|
|
|
public function __construct(OngoingMatches $matches, MatchProposals $proposals) |
|
25
|
|
|
{ |
|
26
|
|
|
$this->matches = $matches; |
|
27
|
|
|
$this->proposals = $proposals; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function events(): iterable |
|
31
|
|
|
{ |
|
32
|
|
|
return [ |
|
33
|
|
|
StartedMatchForProposal::class, |
|
34
|
|
|
MatchStarted::class, |
|
35
|
|
|
]; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function handle(DomainEvent $event): void |
|
39
|
|
|
{ |
|
40
|
|
|
if ($event instanceof StartedMatchForProposal) { |
|
41
|
|
|
$this->setupMatch($event); |
|
42
|
|
|
} else { |
|
43
|
|
|
assert($event instanceof MatchStarted); |
|
44
|
|
|
$this->startMatch($event->aggregateId(), $event->whoBegins()); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
private function setupMatch(StartedMatchForProposal $event): void |
|
49
|
|
|
{ |
|
50
|
|
|
$this->proposalFor[(string) $event->aggregateId()] = $this->proposals->byId($event->proposal()); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
private function startMatch(MatchId $match, int $whoBegins): void |
|
54
|
|
|
{ |
|
55
|
|
|
$this->proposalFor[$match->id()]->begin($match); |
|
56
|
|
|
$this->matches->addFromProposal( |
|
57
|
|
|
$this->proposalFor[$match->id()]->id(), |
|
58
|
|
|
new OngoingMatch($match, $whoBegins) |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|