CardHand   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 62
ccs 25
cts 25
cp 1
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getCards() 0 3 1
A addCard() 0 3 1
B getTotal() 0 25 7
A toArray() 0 7 2
1
<?php
2
3
namespace App\Card;
4
5
/**
6
 * Class CardHand represents a hand of cards.
7
 */
8
class CardHand
9
{
10
    /** @var Card[] */
11
    private array $cards = [];
12
13 6
    public function addCard(Card $card): void
14
    {
15 6
        $this->cards[] = $card;
16
    }
17
18
    /**
19
     * @return Card[]
20
     */
21 2
    public function getCards(): array
22
    {
23 2
        return $this->cards;
24
    }
25
26
    /**
27
     * Get total points of the hand.
28
     * Handle the Aces.
29
     * @return int
30
     */
31 5
    public function getTotal(): int
32
    {
33 5
        $sum = 0;
34 5
        $aces = [];
35
36 5
        foreach ($this->cards as $card) {
37 4
            if ($card->getValue() === 'Ace') {
38 3
                $aces[] = $card;
39 3
                continue;
40
            }
41 2
            $sum += $card->getNumericValue();
42
        }
43 5
        $numAces = count($aces);
44
45 5
        if ($numAces === 2) {
46
            // If 2 Aces — one counts as 14, one as 1
47 1
            $sum += 14 + 1;
48 4
        } elseif ($numAces === 1) {
49
            // One Ace — check the current sum
50 1
            $sum += ($sum + 14 <= 21) ? 14 : 1;
51 3
        } elseif ($numAces > 2) {
52
            // More than 2 Aces — treat one as 14, one as 1, rest as 1
53 1
            $sum += 14 + 1 + ($numAces - 2) * 1;
54
        }
55 5
        return $sum;
56
    }
57
58
    /**
59
     * Convert the hand to an array.
60
     *
61
     * @return array<int, array<string, string>>
62
     */
63 1
    public function toArray(): array
64
    {
65 1
        $array = [];
66 1
        foreach ($this->cards as $card) {
67 1
            $array[] = $card->toArray();
68
        }
69 1
        return $array;
70
    }
71
}
72