Deck::drawMoreCards()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
ccs 8
cts 8
cp 1
crap 3
rs 10
1
<?php
2
3
namespace App\Card;
4
5
/**
6
 * Class Deck represents a standard deck of playing cards.
7
 */
8
class Deck
9
{
10
    /** @var Card[] */
11
    protected array $cards;
12
13 26
    public function __construct()
14
    {
15 26
        $this->cards = [];
16
17 26
        $suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
18 26
        $values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'];
19
20
        // Generate the deck
21 26
        foreach ($suits as $suit) {
22 26
            foreach ($values as $value) {
23 26
                $this->cards[] = new Card($suit, $value);
24
            }
25
        }
26
    }
27
28
    /**
29
     * @return Card[]
30
     */
31 11
    public function getCards(): array
32
    {
33 11
        return $this->cards;
34
    }
35
36 14
    public function shuffle(): void
37
    {
38 14
        shuffle($this->cards);
39
    }
40
41
    /**
42
     * Draw a single card from the deck
43
     *
44
     * @return Card|null
45
     */
46 14
    public function drawCard(): ?Card
47
    {
48 14
        if (count($this->cards) <= 0) {
49 5
            return null;
50
        }
51
        // Get a random index for the card to draw
52 14
        $randomIndex = (int) array_rand($this->cards);
53 14
        $drawnCard = $this->cards[$randomIndex];
54
55
        // Remove the drawn card from the deck
56 14
        array_splice($this->cards, $randomIndex, 1);
57 14
        return $drawnCard;
58
    }
59
60
    /**
61
     * Draw multiple cards
62
     *
63
     * @return Card[]
64
     */
65 6
    public function drawMoreCards(int $num): array
66
    {
67 6
        $drawnCards = [];
68
69 6
        for ($i = 0; $i < $num; $i++) {
70 6
            $drawnCard = $this->drawCard();
71 6
            if ($drawnCard === null) {
72 1
                return $drawnCards;
73
            }
74 6
            $drawnCards[] = $drawnCard;
75
        }
76
77 6
        return $drawnCards;
78
    }
79
80 8
    public function remainingCards(): int
81
    {
82 8
        return count($this->cards);
83
    }
84
85
    /**
86
     * Get the cards as arrays.
87
     *
88
     * @return array<int, array<string, string>>
89
     */
90 6
    public function getCardsAsArray(): array
91
    {
92 6
        return array_map(function (Card $card) {
93 6
            return $card->toArray();
94 6
        }, $this->cards);
95
    }
96
}
97