-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathLanguageToolApiClient.php
More file actions
92 lines (79 loc) · 2.49 KB
/
Copy pathLanguageToolApiClient.php
File metadata and controls
92 lines (79 loc) · 2.49 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace PhpSpellcheck\Spellchecker\LanguageTool;
/**
* @TODO refactor by using PSR HTTP Client
*/
class LanguageToolApiClient
{
/**
* @var string
*/
private $baseUrl;
public function __construct(string $baseUrl)
{
$this->baseUrl = $baseUrl;
}
/**
* @param array<string> $languages
* @param array<mixed> $options
*
* @return array{matches: array<array{
* offset: int,
* context: array{text: string, offset: int, length: int},
* replacements: array<array{value: string}>,
* sentence: string,
* message: string,
* rule: string
* }>}
*/
public function spellCheck(string $text, array $languages, array $options): array
{
$options['text'] = $text;
$options['language'] = array_shift($languages);
if (!empty($languages)) {
$options['altLanguages'] = implode(',', $languages);
}
/** @var array{matches: array<array{offset: int, context: array{text: string, offset: int, length: int}, replacements: array<array{value: string}>, sentence: string, message: string, rule: string}>} */
return $this->requestAPI(
'/v2/check',
'POST',
'Content-type: application/x-www-form-urlencoded; Accept: application/json',
$options
);
}
/**
* @return array<string>
*/
public function getSupportedLanguages(): array
{
/** @var array<array{longCode: string}> $languages */
$languages = $this->requestAPI(
'/v2/languages',
'GET',
'Accept: application/json'
);
return array_values(array_unique(array_column($languages, 'longCode')));
}
/**
* @param array<mixed> $queryParams
*
* @throws \RuntimeException
*
* @return array<mixed>
*/
public function requestAPI(string $endpoint, string $method, string $header, array $queryParams = []): array
{
$httpData = [
'method' => $method,
'header' => $header,
];
if (!empty($queryParams)) {
$httpData['content'] = http_build_query($queryParams);
}
$content = \PhpSpellcheck\file_get_contents($this->baseUrl . $endpoint, false, stream_context_create(['http' => $httpData]));
/** @var array<mixed> $contentAsArray */
$contentAsArray = \PhpSpellcheck\json_decode($content, true);
return $contentAsArray;
}
}