Files
2026-09-15 10:35:56 +08:00

146 lines
5.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\LocaleResolver;
use Esun\MultiLocaleTranslation\Model\ProviderPool;
use Esun\MultiLocaleTranslation\Model\TranslationLogger;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
class AutoTranslate extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly ProviderPool $providerPool,
private readonly LocaleResolver $localeResolver,
private readonly TranslationLogger $translationLogger
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
$providerCode = (string)$this->getRequest()->getParam('provider', 'deepl');
$entityType = (string)$this->getRequest()->getParam('entity_type');
$entityId = (int)$this->getRequest()->getParam('entity_id');
$sourceStoreId = (int)$this->getRequest()->getParam('source_store_id');
$targetStoreId = (int)$this->getRequest()->getParam('target_store_id');
$fields = $this->getRequest()->getParam('fields', []);
$sourceLanguage = '';
$targetLanguage = '';
try {
if ($targetStoreId <= 0 || !is_array($fields) || $fields === []) {
throw new \InvalidArgumentException((string)__('Invalid automatic translation request.'));
}
if ($sourceStoreId > 0 && $sourceStoreId === $targetStoreId) {
throw new \InvalidArgumentException((string)__('Target store view cannot be same as source store view.'));
}
$this->assertBlogPermission($entityType);
$sourceLanguage = $this->localeResolver->getLanguageCode(
$sourceStoreId,
$providerCode,
false
);
$targetLanguage = $this->localeResolver->getLanguageCode(
$targetStoreId,
$providerCode,
true
);
$translations = $sourceLanguage !== '' && $sourceLanguage === $targetLanguage
? $this->copyFieldValues($fields)
: $this->providerPool->get($providerCode)->translate(
$fields,
$sourceLanguage,
$targetLanguage
);
try {
$this->translationLogger->logSuccess(
$providerCode,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$fields,
$translations,
$sourceLanguage === $targetLanguage ? 'copied' : 'success'
);
} catch (\Throwable) {
// Logging must never change a successful translation response.
}
return $result->setData([
'success' => true,
'provider' => $providerCode,
'source_language' => $sourceLanguage !== '' ? $sourceLanguage : 'auto',
'target_language' => $targetLanguage,
'translations' => $translations,
]);
} catch (\Throwable $exception) {
try {
$this->translationLogger->logFailure(
$providerCode,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
is_array($fields) ? $fields : [],
$exception->getMessage()
);
} catch (\Throwable) {
// Logging must never hide the original translation error.
}
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
/**
* @param array<string, mixed> $fields
* @return array<string, string>
*/
private function copyFieldValues(array $fields): array
{
$result = [];
foreach ($fields as $code => $field) {
if (!is_array($field) || !array_key_exists('value', $field)) {
continue;
}
$result[(string)$code] = (string)$field['value'];
}
return $result;
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}