ProposalAcceptationProcess::handle()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 17
nc 3
nop 1
dl 0
loc 28
rs 9.7
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CardGame\Proposal;
4
5
use function assert;
6
use Stratadox\CardGame\Command;
7
use Stratadox\CardGame\EventBag;
8
use Stratadox\CardGame\CommandHandler;
9
use Stratadox\Clock\Clock;
10
11
final class ProposalAcceptationProcess implements CommandHandler
12
{
13
    private $clock;
14
    private $proposals;
15
    private $eventBag;
16
17
    public function __construct(
18
        Clock $clock,
19
        ProposedMatches $proposals,
20
        EventBag $eventBag
21
    ) {
22
        $this->clock = $clock;
23
        $this->proposals = $proposals;
24
        $this->eventBag = $eventBag;
25
    }
26
27
    public function handle(Command $command): void
28
    {
29
        assert($command instanceof AcceptTheProposal);
30
31
        $proposal = $this->proposals->withId($command->proposal());
32
        if (!$proposal || !$command->acceptingPlayer()->is($proposal->proposedTo())) {
33
            $this->eventBag->add(
34
                new TriedAcceptingUnknownProposal(
35
                    $command->correlationId(),
36
                    'Proposal not found'
37
                )
38
            );
39
            return;
40
        }
41
42
        try {
43
            $proposal->accept($this->clock->now());
44
        } catch (ProposalHasAlreadyExpired $weAreTooLate) {
45
            $this->eventBag->add(
46
                new TriedAcceptingExpiredProposal(
47
                    $command->correlationId(),
48
                    $weAreTooLate->getMessage()
49
                )
50
            );
51
            return;
52
        }
53
54
        $this->eventBag->takeFrom($proposal);
55
    }
56
}
57