Passed
Push — master ( ca71fa...a18c2c )
by Sebastian
02:51
created

WordSplitter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * @package Application Utils
4
 * @subpackage ConvertHelper
5
 * @see \AppUtils\ConvertHelper\WordSplitter
6
 */
7
8
declare(strict_types=1);
9
10
namespace AppUtils\ConvertHelper;
11
12
/**
13
 * @package Application Utils
14
 * @subpackage ConvertHelper
15
 * @author Sebastian Mordziol <[email protected]>
16
 */
17
class WordSplitter
18
{
19
    private string $subject;
20
    private bool $removeDuplicates = false;
21
    private bool $sorting = false;
22
    private int $minWordLength = 0;
23
    private bool $duplicatesCaseInsensitive;
24
25
    public function __construct(string $subject)
26
    {
27
        $this->subject = $subject;
28
    }
29
30
    public function setRemoveDuplicates(bool $remove=true, bool $caseInsensitive=false) : self
31
    {
32
        $this->removeDuplicates = $remove;
33
        $this->duplicatesCaseInsensitive = $caseInsensitive;
34
        return $this;
35
    }
36
37
    public function setSorting(bool $sorting=true) : self
38
    {
39
        $this->sorting = $sorting;
40
        return $this;
41
    }
42
43
    public function setMinWordLength(int $length) : self
44
    {
45
        $this->minWordLength = $length;
46
        return $this;
47
    }
48
49
    public function split() : array
50
    {
51
        $words = preg_split("/\W+/", $this->subject);
52
53
        $words = $this->filterEmpty($words);
54
55
        if($this->removeDuplicates) {
56
            $words = $this->filterDuplicates($words);
57
        }
58
59
        if($this->sorting) {
60
            usort($words, 'strnatcasecmp');
61
        }
62
63
        return $words;
64
    }
65
66
    private function filterDuplicates(array $words) : array
67
    {
68
        if($this->duplicatesCaseInsensitive) {
69
            return $this->filterDuplicatesCaseInsensitive($words);
70
        }
71
72
        return array_unique($words);
73
    }
74
75
    private function filterDuplicatesCaseInsensitive(array $array) : array
76
    {
77
        return array_intersect_key(
78
            $array,
79
            array_unique( array_map( "strtolower", $array ) )
80
        );
81
    }
82
83
    /**
84
     * @param string[] $words
85
     * @return string[]
86
     */
87
    private function filterEmpty(array $words) : array
88
    {
89
        $keep = array();
90
91
        foreach($words as $word)
92
        {
93
            if(empty($word)) {
94
                continue;
95
            }
96
97
            if(mb_strlen($word) < $this->minWordLength) {
98
                continue;
99
            }
100
101
            $keep[] = $word;
102
        }
103
104
        return $keep;
105
    }
106
}
107