-
Notifications
You must be signed in to change notification settings - Fork 0
/
Suggestions.php
72 lines (54 loc) · 1.84 KB
/
Suggestions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
namespace uzdevid\matn;
use yii\base\Exception;
use yii\helpers\Html;
/**
* @property string $language
* @property string $text
* @property-read array $suggestions
*/
class Suggestions extends BaseMatn {
private string $_text;
private array $_suggestions = [];
public string $method = '/suggestions';
public function isCorrect(): bool {
if (empty($this->text)) {
throw new Exception('Text is required');
}
$hasError = false;
foreach ($this->splitText() as $chunk) {
$raw = [
'text' => Html::decode($chunk)
];
$response = $this->curlExecute($this->url, $raw);
if ($response['errors']) {
$hasError = true;
}
$this->_suggestions = array_merge($this->_suggestions, $response['data']);
}
return $hasError;
}
public function getText(): string {
return $this->_text;
}
public function setText(string $text): static {
$this->_text = strip_tags($text);
$this->_text = html_entity_decode($this->_text);
$this->_text = preg_replace('/\s+/', ' ', $this->_text);
$this->_text = preg_replace('/\s*\n\s*/', "\n", $this->_text);
return $this;
}
public function getSuggestions(): array {
return $this->_suggestions;
}
public function highlight(): string {
$replacements = [];
foreach ($this->suggestions as $suggestion) {
$word = $suggestion["word"];
$suggestions = implode(', ', $suggestion["suggestions"]);
$replacement = "<span style='color: red;' title='{$suggestions}'>$word</span>";
$replacements[$word] = $replacement;
}
return str_replace(array_keys($replacements), array_values($replacements), $this->text);
}
}