Word::contains()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Hangman;
4
5
class Word
6
{
7
    private $word;
8
9
    /**
10
     * Word constructor.
11
     *
12
     * @param $word
13
     */
14 132
    public function __construct($word)
15
    {
16 132
        $this->word = strtoupper($word);
17 132
    }
18
19
    /**
20
     * Get the letters of the word
21
     *
22
     * @return string[]
23
     */
24 48
    public function getLetters()
25
    {
26 48
        $letters = array_unique(str_split(strtoupper($this->word)));
27 48
        sort($letters);
28 48
        return $letters;
29
    }
30
31
    /**
32
     * Build the word from played letters
33
     *
34
     * @param string[] $playedLetters
35
     *
36
     * @return string
37
     */
38 45
    public function buildWord($playedLetters)
39
    {
40 45
        $wordLetters = $this->getLetters();
41 45
        $playedLetters = array_map(function ($letter) {
42 30
            return strtoupper($letter);
43 45
        }, $playedLetters);
44 45
        $goodLetters = array_intersect($wordLetters, $playedLetters);
45 45
        $splitWord = str_split($this->word);
46
47 45
        $word = '';
48 45
        foreach ($splitWord as $letter) {
49 45
            $word .= (in_array($letter, $goodLetters) ? $letter : '_') . ' ';
50 30
        }
51
52 45
        return trim($word);
53
    }
54
55
    /**
56
     * Checks if the answer is valid
57
     *
58
     * @param string $answer
59
     *
60
     * @return bool
61
     */
62 15
    public function isValid($answer)
63
    {
64 15
        return strlen($answer) === strlen($this->word);
65
    }
66
67
    /**
68
     * Returns if the letter is contained in the word
69
     *
70
     * @param string $letter
71
     *
72
     * @return boolean
73
     */
74 18
    public function contains($letter)
75
    {
76 18
        return strpos($this->word, strtoupper($letter)) !== false;
77
    }
78
79
    /**
80
     * @param string $word
81
     *
82
     * @return bool
83
     */
84 12
    public function equals($word)
85
    {
86 12
        return ($this->word === strtoupper($word));
87
    }
88
89
    /**
90
     * @return string
91
     */
92 30
    public function __toString()
93
    {
94 30
        return $this->word;
95
    }
96
}
97