CardValidator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
c 2
b 0
f 0
lcom 0
cbo 0
dl 0
loc 66
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A areValid() 0 12 4
A areCardsFormatValid() 0 10 3
A hasNoCardDuplication() 0 12 3
1
<?php
2
3
namespace Bourdeau\Bundle\HandEvaluatorBundle\HandEvaluator;
4
5
/**
6
 * CardValidator
7
 *
8
 * Validate that the given cards are a valid set of cards for Texas Holdem Poker
9
 *
10
 * @author Pierre-Henri Bourdeau <[email protected]>
11
 */
12
class CardValidator
13
{
14
    const VALID_CARDS = [
15
        'AD', 'KD', 'QD', 'JD', '10D', '9D', '8D', '7D', '6D', '5D', '4D', '3D', '2D',
16
        'AH', 'KH', 'QH', 'JH', '10H', '9H', '8H', '7H', '6H', '5H', '4H', '3H', '2H',
17
        'AC', 'KC', 'QC', 'JC', '10C', '9C', '8C', '7C', '6C', '5C', '4C', '3C', '2C',
18
        'AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',
19
    ];
20
21
    /**
22
     * The main class method
23
     *
24
     * @param  array $cards
25
     *
26
     * @return boolean
27
     */
28
    public function areValid(array $cards)
29
    {
30
        if (count($cards) != 7) {
31
             throw new \Exception("It's Texas Holdem! You need 7 cards!");
32
        }
33
34
        if ($this->areCardsFormatValid($cards) && $this->hasNoCardDuplication($cards)) {
35
            return true;
36
        }
37
38
        return false;
39
    }
40
41
    /**
42
     * Check if the cards are in a valid format
43
     *
44
     * @param  array  $cards
45
     * @return boolean
46
     */
47
    private function areCardsFormatValid(array $cards)
48
    {
49
        foreach ($cards as $card) {
50
            if (!in_array($card, self::VALID_CARDS)) {
51
                throw new \Exception(sprintf("The card %s is not in a valid format!", $card));
52
            }
53
        }
54
55
        return true;
56
    }
57
58
    /**
59
     * Look for card duplication
60
     *
61
     * @param  array  $cards
62
     *
63
     * @return boolean
64
     */
65
    private function hasNoCardDuplication(array $cards)
66
    {
67
        $values = array_count_values($cards);
68
69
        foreach ($values as $key => $value) {
70
            if ($value > 1) {
71
                throw new \Exception(sprintf("The card %s is duplicate!", $key));
72
            }
73
        }
74
75
        return true;
76
    }
77
}
78