Test Setup Failed
Push — master ( a63fa0...36623d )
by Jesse
04:59
created

Battlefield::remove()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\CardGame\ReadModel\Match;
4
5
use function array_filter;
6
use function array_merge;
7
use function current;
8
9
class Battlefield
10
{
11
    private $cards;
12
13
    public static function untouched(): self
14
    {
15
        return new self();
16
    }
17
18
    public function addFor(int $owner, Card $card): void
19
    {
20
        $this->cards[$owner][] = $card;
21
    }
22
23
    public function removeFrom(int $owner, int $cardToRemove): void
24
    {
25
        $this->cards[$owner] = array_filter(
26
            $this->cards[$owner],
27
            static function (Card $card) use ($cardToRemove): bool {
28
                return $card->offset() !== $cardToRemove;
29
            }
30
        );
31
    }
32
33
    /** @return Card[] */
34
    public function cardsInPlay(): array
35
    {
36
        // @todo this fails if all cards die: by then cards isn't null but []
37
        return array_merge(...$this->cards ?? [[]]);
38
    }
39
40
    /** @return Card[] */
41
    public function cardsInPlayFor(int $player): array
42
    {
43
        return $this->cards[$player];
44
    }
45
46
    public function getSentIntoBattleBy(int $player, int $attacker): void
47
    {
48
        $this->card($attacker, $player)->attack();
49
    }
50
51
    public function getSentToDefendBy(int $player, int $defender): void
52
    {
53
        $this->card($defender, $player)->defend();
54
    }
55
56
    public function getSentToRegroupBy(int $player, int $veteran): void
57
    {
58
        $this->card($veteran, $player)->regroup();
59
    }
60
61
    /** @return Card[] */
62
    public function attackers(): array
63
    {
64
        return array_filter(
65
            $this->cardsInPlay(),
66
            static function (Card $card): bool {
67
                return $card->isAttacking();
68
            }
69
        );
70
    }
71
72
    /** @return Card[] */
73
    public function defenders(): array
74
    {
75
        return array_filter(
76
            $this->cardsInPlay(),
77
            static function (Card $card): bool {
78
                return $card->isDefending();
79
            }
80
        );
81
    }
82
83
    private function card(int $offset, int $player): Card
84
    {
85
        return current(array_filter(
86
            $this->cardsInPlayFor($player),
87
            static function (Card $card) use ($offset): bool {
88
                return $card->offset() === $offset;
89
            }
90
        ));
91
    }
92
}
93