1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace PhpSpellcheck\Spellchecker; |
5
|
|
|
|
6
|
|
|
use Nyholm\Psr7\Factory\Psr17Factory; |
7
|
|
|
use Nyholm\Psr7\Stream; |
8
|
|
|
use PhpSpellcheck\Exception\RuntimeException; |
9
|
|
|
use PhpSpellcheck\Misspelling; |
10
|
|
|
use PhpSpellcheck\Utils\LineAndOffset; |
11
|
|
|
use Psr\Http\Client\ClientInterface; |
12
|
|
|
|
13
|
|
|
class JamSpell implements SpellcheckerInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var ClientInterface |
17
|
|
|
*/ |
18
|
|
|
private $httpClient; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
private $endpoint; |
24
|
|
|
|
25
|
|
|
public function __construct(ClientInterface $httpClient, string $endpoint) |
26
|
|
|
{ |
27
|
|
|
$this->httpClient = $httpClient; |
28
|
|
|
$this->endpoint = $endpoint; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function check(string $text, array $languages, array $context): iterable |
32
|
|
|
{ |
33
|
|
|
$request = (new Psr17Factory()) |
34
|
|
|
->createRequest('POST', $this->endpoint) |
35
|
|
|
->withBody(Stream::create($text)); |
36
|
|
|
|
37
|
|
|
$spellcheckResponse = \Safe\json_decode($this->httpClient->sendRequest($request)->getBody()->getContents(), true); |
38
|
|
|
|
39
|
|
|
// @TODO use json api validation schema |
40
|
|
|
if (!isset($spellcheckResponse['results'])) { |
41
|
|
|
throw new RuntimeException('Jamspell spellcheck HTTP response must include a "results" key. Response given: "'.$spellcheckResponse.'"'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
foreach ($spellcheckResponse['results'] as $result) { |
45
|
|
|
[$line, $offset] = LineAndOffset::findFromFirstCharacterOffset($text, $result['pos_from']); |
46
|
|
|
|
47
|
|
|
yield new Misspelling( |
48
|
|
|
mb_substr($text, $result['pos_from'], $result['len']), |
49
|
|
|
$offset, |
50
|
|
|
$line, |
51
|
|
|
$result['candidates'], |
52
|
|
|
$context |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function getSupportedLanguages(): iterable |
58
|
|
|
{ |
59
|
|
|
throw new RuntimeException('Jamspell doesn\'t provide a way to retrieve the language its actually supporting through its HTTP API. Rely on the language models it has been setup with.'); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|