AttackingProcess::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
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\AttackWithCard;
10
use Stratadox\CardGame\CommandHandler;
11
use Stratadox\CardGame\Match\Event\TriedAttackingOutOfTurn;
12
use Stratadox\CardGame\Match\Event\TriedAttackingWithUnknownCard;
13
use Stratadox\CardGame\Match\Match;
14
use Stratadox\CardGame\Match\Matches;
15
use Stratadox\CardGame\Match\NoSuchCard;
16
use Stratadox\CardGame\Match\NotYourTurn;
17
use Stratadox\Clock\Clock;
18
19
final class AttackingProcess 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 AttackWithCard);
35
36
        $this->sendIntoBattle(
37
            $this->matches->withId($command->match()),
38
            $command->player(),
39
            $command->cardNumber(),
40
            $command->correlationId()
41
        );
42
    }
43
44
    private function sendIntoBattle(
45
        Match $match,
46
        int $player,
47
        int $cardNumber,
48
        CorrelationId $correlationId
49
    ): void {
50
        try {
51
            $match->attackWithCard($cardNumber, $player, $this->clock->now());
52
        } catch (NoSuchCard $ohNo) {
53
            $this->eventBag->add(new TriedAttackingWithUnknownCard(
54
                $correlationId,
55
                'That card does not exist'
56
            ));
57
            return;
58
        } catch (NotYourTurn $ohNo) {
59
            $this->eventBag->add(new TriedAttackingOutOfTurn(
60
                $correlationId,
61
                $ohNo->getMessage()
62
            ));
63
            return;
64
        }
65
        $this->eventBag->takeFrom($match);
66
    }
67
}
68