class ModelMassTranslateApiYandex extends Model {
private $apiKey;
private $folderId;
private $endpoint = '
https://translation.api.cloud.yandex.net/translate/v2/translate';
public function init($config) {
if (empty($config['apiKey'])) {
die('Missing API key');
}
if (empty($config['folderId'])) {
die('Missing folder ID');
}
$this->apiKey = $config['apiKey'];
$this->folderId = $config['folderId'];
}
public function translate($text, $sourceLangCode, $targetLangCode) {
$sourceLangCode = $this->convertLangCode($sourceLangCode);
$targetLangCode = $this->convertLangCode($targetLangCode);
$params = [
'sourceLanguageCode' => $sourceLangCode,
'targetLanguageCode' => $targetLangCode,
'texts' => [$text]
];
$translateResult = $this->runTranslate($params);
if (!empty($translateResult['translations'])) {
return $translateResult['translations'][0]['text'];
}
return '';
}
public function translateBatch($sourceLangCode, $targetLangCode, $values = []) {
$sourceLangCode = $this->convertLangCode($sourceLangCode);
$targetLangCode = $this->convertLangCode($targetLangCode);
$params = [
'sourceLanguageCode' => $sourceLangCode,
'targetLanguageCode' => $targetLangCode,
'texts' => array_values($values)
];
$translateResult = $this->runTranslate($params);
$translated = [];
if (!empty($translateResult['translations'])) {
foreach ($translateResult['translations'] as $k => $translation) {
$translated[$k] = $translation['text'];
}
}
return $translated;
}
private function runTranslate($params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Api-Key ' . $this->apiKey,
'x-folder-id: ' . $this->folderId,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_errno($ch)) {
file_put_contents(
DIR_LOGS . 'mass_translate.log',
'Curl error: ' . curl_error($ch) . PHP_EOL,
FILE_APPEND | LOCK_EX
);
curl_close($ch);
return [];
}
curl_close($ch);
$res = json_decode($result, true);
if (isset($res['error'])) {
file_put_contents(
DIR_LOGS . 'mass_translate.log',
'API error: ' . $res['error']['message'] . ' (code: ' . $res['error']['code'] . ')' . PHP_EOL,
FILE_APPEND | LOCK_EX
);
}
return $res;
}
public function convertLangCode($lang) {
return strtolower(substr($lang, 0, 2));
}
public function sanitizeHtml($text) {
$replace = [
'<br>' => '<br/>',
'<hr>' => '<hr/>',
];
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
}