Completed
Push — master ( 252970...4a8c07 )
by Faiz
02:03
created

Levenshtein::closest()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 44
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 44
ccs 19
cts 19
cp 1
rs 6.7272
cc 7
eloc 17
nc 10
nop 2
crap 7
1
<?php
2
3
namespace FaizShukri\Quran\Supports;
4
5
class Levenshtein
6
{
7 12
    public function closest($input, array $words)
8
    {
9
        // no shortest distance found, yet
10 12
        $shortest = -1;
11 12
        $match = [];
12
13
        // loop through words to find the closest
14 12
        foreach ($words as $word) {
15
16
            // calculate the distance between the input word,
17
            // and the current word
18 12
            $lev = levenshtein(strtolower($input), strtolower($word), 1, 2, 3);
19
20
            // check for an exact match
21 12
            if ($lev == 0) {
22
23
                // closest word is this one (exact match)
24 3
                $match = [$word];
25
                // $closest = $word;
26 3
                $shortest = 0;
27
28
                // break out of the loop; we've found an exact match
29 3
                break;
30
            }
31
32
            // if this distance is less than the next found shortest
33
            // distance, OR if a next shortest word has not yet been found
34
35 9
            if ($lev < $shortest || $shortest < 0) {
36
                // set the closest match, and shortest distance
37 9
                $match = [$word];
38
                // $closest = $word;
39 9
                $shortest = $lev;
40 9
            } elseif ($lev == $shortest) {
41 7
                $match[] = $word;
42 4
            }
43 8
        }
44
45 12
        if ($shortest > 6) {
46 3
            return [];
47
        }
48
49 9
        return $match;
50
    }
51
}
52