CardPlayingProcess   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 46
rs 10
c 1
b 0
f 0
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 9 1
A play() 0 21 3
A __construct() 0 5 1
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\CommandHandler;
10
use Stratadox\CardGame\Match\Match;
11
use Stratadox\CardGame\Match\Matches;
12
use Stratadox\CardGame\Match\NotEnoughMana;
13
use Stratadox\CardGame\Match\NotYourTurn;
14
use Stratadox\CardGame\Match\Event\PlayerDidNotHaveTheMana;
15
use Stratadox\CardGame\Match\Command\PlayTheCard;
16
use Stratadox\CardGame\Match\Event\TriedPlayingCardOutOfTurn;
17
use Stratadox\Clock\Clock;
18
19
final class CardPlayingProcess implements CommandHandler
20
{
21
    private $matches;
22
    private $clock;
23
    private $eventBag;
24
25
    public function __construct(Matches $matches, Clock $clock, EventBag $eventBag)
26
    {
27
        $this->matches = $matches;
28
        $this->clock = $clock;
29
        $this->eventBag = $eventBag;
30
    }
31
32
    public function handle(Command $command): void
33
    {
34
        assert($command instanceof PlayTheCard);
35
36
        $this->play(
37
            $this->matches->withId($command->match()),
38
            $command->player(),
39
            $command->cardNumber(),
40
            $command->correlationId()
41
        );
42
    }
43
44
    private function play(
45
        Match $match,
46
        int $player,
47
        int $cardNumber,
48
        CorrelationId $correlationId
49
    ): void {
50
        try {
51
            $match->playTheCard($cardNumber, $player, $this->clock->now());
52
        } catch (NotEnoughMana $problem) {
53
            $this->eventBag->add(new PlayerDidNotHaveTheMana(
54
                $correlationId,
55
                $problem->getMessage()
56
            ));
57
        } catch (NotYourTurn $problem) {
58
            $this->eventBag->add(new TriedPlayingCardOutOfTurn(
59
                $correlationId,
60
                $problem->getMessage()
61
            ));
62
        }
63
64
        $this->eventBag->takeFrom($match);
65
    }
66
}
67