1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CodeblogPro\YandexSpeller\Application\Services\YandexSpeller; |
4
|
|
|
|
5
|
|
|
use CodeblogPro\YandexSpeller\Application\Contracts\AnswerInterface; |
6
|
|
|
use CodeblogPro\YandexSpeller\Application\Contracts\YandexSpellerInterface; |
7
|
|
|
use CodeblogPro\YandexSpeller\Application\Models\Answer; |
8
|
|
|
use CodeblogPro\YandexSpeller\Application\Services\YandexSpeller\Resolvers\CurlRequestContentResolver; |
9
|
|
|
|
10
|
|
|
class YandexSpellerService implements YandexSpellerInterface |
11
|
|
|
{ |
12
|
|
|
public function getAnswerByString(string $sourceString): ?AnswerInterface |
13
|
|
|
{ |
14
|
|
|
$yandexSpellerRequestResolver = resolve(CurlRequestContentResolver::class); |
|
|
|
|
15
|
|
|
$curlContent = $yandexSpellerRequestResolver->handle( |
16
|
|
|
config('yandexspeller.yandex_speller_api_url'), |
|
|
|
|
17
|
|
|
[ |
18
|
|
|
'text' => $sourceString |
19
|
|
|
], |
20
|
|
|
[ |
21
|
|
|
CURLOPT_TIMEOUT => config('yandexspeller.yandex_speller_curlopt_timeout'), |
22
|
|
|
CURLOPT_CONNECTTIMEOUT => config('yandexspeller.yandex_speller_curlopt_connecttimeout'), |
23
|
|
|
] |
24
|
|
|
); |
25
|
|
|
|
26
|
|
|
$correctedStringArray = []; |
27
|
|
|
|
28
|
|
|
if (empty($curlContent['result']) || (bool)$curlContent['result'] === false) { |
29
|
|
|
return null; |
30
|
|
|
} else { |
31
|
|
|
$curlContentResult = json_decode($curlContent['result']); |
32
|
|
|
$spellResult = (is_array($curlContentResult)) ? current($curlContentResult) : []; |
33
|
|
|
$correctionMap = []; |
34
|
|
|
|
35
|
|
|
// @ToDo: Now the first correction is taken for each word. It is necessary to give the functional |
36
|
|
|
// of obtaining all possible permutations. Accordingly, $resultText will become an array |
37
|
|
|
foreach ($spellResult as $correction) { |
38
|
|
|
if (!isset($correction->word) || empty($correction->s) || current($correction->s) === $sourceString) { |
39
|
|
|
continue; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$correctionMap[$correction->word] = current($correction->s); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (!empty($correctionMap)) { |
46
|
|
|
$correctedStringArray[] = str_replace( |
47
|
|
|
array_keys($correctionMap), |
48
|
|
|
array_values($correctionMap), |
49
|
|
|
$sourceString |
50
|
|
|
); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return resolve( |
55
|
|
|
Answer::class, |
56
|
|
|
['string' => $sourceString, 'correctedStringArray' => $correctedStringArray] |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|