Test Failed
Push — master ( 1c9069...553f57 )
by Pol
01:58
created

NGramsTrait::doNgrams()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 9
nc 12
nop 3
1
<?php
2
3
namespace drupol\phpngrams;
4
5
trait NGramsTrait
6
{
7
    /**
8
     * @param array $data
9
     * @param int $n
10
     * @param bool $cyclic
11
     *
12
     * @return \Generator
13
     */
14
    public function ngramsArray(array $data, $n = 1, $cyclic = true)
15
    {
16
        return $this->doNgrams($data, $n, $cyclic);
17
    }
18
19
    /**
20
     * @param $data
21
     * @param int $n
22
     * @param bool $cyclic
23
     *
24
     * @return \Generator
25
     */
26
    public function ngramsString($data, $n = 1, $cyclic = true)
27
    {
28
        foreach ($this->doNgrams(str_split($data), $n, $cyclic) as $data) {
29
            yield implode('', $data);
30
        }
31
    }
32
33
    /**
34
     * @param $data
35
     * @param $n
36
     * @param $cyclic
37
     *
38
     * @return \Generator
39
     */
40
    private function doNgrams($data, $n = 1, $cyclic = true)
41
    {
42
        $dataLength = count($data);
43
44
        $n = $n > $dataLength ? $dataLength : $n;
45
46
        $length = (false === $cyclic ? $dataLength - $n + 1 : $dataLength);
47
48
        for ($j = 0; $j < $length; $j++) {
49
            $ngrams = [];
50
            for ($i = $j; $i < $n + $j; $i++) {
51
                $ngrams[] = $data[$i%$dataLength];
52
            }
53
            yield $ngrams;
54
        }
55
    }
56
}
57