Completed
Push — master ( 9401a4...2cc7a2 )
by mw
13:59
created

TextCatLanguageDetector   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
c 1
b 0
f 1
lcom 1
cbo 1
dl 0
loc 53
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A setLanguageCandidates() 0 3 1
A detect() 0 8 1
1
<?php
2
3
namespace Onoi\Tesa\LanguageDetector;
4
5
use TextCat;
6
7
/**
8
 * @license GNU GPL v2+
9
 * @since 0.1
10
 *
11
 * @author mwjames
12
 */
13
class TextCatLanguageDetector implements LanguageDetector {
14
15
	const VERION = '0.1';
16
17
	/**
18
	 * @var TextCat
19
	 */
20
	private $textCat;
21
22
	/**
23
	 * @var array|null
24
	 */
25
	private $languageCandidates = null;
26
27
	/**
28
	 * @since 0.1
29
	 *
30
	 * @param TextCat|null $textCat
31
	 */
32
	public function __construct( TextCat $textCat = null ) {
33
		$this->textCat = $textCat;
34
35
		if ( $this->textCat === null ) {
36
			$this->textCat = new TextCat();
37
		}
38
	}
39
40
	/**
41
	 * @since 0.1
42
	 *
43
	 * @param array $languageCandidates
44
	 */
45
	public function setLanguageCandidates( array $languageCandidates ) {
46
		$this->languageCandidates = $languageCandidates;
47
	}
48
49
	/**
50
	 * @since 0.1
51
	 *
52
	 * @param string $text
53
	 *
54
	 * @return string|null
55
	 */
56
	public function detect( $text ) {
57
58
		$languages = $this->textCat->classify( $text, $this->languageCandidates );
0 ignored issues
show
Bug introduced by
It seems like $this->languageCandidates can also be of type array; however, TextCat::classify() does only seem to accept array<integer,string>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
59
		reset( $languages );
60
61
		// For now, only return the best match
62
		return key( $languages );
63
	}
64
65
}
66