Passed
Push — master ( 8e80a1...4c4d1d )
by Philippe
02:55
created

JamSpell::getSupportedLanguages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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