|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace PhpSpellcheck\Spellchecker; |
|
6
|
|
|
|
|
7
|
|
|
use PhpSpellcheck\Misspelling; |
|
8
|
|
|
use PhpSpellcheck\Spellchecker\LanguageTool\LanguageToolApiClient; |
|
9
|
|
|
use PhpSpellcheck\Utils\LineAndOffset; |
|
10
|
|
|
use PhpSpellcheck\Utils\TextEncoding; |
|
11
|
|
|
use Webmozart\Assert\Assert; |
|
12
|
|
|
|
|
13
|
|
|
class LanguageTool implements SpellcheckerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var LanguageToolApiClient |
|
17
|
|
|
*/ |
|
18
|
|
|
private $apiClient; |
|
19
|
|
|
|
|
20
|
4 |
|
public function __construct(LanguageToolApiClient $apiClient) |
|
21
|
|
|
{ |
|
22
|
4 |
|
$this->apiClient = $apiClient; |
|
23
|
4 |
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @return Misspelling[] |
|
27
|
|
|
*/ |
|
28
|
2 |
|
public function check( |
|
29
|
|
|
string $text, |
|
30
|
|
|
array $languages = [], |
|
31
|
|
|
array $context = [], |
|
32
|
|
|
?string $encoding = null |
|
33
|
|
|
): iterable { |
|
34
|
2 |
|
Assert::notEmpty($languages, 'LanguageTool requires at least one language to run it\'s spellchecking process'); |
|
35
|
|
|
|
|
36
|
2 |
|
$check = $this->apiClient->spellCheck($text, $languages, $context[self::class] ?? []); |
|
37
|
2 |
|
|
|
38
|
|
|
foreach ($check['matches'] as $match) { |
|
39
|
2 |
|
list($line, $offsetFromLine) = LineAndOffset::findFromFirstCharacterOffset( |
|
40
|
2 |
|
$text, |
|
41
|
|
|
$match['offset'], |
|
42
|
2 |
|
$encoding ?? TextEncoding::detect($text) |
|
43
|
2 |
|
); |
|
44
|
2 |
|
|
|
45
|
2 |
|
yield new Misspelling( |
|
|
|
|
|
|
46
|
2 |
|
mb_substr($match['context']['text'], $match['context']['offset'], $match['context']['length']), |
|
47
|
2 |
|
$offsetFromLine, |
|
48
|
|
|
$line, // line break index transformed in line number |
|
49
|
2 |
|
array_column($match['replacements'], 'value'), |
|
50
|
2 |
|
array_merge( |
|
51
|
2 |
|
[ |
|
52
|
|
|
'sentence' => $match['sentence'], |
|
53
|
2 |
|
'spellingErrorMessage' => $match['message'], |
|
54
|
|
|
'ruleUsed' => $match['rule'], |
|
55
|
|
|
], |
|
56
|
|
|
$context |
|
57
|
2 |
|
) |
|
58
|
|
|
); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
2 |
|
/** |
|
63
|
|
|
* @return string[] |
|
64
|
2 |
|
*/ |
|
65
|
|
|
public function getSupportedLanguages(): array |
|
66
|
|
|
{ |
|
67
|
2 |
|
return $this->apiClient->getSupportedLanguages(); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|