BlockingProcess::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 8
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\BlockTheAttacker;
10
use Stratadox\CardGame\CommandHandler;
11
use Stratadox\CardGame\Match\Event\TriedBlockingOutOfTurn;
12
use Stratadox\CardGame\Match\Match;
13
use Stratadox\CardGame\Match\Matches;
14
use Stratadox\CardGame\Match\NoSuchCard;
15
use Stratadox\CardGame\Match\NotYourTurn;
16
use Stratadox\Clock\Clock;
17
18
final class BlockingProcess implements CommandHandler
19
{
20
    /** @var Matches */
21
    private $matches;
22
    /** @var Clock */
23
    private $clock;
24
    /** @var EventBag */
25
    private $eventBag;
26
27
    public function __construct(
28
        Matches $matches,
29
        Clock $clock,
30
        EventBag $eventBag
31
    ) {
32
        $this->matches = $matches;
33
        $this->clock = $clock;
34
        $this->eventBag = $eventBag;
35
    }
36
37
    public function handle(Command $command): void
38
    {
39
        assert($command instanceof BlockTheAttacker);
40
41
        $this->sendIntoBattle(
42
            $this->matches->withId($command->match()),
43
            $command->player(),
44
            $command->defender(),
45
            $command->attacker(),
46
            $command->correlationId()
47
        );
48
    }
49
50
    private function sendIntoBattle(
51
        Match $match,
52
        int $thePlayer,
53
        int $defender,
54
        int $attacker,
55
        CorrelationId $correlationId
56
    ): void {
57
        try {
58
            $match->defendAgainst(
59
                $attacker,
60
                $defender,
61
                $thePlayer,
62
                $this->clock->now()
63
            );
64
        } catch (NoSuchCard $ohNo) {
65
            $this->eventBag->add(new TriedBlockingOutOfTurn(
66
                $correlationId,
67
                'No such defender'
68
            ));
69
            return;
70
        } catch (NotYourTurn $ohNo) {
71
            $this->eventBag->add(new TriedBlockingOutOfTurn(
72
                $correlationId,
73
                $ohNo->getMessage()
74
            ));
75
            return;
76
        }
77
78
        $this->eventBag->takeFrom($match);
79
    }
80
}
81