Passed
Push — master ( 22f2b2...f1c910 )
by Arthur
04:05
created

Words::setData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace detox\core;
4
5
6
use detox\dataset\SetContract;
7
8
class Words
9
{
10
11
    public const MAX_SCORE        = 1;
12
    public const ASTERISKS_MIDDLE = 0.8;
13
    public const ASTERISKS_LEFT   = 0.5;
14
    public const ASTERISKS_RIGHT  = 0.6;
15
16
    protected $dataSet;
17
    protected $score = 0;
18
19
    /**
20
     * Words constructor.
21
     *
22
     * @param SetContract $set
23
     */
24
    public function __construct(SetContract $set)
25
    {
26
        $this->dataSet = $set;
27
    }
28
29
    /**
30
     * @param string $source
31
     */
32
    public function processWords(string $source) : void
33
    {
34
        // to match lower case letters in words set array
35
        $lowerSource = $this->addLowSpaces($source);
36
        /**
37
         * @var string $points
38
         * @var array $words
39
         */
40
        foreach ($this->dataSet->getWords() as $points => $words) {
41
            foreach ($words as $word) {
42
                if (mb_strpos($lowerSource, ' ' . $word . ' ') !== false) {
43
                    $this->score += (float)$points;
44
                }
45
                if ($this->score >= self::MAX_SCORE) {
46
                    $this->score = self::MAX_SCORE;
47
48
                    // we don't need to iterate more with max score
49
                    return;
50
                }
51
            }
52
        }
53
    }
54
55
    /**
56
     * @param string $source
57
     */
58
    public function processPatterns(string $source) : void
59
    {
60
        $lowerSource = $this->addLowSpaces($source);
61
        if (preg_match('/\s(([\w]+)[\*]+([\w]+))\s/', $lowerSource) === 1) {
62
            $this->score += self::ASTERISKS_MIDDLE;
63
        } else if (preg_match('/\s(([\w]+)[\*]+)/', $lowerSource) === 1) {
64
            $this->score += self::ASTERISKS_RIGHT;
65
        } else if (preg_match('/([\*]+([\w]+))\s/', $lowerSource) === 1) {
66
            $this->score += self::ASTERISKS_LEFT;
67
        }
68
    }
69
70
    /**
71
     * @param SetContract $set
72
     */
73
    public function setData(SetContract $set) : void
74
    {
75
        $this->dataSet = $set;
76
    }
77
78
    /**
79
     * @return float
80
     */
81
    public function getScore() : float
82
    {
83
        return $this->score;
84
    }
85
86
    /**
87
     * @param float $score
88
     */
89
    public function setScore(float $score) : void
90
    {
91
        $this->score = $score;
92
    }
93
94
    /**
95
     * @param string $str
96
     * @return string
97
     */
98
    protected function addLowSpaces(string $str) : string
99
    {
100
        return ' ' . mb_strtolower($str) . ' ';
101
    }
102
}