TextCatLanguageDetector::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
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 2
	public function __construct( TextCat $textCat = null ) {
33 2
		$this->textCat = $textCat;
34
35 2
		if ( $this->textCat === null ) {
36 1
			$this->textCat = new TextCat();
37 1
		}
38 2
	}
39
40
	/**
41
	 * @since 0.1
42
	 *
43
	 * @param array $languageCandidates
44
	 */
45 1
	public function setLanguageCandidates( array $languageCandidates ) {
46 1
		$this->languageCandidates = $languageCandidates;
47 1
	}
48
49
	/**
50
	 * @since 0.1
51
	 *
52
	 * @param string $text
53
	 *
54
	 * @return string|null
55
	 */
56 1
	public function detect( $text ) {
57
58 1
		$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 1
		reset( $languages );
60
61
		// For now, only return the best match
62 1
		return key( $languages );
63
	}
64
65
}
66