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

GameBlackJackValidateService::validateInput()   A

Complexity

Conditions 5
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
nc 2
nop 1
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
c 1
b 0
f 0
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