TurnEndingProcess::handle()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CardGame\Match\Handler;
4
5
use function assert;
6
use Stratadox\CardGame\Command;
7
use Stratadox\CardGame\CorrelationId;
8
use Stratadox\CardGame\EventBag;
9
use Stratadox\CardGame\Match\Command\EndTheTurn;
10
use Stratadox\CardGame\CommandHandler;
11
use Stratadox\CardGame\Match\Event\TriedEndingAlreadyEndedTurn;
12
use Stratadox\CardGame\Match\Match;
13
use Stratadox\CardGame\Match\Matches;
14
use Stratadox\CardGame\Match\NotYourTurn;
15
use Stratadox\Clock\Clock;
16
17
final class TurnEndingProcess implements CommandHandler
18
{
19
    /** @var Matches */
20
    private $matches;
21
    /** @var Clock */
22
    private $clock;
23
    /** @var EventBag */
24
    private $eventBag;
25
26
    public function __construct(Matches $matches, Clock $clock, EventBag $eventBag)
27
    {
28
        $this->matches = $matches;
29
        $this->clock = $clock;
30
        $this->eventBag = $eventBag;
31
    }
32
33
    public function handle(Command $command): void
34
    {
35
        assert($command instanceof EndTheTurn);
36
37
        $this->endTurn(
38
            $this->matches->withId($command->match()),
39
            $command->player(),
40
            $command->correlationId()
41
        );
42
    }
43
44
    private function endTurn(Match $match, int $player, CorrelationId $id): void
45
    {
46
        try {
47
            $match->endTurnOf($player, $this->clock->now());
48
        } catch (NotYourTurn $cannotEndAnything) {
49
            $this->eventBag->add(
50
                new TriedEndingAlreadyEndedTurn(
51
                    $id,
52
                    $cannotEndAnything->getMessage()
53
                )
54
            );
55
            return;
56
        }
57
        $this->eventBag->takeFrom($match);
58
    }
59
}
60