-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHyphenizerClient.php
More file actions
256 lines (213 loc) · 7.71 KB
/
HyphenizerClient.php
File metadata and controls
256 lines (213 loc) · 7.71 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<?php
/**
* Bit&Black Hyphenizer SDK.
*
* @author Tobias Köngeter
* @copyright Copyright © Bit&Black
* @link https://www.bitandblack.com
* @license MIT
*/
namespace BitAndBlack\Hyphenizer\Sdk;
use BitAndBlack\Hyphenizer\Sdk\Api\WordPayload;
use BitAndBlack\Hyphenizer\Sdk\Api\WordResponse;
use BitAndBlack\Hyphenizer\Sdk\Api\WordsPayload;
use BitAndBlack\Hyphenizer\Sdk\Api\WordsResponse;
use BitAndBlack\Hyphenizer\Sdk\Exception\RequestException;
use CuyZ\Valinor\Mapper\Source\Source;
use CuyZ\Valinor\MapperBuilder;
use Fig\Http\Message\StatusCodeInterface;
use Http\Client\Common\HttpMethodsClient;
use Http\Client\Common\HttpMethodsClientInterface;
use Http\Client\Exception as HttpClientException;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Throwable;
class HyphenizerClient implements HyphenizerClientInterface, LoggerAwareInterface
{
private readonly HttpMethodsClientInterface $httpMethodsClient;
/**
* @var array<int, string>
*/
private array $wordsWithTypos = [];
private string $hyphenizerUrl = 'https://api.hyphenizer.com';
private LoggerInterface $logger;
/**
* @param non-empty-string $token
* @param non-empty-string|null $hyphenizerUrl
*/
public function __construct(
private readonly string $token,
string|null $hyphenizerUrl = null
) {
$this->logger = new NullLogger();
$this->httpMethodsClient = new HttpMethodsClient(
Psr18ClientDiscovery::find(),
Psr17FactoryDiscovery::findRequestFactory(),
Psr17FactoryDiscovery::findStreamFactory(),
);
$this->hyphenizerUrl = $hyphenizerUrl ?? $this->hyphenizerUrl;
}
/**
* @param non-empty-string $word
* @throws RequestException
*/
public function getSingleWordRequest(string $word): WordResponse
{
$headers = [
'Authorization' => 'Bearer ' . $this->token,
];
try {
$response = $this->httpMethodsClient->get($this->hyphenizerUrl . '/v2/words/' . $word, $headers);
} catch (HttpClientException $httpClientException) {
throw new RequestException('Failed to request Hyphenizer API.', $httpClientException);
}
$contents = $response->getBody()->getContents();
$mapper = (new MapperBuilder())->mapper();
try {
$responseDecoded = $mapper->map(
WordResponse::class,
Source::json($contents)
);
} catch (Throwable $throwable) {
throw new RequestException('Failed to decode response.', $throwable);
}
return $responseDecoded;
}
/**
* @param array<int, non-empty-string> $words
* @throws RequestException
*/
public function getMultipleWordsRequest(array $words): WordsResponse
{
$headers = [
'Authorization' => 'Bearer ' . $this->token,
];
$body = http_build_query([
'words' => $words,
]);
try {
$response = $this->httpMethodsClient->post($this->hyphenizerUrl . '/v2/multiple-words', $headers, $body);
} catch (HttpClientException $httpClientException) {
throw new RequestException('Failed to request Hyphenizer API.', $httpClientException);
}
$contents = $response->getBody()->getContents();
$mapper = (new MapperBuilder())->mapper();
try {
$wordsResponse = $mapper->map(
WordsResponse::class,
Source::json($contents)
);
} catch (Throwable $throwable) {
throw new RequestException('Failed to decode response.', $throwable);
}
return $wordsResponse;
}
/**
* @param non-empty-string $word
* @param int<0, 100> $minScoreRequired
*/
public function getSingleWordHyphenated(string $word, int $minScoreRequired = 50): string
{
try {
$singleWordRequest = $this->getSingleWordRequest($word);
} catch (Exception $exception) {
$this->logger->error('Failed hyphenation words with exception: {exception}.', [
'exception' => $exception->getMessage(),
]);
return $word;
}
if (StatusCodeInterface::STATUS_OK !== $singleWordRequest->getStatusCode()) {
$this->logger->error('Failed hyphenation words because of status code: {code}.', [
'code' => $singleWordRequest->getStatusCode(),
]);
return $word;
}
$payload = $singleWordRequest->getPayload();
if (!$payload instanceof WordPayload) {
$this->logger->error('Failed hyphenation words (got empty payload).');
return $word;
}
$wordHyphenated = $payload->getWord()[0] ?? null;
if (null === $wordHyphenated) {
$this->logger->error('Failed hyphenation words (word is missing from response).');
return $word;
}
if (true === $wordHyphenated->hasTypo()) {
$this->wordsWithTypos[] = $word;
}
if ($wordHyphenated->getScore() < $minScoreRequired) {
return $word;
}
return $wordHyphenated->getHyphenation();
}
/**
* @param array<int, non-empty-string> $words
* @param int<0, 100> $minScoreRequired
* @return array<non-empty-string, non-empty-string>
*/
public function getWordsHyphenated(array $words, int $minScoreRequired = 50): array
{
try {
$wordsResponse = $this->getMultipleWordsRequest($words);
} catch (Exception $exception) {
$this->logger->error('Failed hyphenation words with exception: {exception}.', [
'exception' => $exception->getMessage(),
]);
return array_combine(
$words,
$words,
);
}
return $this->getWordsHyphenatedFromWordsResponse(
$wordsResponse,
$minScoreRequired
);
}
/**
* @param int<0, 100> $minScoreRequired
* @return array<non-empty-string, non-empty-string>
*/
public function getWordsHyphenatedFromWordsResponse(WordsResponse $wordsResponse, int $minScoreRequired = 50): array
{
$wordsHyphenated = [];
if (StatusCodeInterface::STATUS_OK !== $wordsResponse->getStatusCode()) {
$this->logger->error('Failed hyphenation words because of status code: {code}.', [
'code' => $wordsResponse->getStatusCode(),
]);
return $wordsHyphenated;
}
$payload = $wordsResponse->getPayload();
if (!$payload instanceof WordsPayload) {
$this->logger->error('Failed hyphenation words (got empty payload).');
return $wordsHyphenated;
}
foreach ($payload->getWords() as $word => $hyphenationPossibilities) {
$hyphenationPossibility = $hyphenationPossibilities[0] ?? null;
if (null === $hyphenationPossibility) {
continue;
}
if (true === $hyphenationPossibility->hasTypo()) {
$this->wordsWithTypos[] = $word;
}
if ($hyphenationPossibility->getScore() < $minScoreRequired) {
continue;
}
$wordsHyphenated[$word] = $hyphenationPossibility->getHyphenation();
}
return $wordsHyphenated;
}
/**
* @return array<int, string>
*/
public function getWordsWithTypos(): array
{
return $this->wordsWithTypos;
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
}