Passed
Push — main ( a57e19...f52e71 )
by Vedrana
28:10
created

GameBlackJackValidateService   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 47
ccs 18
cts 18
cp 1
rs 10
c 1
b 0
f 0
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validateInput() 0 15 5
A validateBet() 0 14 4
1
<?php
2
3
namespace App\Service;
4
5
use App\Card\BlackJack;
6
7
/**
8
 * Service class for BlackJack game handling the input from post.
9
 *
10
 * This class validates user input and bets.
11
 *
12
 */
13
class GameBlackJackValidateService
14
{
15
    /**
16
     * Validate the bet amount against game state.
17
     *
18
     * @param BlackJack|null $blackJack The current game instance.
19
     * @param int $betAmount The amount to bet.
20
     * @param int $numHands Number of hands to play in new round.
21
     * @return string|null Error message if validation fails, otherwise null.
22
     */
23 3
    public function validateBet(?BlackJack $blackJack, int $betAmount, int $numHands = 1): ?string
24
    {
25 3
        if ($betAmount <= 0) {
26 1
            return 'Invalid bet amount.';
27
        }
28
29
        // If no game exists yet, assume starting balance 1000
30 2
        $balance = $blackJack ? $blackJack->getBalance() : 1000;
31 2
        $totalBet = $betAmount * $numHands;
32 2
        if ($totalBet > $balance) {
33 1
            return 'Your bet exceeds your current balance.';
34
        }
35
36 1
        return null;
37
    }
38
39
    /**
40
     * Validate input from request.
41
     *
42
     * @param array<string, string> $data
43
     * @return array{playerName: string, betAmount: int, numHands: int}|string
44
     */
45 2
    public function validateInput(array $data): array|string
46
    {
47
        // Extract and validate input from POST
48 2
        $playerName = trim((string) ($data['playerName'] ?? ''));
49 2
        $betAmount = (int) ($data['betAmount'] ?? 0);
50 2
        $numHands = (int) ($data['numHands'] ?? 1);
51
52 2
        if ($playerName === '' || $betAmount <= 0 || $numHands < 1 || $numHands > 3) {
53 1
            return "Invalid input.";
54
        }
55
56 1
        return [
57 1
            'playerName' => $playerName,
58 1
            'betAmount' => $betAmount,
59 1
            'numHands' => $numHands,
60 1
        ];
61
    }
62
}
63