init
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Api;
|
||||
|
||||
interface TranslatableEntityInterface
|
||||
{
|
||||
public function getType(): string;
|
||||
|
||||
public function getLabel(): string;
|
||||
|
||||
public function getTitle(int $entityId): string;
|
||||
|
||||
public function getEditUrlPath(): string;
|
||||
|
||||
public function getEditIdParam(): string;
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array;
|
||||
|
||||
/**
|
||||
* @param int[] $storeIds
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Api;
|
||||
|
||||
interface TranslatorInterface
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $texts
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function translate(array $texts, string $sourceLocale, string $targetLocale): array;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Block\Adminhtml\Cms\Block\Edit\Button;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Cms\Block\Adminhtml\Block\Edit\GenericButton;
|
||||
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
|
||||
|
||||
class Translate extends GenericButton implements ButtonProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
\Magento\Backend\Block\Widget\Context $context,
|
||||
\Magento\Cms\Api\BlockRepositoryInterface $blockRepository,
|
||||
private readonly Config $config
|
||||
) {
|
||||
parent::__construct($context, $blockRepository);
|
||||
}
|
||||
|
||||
public function getButtonData(): array
|
||||
{
|
||||
$blockId = (int)$this->getBlockId();
|
||||
if (!$this->config->isEnabled() || $blockId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => __('Translate'),
|
||||
'class' => 'action-secondary',
|
||||
'on_click' => sprintf(
|
||||
"location.href = '%s';",
|
||||
$this->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'cms_block', 'entity_id' => $blockId]
|
||||
)
|
||||
),
|
||||
'sort_order' => 85,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Block\Adminhtml\Cms\Page\Edit\Button;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Cms\Block\Adminhtml\Page\Edit\GenericButton;
|
||||
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
|
||||
|
||||
class Translate extends GenericButton implements ButtonProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
\Magento\Backend\Block\Widget\Context $context,
|
||||
\Magento\Cms\Api\PageRepositoryInterface $pageRepository,
|
||||
private readonly Config $config
|
||||
) {
|
||||
parent::__construct($context, $pageRepository);
|
||||
}
|
||||
|
||||
public function getButtonData(): array
|
||||
{
|
||||
$pageId = (int)$this->getPageId();
|
||||
if (!$this->config->isEnabled() || $pageId <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => __('Translate'),
|
||||
'class' => 'action-secondary',
|
||||
'on_click' => sprintf(
|
||||
"location.href = '%s';",
|
||||
$this->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'cms_page', 'entity_id' => $pageId]
|
||||
)
|
||||
),
|
||||
'sort_order' => 85,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Block\Adminhtml\Product\Edit\Button;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic;
|
||||
|
||||
class Translate extends Generic
|
||||
{
|
||||
public function __construct(
|
||||
\Magento\Framework\View\Element\UiComponent\Context $context,
|
||||
\Magento\Framework\Registry $registry,
|
||||
private readonly Config $config
|
||||
) {
|
||||
parent::__construct($context, $registry);
|
||||
}
|
||||
|
||||
public function getButtonData(): array
|
||||
{
|
||||
$product = $this->getProduct();
|
||||
if (!$this->config->isEnabled() || !$product || !$product->getId()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'label' => __('Translate'),
|
||||
'class' => 'action-secondary',
|
||||
'on_click' => sprintf(
|
||||
"location.href = '%s';",
|
||||
$this->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'product', 'entity_id' => (int)$product->getId()]
|
||||
)
|
||||
),
|
||||
'sort_order' => 85,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Block\Adminhtml\Translation;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Backend\Block\Template\Context;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
|
||||
class Workspace extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly Config $config,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly Json $json,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->config->isEnabled();
|
||||
}
|
||||
|
||||
public function getEntityType(): string
|
||||
{
|
||||
return (string)$this->getRequest()->getParam('entity_type', 'product');
|
||||
}
|
||||
|
||||
public function getEntityId(): int
|
||||
{
|
||||
return (int)$this->getRequest()->getParam('entity_id', $this->getRequest()->getParam('product_id'));
|
||||
}
|
||||
|
||||
public function getEntityLabel(): string
|
||||
{
|
||||
try {
|
||||
return $this->entityPool->get($this->getEntityType())->getLabel();
|
||||
} catch (\Throwable) {
|
||||
return (string)__('Content');
|
||||
}
|
||||
}
|
||||
|
||||
public function getEntityTitle(): string
|
||||
{
|
||||
$entityId = $this->getEntityId();
|
||||
if ($entityId <= 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->entityPool->get($this->getEntityType())->getTitle($entityId);
|
||||
} catch (\Throwable) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
public function getBackUrl(): string
|
||||
{
|
||||
$entityId = $this->getEntityId();
|
||||
if ($entityId <= 0) {
|
||||
return '#';
|
||||
}
|
||||
|
||||
try {
|
||||
$entity = $this->entityPool->get($this->getEntityType());
|
||||
|
||||
return $this->getUrl($entity->getEditUrlPath(), [$entity->getEditIdParam() => $entityId]);
|
||||
} catch (\Throwable) {
|
||||
return '#';
|
||||
}
|
||||
}
|
||||
|
||||
public function getConfigJson(): string
|
||||
{
|
||||
return $this->json->serialize([
|
||||
'entityType' => $this->getEntityType(),
|
||||
'entityId' => $this->getEntityId(),
|
||||
'entityLabel' => $this->getEntityLabel(),
|
||||
'entityTitle' => $this->getEntityTitle(),
|
||||
'sourceLocale' => $this->config->getSourceLocale(),
|
||||
'formKey' => $this->getFormKey(),
|
||||
'languages' => array_map(
|
||||
static fn ($group): array => $group->toArray(),
|
||||
$this->languageGroupProvider->getGroups()
|
||||
),
|
||||
'urls' => [
|
||||
'fields' => $this->getUrl('esun_translation/translate/fields'),
|
||||
'translate' => $this->getUrl('esun_translation/translate/run'),
|
||||
'apply' => $this->getUrl('esun_translation/translate/apply'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Controller\Adminhtml\Translate;
|
||||
|
||||
use Esun\Translation\Model\Translation\ApplyService;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
|
||||
class Apply extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Magento_Backend::admin';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly ApplyService $applyService
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
|
||||
try {
|
||||
$type = (string)$this->getRequest()->getParam('entity_type', 'product');
|
||||
$entityId = (int)$this->getRequest()->getParam('entity_id', $this->getRequest()->getParam('product_id'));
|
||||
$language = (string)$this->getRequest()->getParam('language');
|
||||
$fields = $this->getRequest()->getParam('fields', []);
|
||||
if ($entityId <= 0) {
|
||||
throw new \InvalidArgumentException('A valid content ID is required.');
|
||||
}
|
||||
if (!is_array($fields)) {
|
||||
throw new \InvalidArgumentException('Fields payload is invalid.');
|
||||
}
|
||||
|
||||
$response = $this->applyService->apply($type, $entityId, $language, $fields);
|
||||
|
||||
return $result->setData(array_merge(['success' => true], $response));
|
||||
} catch (\Throwable $exception) {
|
||||
return $result->setData([
|
||||
'success' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function _isAllowed(): bool
|
||||
{
|
||||
return $this->_authorization->isAllowed($this->getApplyResource());
|
||||
}
|
||||
|
||||
private function getApplyResource(): string
|
||||
{
|
||||
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
|
||||
'cms_page' => 'Esun_Translation::apply_cms_page_translation',
|
||||
'cms_block' => 'Esun_Translation::apply_cms_block_translation',
|
||||
default => 'Esun_Translation::apply_product_translation',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Controller\Adminhtml\Translate;
|
||||
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
|
||||
class Fields extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Magento_Backend::admin';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
|
||||
try {
|
||||
$type = (string)$this->getRequest()->getParam('entity_type', 'product');
|
||||
$entityId = (int)$this->getRequest()->getParam('entity_id', $this->getRequest()->getParam('product_id'));
|
||||
$language = (string)$this->getRequest()->getParam('language');
|
||||
if ($entityId <= 0) {
|
||||
throw new \InvalidArgumentException('A valid content ID is required.');
|
||||
}
|
||||
|
||||
$group = $this->languageGroupProvider->getGroup($language);
|
||||
if (!$group) {
|
||||
throw new \InvalidArgumentException('Language group was not found.');
|
||||
}
|
||||
|
||||
return $result->setData([
|
||||
'success' => true,
|
||||
'fields' => $this->entityPool->get($type)->getFields($entityId, $group->getStoreIds()),
|
||||
]);
|
||||
} catch (\Throwable $exception) {
|
||||
return $result->setData([
|
||||
'success' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function _isAllowed(): bool
|
||||
{
|
||||
return $this->_authorization->isAllowed($this->getTranslateResource());
|
||||
}
|
||||
|
||||
private function getTranslateResource(): string
|
||||
{
|
||||
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
|
||||
'cms_page' => 'Esun_Translation::translate_cms_page',
|
||||
'cms_block' => 'Esun_Translation::translate_cms_block',
|
||||
default => 'Esun_Translation::translate_product',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Controller\Adminhtml\Translate;
|
||||
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\Controller\ResultInterface;
|
||||
use Magento\Framework\View\Result\PageFactory;
|
||||
|
||||
class Index extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Magento_Backend::admin';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly PageFactory $pageFactory
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): ResultInterface
|
||||
{
|
||||
$page = $this->pageFactory->create();
|
||||
$page->getConfig()->getTitle()->prepend(__('Esun Translation'));
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
protected function _isAllowed(): bool
|
||||
{
|
||||
return $this->_authorization->isAllowed($this->getTranslateResource());
|
||||
}
|
||||
|
||||
private function getTranslateResource(): string
|
||||
{
|
||||
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
|
||||
'cms_page' => 'Esun_Translation::translate_cms_page',
|
||||
'cms_block' => 'Esun_Translation::translate_cms_block',
|
||||
default => 'Esun_Translation::translate_product',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Controller\Adminhtml\Translate;
|
||||
|
||||
use Esun\Translation\Model\Translation\TranslationService;
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
|
||||
class Run extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Magento_Backend::admin';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly TranslationService $translationService
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
|
||||
try {
|
||||
$type = (string)$this->getRequest()->getParam('entity_type', 'product');
|
||||
$entityId = (int)$this->getRequest()->getParam('entity_id', $this->getRequest()->getParam('product_id'));
|
||||
$language = (string)$this->getRequest()->getParam('language');
|
||||
$sourceOverrides = $this->getRequest()->getParam('source_overrides', []);
|
||||
if ($entityId <= 0) {
|
||||
throw new \InvalidArgumentException('A valid content ID is required.');
|
||||
}
|
||||
if (!is_array($sourceOverrides)) {
|
||||
$sourceOverrides = [];
|
||||
}
|
||||
|
||||
return $result->setData([
|
||||
'success' => true,
|
||||
'translations' => $this->translationService->translate($type, $entityId, $language, $sourceOverrides),
|
||||
]);
|
||||
} catch (\Throwable $exception) {
|
||||
return $result->setData([
|
||||
'success' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function _isAllowed(): bool
|
||||
{
|
||||
return $this->_authorization->isAllowed($this->getTranslateResource());
|
||||
}
|
||||
|
||||
private function getTranslateResource(): string
|
||||
{
|
||||
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
|
||||
'cms_page' => 'Esun_Translation::translate_cms_page',
|
||||
'cms_block' => 'Esun_Translation::translate_cms_block',
|
||||
default => 'Esun_Translation::translate_product',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Ai;
|
||||
|
||||
use Esun\Translation\Api\TranslatorInterface;
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Framework\HTTP\Client\Curl;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class OpenAiCompatibleTranslator implements TranslatorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly Curl $curl,
|
||||
private readonly Json $json,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function translate(array $texts, string $sourceLocale, string $targetLocale): array
|
||||
{
|
||||
$texts = array_filter($texts, static fn (string $value): bool => trim($value) !== '');
|
||||
if ($texts === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$apiKey = $this->config->getApiKey();
|
||||
$baseUrl = $this->config->getApiBaseUrl();
|
||||
$model = $this->config->getModel();
|
||||
|
||||
if ($apiKey === '' || $baseUrl === '' || $model === '') {
|
||||
throw new \RuntimeException('AI provider is not configured.');
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'model' => $model,
|
||||
'temperature' => $this->config->getTemperature(),
|
||||
'response_format' => $this->buildResponseFormat(array_keys($texts)),
|
||||
'messages' => [
|
||||
[
|
||||
'role' => 'system',
|
||||
'content' => 'You translate Magento ecommerce content. Return only JSON that conforms to the supplied schema. The translations object must contain every input key exactly once. Do not rename keys. Preserve placeholders like __ESUN_TRANSLATION_PRESERVE_0__ exactly.',
|
||||
],
|
||||
[
|
||||
'role' => 'user',
|
||||
'content' => $this->json->serialize([
|
||||
'source_locale' => $sourceLocale,
|
||||
'target_locale' => $targetLocale,
|
||||
'required_keys' => array_keys($texts),
|
||||
'texts' => $texts,
|
||||
]),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$this->curl->setTimeout($this->config->getTimeout());
|
||||
$this->curl->addHeader('Content-Type', 'application/json');
|
||||
$this->curl->addHeader('Authorization', 'Bearer ' . $apiKey);
|
||||
$this->curl->post($baseUrl . '/chat/completions', $this->json->serialize($payload));
|
||||
$status = $this->curl->getStatus();
|
||||
$body = $this->curl->getBody();
|
||||
|
||||
if ($status < 200 || $status >= 300) {
|
||||
if ($this->shouldRetryWithoutJsonSchema($status, $body)) {
|
||||
$payload['response_format'] = ['type' => 'json_object'];
|
||||
$payload['messages'][0]['content'] = 'You translate Magento ecommerce content. Return only JSON in this exact shape: {"translations":{"field_key":"translated text"}}. The translations object must contain every input key exactly once. Do not rename keys. Do not add commentary. Preserve placeholders like __ESUN_TRANSLATION_PRESERVE_0__ exactly.';
|
||||
$this->curl->post($baseUrl . '/chat/completions', $this->json->serialize($payload));
|
||||
$status = $this->curl->getStatus();
|
||||
$body = $this->curl->getBody();
|
||||
}
|
||||
|
||||
if ($status < 200 || $status >= 300) {
|
||||
throw new \RuntimeException(sprintf('AI provider returned HTTP %d.', $status));
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->json->unserialize($body);
|
||||
$content = $response['choices'][0]['message']['content'] ?? null;
|
||||
if (!is_string($content) || trim($content) === '') {
|
||||
throw new \RuntimeException('AI provider response did not contain translated content.');
|
||||
}
|
||||
|
||||
$translated = $this->json->unserialize($content);
|
||||
if (!is_array($translated)) {
|
||||
throw new \RuntimeException('AI provider response content is not a JSON object.');
|
||||
}
|
||||
|
||||
return $this->normalizeTranslations($texts, $translated);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('Esun Translation AI request failed.', ['exception' => $exception]);
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $sourceTexts
|
||||
* @param array<mixed> $translated
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function normalizeTranslations(array $sourceTexts, array $translated): array
|
||||
{
|
||||
if (!isset($translated['translations']) || !is_array($translated['translations'])) {
|
||||
throw new \RuntimeException('AI response must be a JSON object with a "translations" object.');
|
||||
}
|
||||
|
||||
$translations = $translated['translations'];
|
||||
$result = [];
|
||||
foreach ($sourceTexts as $key => $sourceText) {
|
||||
if (!array_key_exists($key, $translations) || !is_scalar($translations[$key])) {
|
||||
throw new \RuntimeException(sprintf('AI response is missing translation key "%s".', $key));
|
||||
}
|
||||
$result[$key] = (string)$translations[$key];
|
||||
}
|
||||
|
||||
$unexpectedKeys = array_diff(array_keys($translations), array_keys($sourceTexts));
|
||||
if ($unexpectedKeys !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'AI response contains unexpected translation key "%s".',
|
||||
(string)reset($unexpectedKeys)
|
||||
));
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $keys
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function buildResponseFormat(array $keys): array
|
||||
{
|
||||
$properties = [];
|
||||
foreach ($keys as $key) {
|
||||
$properties[$key] = [
|
||||
'type' => 'string',
|
||||
'description' => 'Translated text for input key ' . $key,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'json_schema',
|
||||
'json_schema' => [
|
||||
'name' => 'product_translation_response',
|
||||
'strict' => true,
|
||||
'schema' => [
|
||||
'type' => 'object',
|
||||
'additionalProperties' => false,
|
||||
'required' => ['translations'],
|
||||
'properties' => [
|
||||
'translations' => [
|
||||
'type' => 'object',
|
||||
'additionalProperties' => false,
|
||||
'required' => $keys,
|
||||
'properties' => $properties,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function shouldRetryWithoutJsonSchema(int $status, string $body): bool
|
||||
{
|
||||
if ($status !== 400 && $status !== 422) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lowerBody = strtolower($body);
|
||||
|
||||
return str_contains($lowerBody, 'json_schema')
|
||||
|| str_contains($lowerBody, 'response_format')
|
||||
|| str_contains($lowerBody, 'unsupported');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Ai;
|
||||
|
||||
class ProtectedTextProcessor
|
||||
{
|
||||
/**
|
||||
* @return array{0: string, 1: array<string, string>}
|
||||
*/
|
||||
public function protect(string $text): array
|
||||
{
|
||||
$placeholders = [];
|
||||
$index = 0;
|
||||
$protected = preg_replace_callback(
|
||||
'/\{\{.*?\}\}|https?:\/\/[^\s<>"\']+|%[0-9]*\$?[a-zA-Z]|\{[A-Za-z0-9_.-]+\}/',
|
||||
function (array $matches) use (&$placeholders, &$index): string {
|
||||
$token = '__ESUN_TRANSLATION_PRESERVE_' . $index++ . '__';
|
||||
$placeholders[$token] = $matches[0];
|
||||
|
||||
return $token;
|
||||
},
|
||||
$text
|
||||
);
|
||||
|
||||
return [$protected ?? $text, $placeholders];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $placeholders
|
||||
*/
|
||||
public function restore(string $text, array $placeholders): string
|
||||
{
|
||||
foreach ($placeholders as $token => $original) {
|
||||
if (!str_contains($text, $token)) {
|
||||
throw new \RuntimeException(sprintf('Protected token "%s" was not preserved by AI response.', $token));
|
||||
}
|
||||
}
|
||||
|
||||
return strtr($text, $placeholders);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Encryption\EncryptorInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
private const XML_PATH_ENABLED = 'esun_translation/general/enabled';
|
||||
private const XML_PATH_SOURCE_LOCALE = 'esun_translation/general/source_locale';
|
||||
private const XML_PATH_SOURCE_STORE_ID = 'esun_translation/general/source_store_id';
|
||||
private const XML_PATH_ATTRIBUTES = 'esun_translation/general/translatable_attributes';
|
||||
private const XML_PATH_LANGUAGE_GROUPS = 'esun_translation/general/language_groups';
|
||||
private const XML_PATH_API_BASE_URL = 'esun_translation/ai/api_base_url';
|
||||
private const XML_PATH_API_KEY = 'esun_translation/ai/api_key';
|
||||
private const XML_PATH_MODEL = 'esun_translation/ai/model';
|
||||
private const XML_PATH_TEMPERATURE = 'esun_translation/ai/temperature';
|
||||
private const XML_PATH_TIMEOUT = 'esun_translation/ai/timeout';
|
||||
|
||||
public function __construct(
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly EncryptorInterface $encryptor
|
||||
) {
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE);
|
||||
}
|
||||
|
||||
public function getSourceLocale(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_SOURCE_LOCALE)) ?: 'en';
|
||||
}
|
||||
|
||||
public function getSourceStoreId(): int
|
||||
{
|
||||
return max(0, (int)$this->scopeConfig->getValue(self::XML_PATH_SOURCE_STORE_ID));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getTranslatableAttributeCodes(): array
|
||||
{
|
||||
$raw = (string)$this->scopeConfig->getValue(self::XML_PATH_ATTRIBUTES);
|
||||
$codes = preg_split('/[\s,]+/', $raw) ?: [];
|
||||
|
||||
return array_values(array_unique(array_filter(array_map('trim', $codes))));
|
||||
}
|
||||
|
||||
public function getLanguageGroupsConfig(): string
|
||||
{
|
||||
return (string)$this->scopeConfig->getValue(self::XML_PATH_LANGUAGE_GROUPS);
|
||||
}
|
||||
|
||||
public function getApiBaseUrl(): string
|
||||
{
|
||||
return rtrim((string)$this->scopeConfig->getValue(self::XML_PATH_API_BASE_URL), '/');
|
||||
}
|
||||
|
||||
public function getApiKey(): string
|
||||
{
|
||||
$value = (string)$this->scopeConfig->getValue(self::XML_PATH_API_KEY);
|
||||
|
||||
return $value !== '' ? $this->encryptor->decrypt($value) : '';
|
||||
}
|
||||
|
||||
public function getModel(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_MODEL));
|
||||
}
|
||||
|
||||
public function getTemperature(): float
|
||||
{
|
||||
return (float)$this->scopeConfig->getValue(self::XML_PATH_TEMPERATURE);
|
||||
}
|
||||
|
||||
public function getTimeout(): int
|
||||
{
|
||||
return max(1, (int)$this->scopeConfig->getValue(self::XML_PATH_TIMEOUT));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class Provider implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'openai_compatible', 'label' => __('OpenAI Compatible')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Cms\Api\BlockRepositoryInterface;
|
||||
use Magento\Cms\Model\Block;
|
||||
use Magento\Cms\Model\BlockFactory;
|
||||
use Magento\Cms\Model\ResourceModel\Block\CollectionFactory;
|
||||
|
||||
class CmsBlockEntity implements TranslatableEntityInterface
|
||||
{
|
||||
private const FIELDS = [
|
||||
'title' => ['label' => 'Block Title', 'is_html' => false],
|
||||
'content' => ['label' => 'Content', 'is_html' => true],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly BlockRepositoryInterface $blockRepository,
|
||||
private readonly BlockFactory $blockFactory,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'cms_block';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'CMS Block';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->getBlock($entityId)->getTitle();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'cms/block/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'block_id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
$source = $this->getBlock($entityId);
|
||||
$target = $this->findTargetBlock($source, $targetStoreIds);
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $code => $metadata) {
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => $metadata['label'],
|
||||
'source_value' => (string)($source->getData($code) ?? ''),
|
||||
'target_value' => $target ? (string)($target->getData($code) ?? '') : '',
|
||||
'is_html' => (bool)$metadata['is_html'],
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$source = $this->getBlock($entityId);
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable CMS block fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
$created = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$block = $this->findByIdentifierAndStore((string)$source->getIdentifier(), $storeId);
|
||||
if ($block) {
|
||||
$this->applyFields($block, $fields);
|
||||
$block->setStores([$storeId]);
|
||||
$this->blockRepository->save($block);
|
||||
$updated++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array(0, array_map('intval', (array)$source->getStores()), true)) {
|
||||
throw new \RuntimeException(
|
||||
'This CMS block is assigned to All Store Views. Create store-specific blocks first or remove All Store Views before creating localized copies.'
|
||||
);
|
||||
}
|
||||
|
||||
$copy = $this->cloneForStore($source, $storeId);
|
||||
$this->applyFields($copy, $fields);
|
||||
$this->blockRepository->save($copy);
|
||||
$created++;
|
||||
}
|
||||
|
||||
if ($updated + $created === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'created' => $created,
|
||||
'message' => __('CMS block translations applied. Updated: %1, Created: %2.', $updated, $created)->render(),
|
||||
];
|
||||
}
|
||||
|
||||
private function getBlock(int $blockId): Block
|
||||
{
|
||||
$block = $this->blockRepository->getById($blockId);
|
||||
if (!$block instanceof Block) {
|
||||
throw new \RuntimeException('CMS block model type is not supported.');
|
||||
}
|
||||
|
||||
return $block;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
*/
|
||||
private function findTargetBlock(Block $source, array $targetStoreIds): ?Block
|
||||
{
|
||||
foreach ($targetStoreIds as $storeId) {
|
||||
$block = $this->findByIdentifierAndStore((string)$source->getIdentifier(), (int)$storeId);
|
||||
if ($block && (int)$block->getId() !== (int)$source->getId()) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function findByIdentifierAndStore(string $identifier, int $storeId): ?Block
|
||||
{
|
||||
if ($storeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$collection = $this->collectionFactory->create();
|
||||
$collection->addFieldToFilter('identifier', $identifier);
|
||||
$collection->addStoreFilter($storeId, false);
|
||||
$collection->setPageSize(1);
|
||||
$block = $collection->getFirstItem();
|
||||
|
||||
return $block && $block->getId() ? $block : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!isset(self::FIELDS[$code])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ((bool)self::FIELDS[$code]['is_html']) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
private function applyFields(Block $block, array $fields): void
|
||||
{
|
||||
foreach ($fields as $code => $value) {
|
||||
$block->setData($code, $value);
|
||||
}
|
||||
}
|
||||
|
||||
private function cloneForStore(Block $source, int $storeId): Block
|
||||
{
|
||||
$data = $source->getData();
|
||||
unset($data['block_id'], $data['store_id']);
|
||||
|
||||
$copy = $this->blockFactory->create();
|
||||
$copy->setData($data);
|
||||
$copy->setStores([$storeId]);
|
||||
$copy->setData('store_id', [$storeId]);
|
||||
|
||||
return $copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Cms\Api\PageRepositoryInterface;
|
||||
use Magento\Cms\Model\Page;
|
||||
use Magento\Cms\Model\PageFactory;
|
||||
use Magento\Cms\Model\ResourceModel\Page\CollectionFactory;
|
||||
|
||||
class CmsPageEntity implements TranslatableEntityInterface
|
||||
{
|
||||
private const FIELDS = [
|
||||
'title' => ['label' => 'Page Title', 'is_html' => false],
|
||||
'content_heading' => ['label' => 'Content Heading', 'is_html' => false],
|
||||
'content' => ['label' => 'Content', 'is_html' => true],
|
||||
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
|
||||
'meta_keywords' => ['label' => 'Meta Keywords', 'is_html' => false],
|
||||
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly PageRepositoryInterface $pageRepository,
|
||||
private readonly PageFactory $pageFactory,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'cms_page';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'CMS Page';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->getPage($entityId)->getTitle();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'cms/page/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'page_id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
$source = $this->getPage($entityId);
|
||||
$target = $this->findTargetPage($source, $targetStoreIds);
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $code => $metadata) {
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => $metadata['label'],
|
||||
'source_value' => (string)($source->getData($code) ?? ''),
|
||||
'target_value' => $target ? (string)($target->getData($code) ?? '') : '',
|
||||
'is_html' => (bool)$metadata['is_html'],
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$source = $this->getPage($entityId);
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable CMS page fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
$created = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$page = $this->findByIdentifierAndStore((string)$source->getIdentifier(), $storeId);
|
||||
if ($page) {
|
||||
$this->applyFields($page, $fields);
|
||||
$page->setStores([$storeId]);
|
||||
$this->pageRepository->save($page);
|
||||
$updated++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array(0, array_map('intval', (array)$source->getStores()), true)) {
|
||||
throw new \RuntimeException(
|
||||
'This CMS page is assigned to All Store Views. Create store-specific pages first or remove All Store Views before creating localized copies.'
|
||||
);
|
||||
}
|
||||
|
||||
$copy = $this->cloneForStore($source, $storeId);
|
||||
$this->applyFields($copy, $fields);
|
||||
$this->pageRepository->save($copy);
|
||||
$created++;
|
||||
}
|
||||
|
||||
if ($updated + $created === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'created' => $created,
|
||||
'message' => __('CMS page translations applied. Updated: %1, Created: %2.', $updated, $created)->render(),
|
||||
];
|
||||
}
|
||||
|
||||
private function getPage(int $pageId): Page
|
||||
{
|
||||
$page = $this->pageRepository->getById($pageId);
|
||||
if (!$page instanceof Page) {
|
||||
throw new \RuntimeException('CMS page model type is not supported.');
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
*/
|
||||
private function findTargetPage(Page $source, array $targetStoreIds): ?Page
|
||||
{
|
||||
foreach ($targetStoreIds as $storeId) {
|
||||
$page = $this->findByIdentifierAndStore((string)$source->getIdentifier(), (int)$storeId);
|
||||
if ($page && (int)$page->getId() !== (int)$source->getId()) {
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function findByIdentifierAndStore(string $identifier, int $storeId): ?Page
|
||||
{
|
||||
if ($storeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$collection = $this->collectionFactory->create();
|
||||
$collection->addFieldToFilter('identifier', $identifier);
|
||||
$collection->addStoreFilter($storeId, false);
|
||||
$collection->setPageSize(1);
|
||||
$page = $collection->getFirstItem();
|
||||
|
||||
return $page && $page->getId() ? $page : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!isset(self::FIELDS[$code])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ((bool)self::FIELDS[$code]['is_html']) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
private function applyFields(Page $page, array $fields): void
|
||||
{
|
||||
foreach ($fields as $code => $value) {
|
||||
$page->setData($code, $value);
|
||||
}
|
||||
}
|
||||
|
||||
private function cloneForStore(Page $source, int $storeId): Page
|
||||
{
|
||||
$data = $source->getData();
|
||||
unset($data['page_id'], $data['store_id']);
|
||||
|
||||
$copy = $this->pageFactory->create();
|
||||
$copy->setData($data);
|
||||
$copy->setStores([$storeId]);
|
||||
$copy->setData('store_id', [$storeId]);
|
||||
|
||||
return $copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
|
||||
class EntityPool
|
||||
{
|
||||
/**
|
||||
* @param array<string, TranslatableEntityInterface> $entities
|
||||
*/
|
||||
public function __construct(private readonly array $entities = [])
|
||||
{
|
||||
}
|
||||
|
||||
public function get(string $type): TranslatableEntityInterface
|
||||
{
|
||||
if (!isset($this->entities[$type])) {
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported translation entity type "%s".', $type));
|
||||
}
|
||||
|
||||
return $this->entities[$type];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getTypes(): array
|
||||
{
|
||||
return array_keys($this->entities);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Product\TranslatableFieldProvider;
|
||||
use Esun\Translation\Model\Product\TranslationApplier;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
|
||||
class ProductEntity implements TranslatableEntityInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly TranslatableFieldProvider $fieldProvider,
|
||||
private readonly TranslationApplier $translationApplier
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'product';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'Product';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->productRepository->getById($entityId)->getName();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'catalog/product/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
return $this->fieldProvider->getFields($entityId, $targetStoreIds);
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$updated = $this->translationApplier->apply($entityId, $storeIds, $fields);
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'message' => __('Translations applied to %1 store view(s).', $updated)->render(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMText;
|
||||
|
||||
class HtmlFragment
|
||||
{
|
||||
/**
|
||||
* @param array<string, DOMText> $textNodes
|
||||
* @param array<string, string> $texts
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly DOMDocument $document,
|
||||
private readonly DOMElement $root,
|
||||
private readonly array $textNodes,
|
||||
private readonly array $texts,
|
||||
private readonly array $directivePlaceholders = []
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getTexts(): array
|
||||
{
|
||||
return $this->texts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $translations
|
||||
*/
|
||||
public function applyTranslations(array $translations): string
|
||||
{
|
||||
foreach ($this->textNodes as $id => $node) {
|
||||
if (array_key_exists($id, $translations)) {
|
||||
$node->nodeValue = $translations[$id];
|
||||
}
|
||||
}
|
||||
|
||||
$html = '';
|
||||
foreach ($this->root->childNodes as $childNode) {
|
||||
$html .= $this->document->saveHTML($childNode);
|
||||
}
|
||||
|
||||
$restored = $this->directivePlaceholders === [] ? $html : strtr($html, $this->directivePlaceholders);
|
||||
|
||||
return $this->normalizeMagentoDirectiveQuotes($restored);
|
||||
}
|
||||
|
||||
private function normalizeMagentoDirectiveQuotes(string $html): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
static function (array $matches): string {
|
||||
return str_ireplace(
|
||||
['"', '"', '"', ''', ''', '''],
|
||||
['"', '"', '"', "'", "'", "'"],
|
||||
$matches[0]
|
||||
);
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMNode;
|
||||
use DOMText;
|
||||
use DOMXPath;
|
||||
|
||||
class HtmlTextExtractor
|
||||
{
|
||||
private const ROOT_ID = 'esun-translation-root';
|
||||
private const DIRECTIVE_TOKEN_PREFIX = '__ESUN_HTML_DIRECTIVE_';
|
||||
|
||||
public function extract(string $html): HtmlFragment
|
||||
{
|
||||
[$protectedHtml, $directivePlaceholders] = $this->protectMagentoDirectives($html);
|
||||
$document = $this->createDocument($protectedHtml);
|
||||
$xpath = new DOMXPath($document);
|
||||
$query = sprintf(
|
||||
'//*[@id="%s"]//text()[normalize-space(.) != "" and not(ancestor::script) and not(ancestor::style) and not(ancestor::code) and not(ancestor::pre)]',
|
||||
self::ROOT_ID
|
||||
);
|
||||
$nodes = $xpath->query($query);
|
||||
$textNodes = [];
|
||||
$texts = [];
|
||||
$index = 0;
|
||||
|
||||
if ($nodes !== false) {
|
||||
foreach ($nodes as $node) {
|
||||
if (!$node instanceof DOMText) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = $this->restoreMagentoDirectives($node->nodeValue ?? '', $directivePlaceholders);
|
||||
if (trim($text) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = 'html_' . $index++;
|
||||
$textNodes[$id] = $node;
|
||||
$texts[$id] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
$root = $document->getElementById(self::ROOT_ID);
|
||||
if (!$root) {
|
||||
throw new \RuntimeException('Unable to parse HTML fragment.');
|
||||
}
|
||||
|
||||
return new HtmlFragment($document, $root, $textNodes, $texts, $directivePlaceholders);
|
||||
}
|
||||
|
||||
private function createDocument(string $html): DOMDocument
|
||||
{
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$wrappedHtml = sprintf(
|
||||
'<?xml encoding="UTF-8"><div id="%s">%s</div>',
|
||||
self::ROOT_ID,
|
||||
$html
|
||||
);
|
||||
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
$loaded = $document->loadHTML($wrappedHtml, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
|
||||
if (!$loaded) {
|
||||
throw new \RuntimeException('Unable to parse HTML fragment.');
|
||||
}
|
||||
|
||||
return $document;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: array<string, string>}
|
||||
*/
|
||||
private function protectMagentoDirectives(string $html): array
|
||||
{
|
||||
$placeholders = [];
|
||||
$index = 0;
|
||||
$protected = preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
function (array $matches) use (&$placeholders, &$index): string {
|
||||
$token = self::DIRECTIVE_TOKEN_PREFIX . $index++ . '__';
|
||||
$placeholders[$token] = $this->normalizeMagentoDirectiveQuotes($matches[0]);
|
||||
|
||||
return $token;
|
||||
},
|
||||
$html
|
||||
);
|
||||
|
||||
return [$protected ?? $html, $placeholders];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $placeholders
|
||||
*/
|
||||
private function restoreMagentoDirectives(string $html, array $placeholders): string
|
||||
{
|
||||
$restored = $placeholders === [] ? $html : strtr($html, $placeholders);
|
||||
|
||||
return $this->normalizeMagentoDirectiveQuotes($restored);
|
||||
}
|
||||
|
||||
private function normalizeMagentoDirectiveQuotes(string $html): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
static function (array $matches): string {
|
||||
return str_ireplace(
|
||||
['"', '"', '"', ''', ''', '''],
|
||||
['"', '"', '"', "'", "'", "'"],
|
||||
$matches[0]
|
||||
);
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
|
||||
class HtmlTranslationValidator
|
||||
{
|
||||
/**
|
||||
* DOMDocument::loadHTML uses an HTML4 parser and reports safe HTML5/Page Builder tags as invalid.
|
||||
*/
|
||||
private const HTML5_ALLOWED_INVALID_TAGS = [
|
||||
'article',
|
||||
'aside',
|
||||
'audio',
|
||||
'canvas',
|
||||
'figcaption',
|
||||
'figure',
|
||||
'footer',
|
||||
'header',
|
||||
'main',
|
||||
'nav',
|
||||
'picture',
|
||||
'section',
|
||||
'source',
|
||||
'summary',
|
||||
'template',
|
||||
'time',
|
||||
'video',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function validate(string $html): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
if (substr_count($html, '{{') !== substr_count($html, '}}')) {
|
||||
$errors[] = 'Magento directive braces are unbalanced.';
|
||||
}
|
||||
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
$loaded = $document->loadHTML(
|
||||
'<?xml encoding="UTF-8"><div>' . $html . '</div>',
|
||||
LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED
|
||||
);
|
||||
$libxmlErrors = libxml_get_errors();
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
|
||||
if (!$loaded) {
|
||||
return ['HTML cannot be parsed.'];
|
||||
}
|
||||
|
||||
foreach ($libxmlErrors as $error) {
|
||||
if ($error->level >= LIBXML_ERR_ERROR) {
|
||||
if ($this->isAllowedHtml5InvalidTagMessage(trim($error->message))) {
|
||||
continue;
|
||||
}
|
||||
$errors[] = trim($error->message);
|
||||
}
|
||||
}
|
||||
|
||||
$xpath = new DOMXPath($document);
|
||||
foreach (['script', 'iframe', 'object', 'embed'] as $tag) {
|
||||
$nodes = $xpath->query('//' . $tag);
|
||||
if ($nodes !== false && $nodes->length > 0) {
|
||||
$errors[] = sprintf('Disallowed <%s> tag found.', $tag);
|
||||
}
|
||||
}
|
||||
|
||||
$allNodes = $xpath->query('//*');
|
||||
if ($allNodes !== false) {
|
||||
foreach ($allNodes as $node) {
|
||||
if (!$node instanceof DOMElement || !$node->hasAttributes()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($node->attributes as $attribute) {
|
||||
$name = strtolower($attribute->nodeName);
|
||||
$value = strtolower(trim($attribute->nodeValue ?? ''));
|
||||
if (str_starts_with($name, 'on')) {
|
||||
$errors[] = sprintf('Disallowed event attribute "%s" found.', $name);
|
||||
}
|
||||
if (in_array($name, ['href', 'src'], true) && str_starts_with($value, 'javascript:')) {
|
||||
$errors[] = sprintf('Disallowed javascript URL in "%s" found.', $name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique(array_filter($errors)));
|
||||
}
|
||||
|
||||
private function isAllowedHtml5InvalidTagMessage(string $message): bool
|
||||
{
|
||||
if (!preg_match('/^Tag ([a-z0-9:-]+) invalid$/i', $message, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return in_array(strtolower($matches[1]), self::HTML5_ALLOWED_INVALID_TAGS, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Product;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
|
||||
|
||||
class TranslatableFieldProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly ProductAttributeRepositoryInterface $attributeRepository
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function getFields(int $productId, array $targetStoreIds = []): array
|
||||
{
|
||||
$sourceProduct = $this->productRepository->getById($productId, false, $this->config->getSourceStoreId());
|
||||
$targetProduct = $targetStoreIds !== []
|
||||
? $this->productRepository->getById($productId, false, (int)reset($targetStoreIds))
|
||||
: null;
|
||||
$fields = [];
|
||||
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
$code = (string)$attribute->getAttributeCode();
|
||||
$sourceValue = (string)($sourceProduct->getData($code) ?? '');
|
||||
$targetValue = $targetProduct ? (string)($targetProduct->getData($code) ?? '') : '';
|
||||
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => (string)$attribute->getDefaultFrontendLabel() ?: $code,
|
||||
'source_value' => $sourceValue,
|
||||
'target_value' => $targetValue,
|
||||
'is_html' => $this->isHtmlAttribute($attribute),
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Attribute[]
|
||||
*/
|
||||
public function getAttributes(): array
|
||||
{
|
||||
$attributes = [];
|
||||
foreach ($this->config->getTranslatableAttributeCodes() as $code) {
|
||||
try {
|
||||
$attribute = $this->attributeRepository->get($code);
|
||||
} catch (\Throwable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$attribute instanceof Attribute) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_array((string)$attribute->getFrontendInput(), ['text', 'textarea'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($attribute->isScopeGlobal()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes[$code] = $attribute;
|
||||
}
|
||||
|
||||
return array_values($attributes);
|
||||
}
|
||||
|
||||
public function isAttributeAllowed(string $code): bool
|
||||
{
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
if ((string)$attribute->getAttributeCode() === $code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isHtmlAttributeCode(string $code): bool
|
||||
{
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
if ((string)$attribute->getAttributeCode() === $code) {
|
||||
return $this->isHtmlAttribute($attribute);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function isHtmlAttribute(Attribute $attribute): bool
|
||||
{
|
||||
return (bool)$attribute->getIsWysiwygEnabled()
|
||||
|| in_array((string)$attribute->getAttributeCode(), ['description', 'short_description'], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Product;
|
||||
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
|
||||
class TranslationApplier
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly TranslatableFieldProvider $fieldProvider,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $storeIds
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
public function apply(int $productId, array $storeIds, array $fields): int
|
||||
{
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$product = $this->productRepository->getById($productId, false, $storeId);
|
||||
$product->setStoreId($storeId);
|
||||
foreach ($fields as $code => $value) {
|
||||
$product->setData($code, $value);
|
||||
}
|
||||
$this->productRepository->save($product);
|
||||
$updated++;
|
||||
}
|
||||
|
||||
if ($updated === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!$this->fieldProvider->isAttributeAllowed($code)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ($this->fieldProvider->isHtmlAttributeCode($code)) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\StoreView;
|
||||
|
||||
class LanguageGroup
|
||||
{
|
||||
/**
|
||||
* @param int[] $storeIds
|
||||
* @param string[] $storeCodes
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $label,
|
||||
private readonly string $targetLocale,
|
||||
private readonly array $storeIds,
|
||||
private readonly array $storeCodes
|
||||
) {
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return $this->label;
|
||||
}
|
||||
|
||||
public function getTargetLocale(): string
|
||||
{
|
||||
return $this->targetLocale;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
public function getStoreIds(): array
|
||||
{
|
||||
return $this->storeIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getStoreCodes(): array
|
||||
{
|
||||
return $this->storeCodes;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'label' => $this->label,
|
||||
'target_locale' => $this->targetLocale,
|
||||
'store_ids' => $this->storeIds,
|
||||
'store_codes' => $this->storeCodes,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\StoreView;
|
||||
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class LanguageGroupProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StoreManagerInterface $storeManager
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return LanguageGroup[]
|
||||
*/
|
||||
public function getGroups(): array
|
||||
{
|
||||
$groups = [];
|
||||
foreach ($this->storeManager->getStores(false) as $store) {
|
||||
if (!$store->isActive()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$languageCode = $this->getLanguageCode((string)$store->getCode());
|
||||
if ($languageCode === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$groups[$languageCode]['label'] = $this->getLanguageLabel($languageCode);
|
||||
$groups[$languageCode]['store_ids'][] = (int)$store->getId();
|
||||
$groups[$languageCode]['store_codes'][] = (string)$store->getCode();
|
||||
}
|
||||
|
||||
ksort($groups);
|
||||
|
||||
return array_map(
|
||||
static fn (array $group): LanguageGroup => new LanguageGroup(
|
||||
$group['label'],
|
||||
$group['target_locale'],
|
||||
$group['store_ids'],
|
||||
$group['store_codes']
|
||||
),
|
||||
array_map(
|
||||
static fn (array $group, string $languageCode): array => $group + ['target_locale' => $languageCode],
|
||||
$groups,
|
||||
array_keys($groups)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function getGroup(string $label): ?LanguageGroup
|
||||
{
|
||||
foreach ($this->getGroups() as $group) {
|
||||
if ($group->getLabel() === $label || $group->getTargetLocale() === $label) {
|
||||
return $group;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function getLanguageCode(string $storeCode): string
|
||||
{
|
||||
if (!preg_match('/^([a-z]{2,3})(?:[_-]|$)/i', $storeCode, $matches)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return strtolower($matches[1]);
|
||||
}
|
||||
|
||||
private function getLanguageLabel(string $languageCode): string
|
||||
{
|
||||
if (class_exists(\Locale::class)) {
|
||||
$label = \Locale::getDisplayLanguage($languageCode, 'en');
|
||||
if (is_string($label) && $label !== '') {
|
||||
return ucfirst($label);
|
||||
}
|
||||
}
|
||||
|
||||
return strtoupper($languageCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Translation;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
|
||||
class ApplyService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function apply(string $type, int $entityId, string $languageLabel, array $fields): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
throw new \RuntimeException('Esun Translation is disabled.');
|
||||
}
|
||||
|
||||
$group = $this->languageGroupProvider->getGroup($languageLabel);
|
||||
if (!$group) {
|
||||
throw new \RuntimeException('Language group was not found.');
|
||||
}
|
||||
|
||||
return $this->entityPool->get($type)->apply($entityId, $group->getStoreIds(), $fields);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Translation;
|
||||
|
||||
use Esun\Translation\Api\TranslatorInterface;
|
||||
use Esun\Translation\Model\Ai\ProtectedTextProcessor;
|
||||
use Esun\Translation\Model\Config;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\Html\HtmlTextExtractor;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
|
||||
class TranslationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider,
|
||||
private readonly HtmlTextExtractor $htmlTextExtractor,
|
||||
private readonly HtmlTranslationValidator $htmlValidator,
|
||||
private readonly ProtectedTextProcessor $protectedTextProcessor,
|
||||
private readonly TranslatorInterface $translator
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $sourceOverrides
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function translate(string $type, int $entityId, string $languageLabel, array $sourceOverrides = []): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
throw new \RuntimeException('Esun Translation is disabled.');
|
||||
}
|
||||
|
||||
$entity = $this->entityPool->get($type);
|
||||
$group = $this->languageGroupProvider->getGroup($languageLabel);
|
||||
if (!$group) {
|
||||
throw new \RuntimeException('Language group was not found.');
|
||||
}
|
||||
|
||||
$fields = $entity->getFields($entityId, $group->getStoreIds());
|
||||
$plainUnits = [];
|
||||
$restoreMaps = [];
|
||||
$htmlFragments = [];
|
||||
$fieldUnits = [];
|
||||
|
||||
foreach ($fields as $field) {
|
||||
$code = (string)$field['code'];
|
||||
$sourceValue = array_key_exists($code, $sourceOverrides)
|
||||
? (string)$sourceOverrides[$code]
|
||||
: (string)$field['source_value'];
|
||||
if (trim($sourceValue) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((bool)$field['is_html']) {
|
||||
$fragment = $this->htmlTextExtractor->extract($sourceValue);
|
||||
$htmlFragments[$code] = $fragment;
|
||||
foreach ($fragment->getTexts() as $nodeId => $text) {
|
||||
[$protectedText, $placeholders] = $this->protectedTextProcessor->protect($text);
|
||||
$unitId = $code . '::' . $nodeId;
|
||||
$plainUnits[$unitId] = $protectedText;
|
||||
$restoreMaps[$unitId] = $placeholders;
|
||||
$fieldUnits[$code][] = $unitId;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
[$protectedText, $placeholders] = $this->protectedTextProcessor->protect($sourceValue);
|
||||
$plainUnits[$code] = $protectedText;
|
||||
$restoreMaps[$code] = $placeholders;
|
||||
}
|
||||
|
||||
$translatedUnits = $this->translator->translate(
|
||||
$plainUnits,
|
||||
$this->config->getSourceLocale(),
|
||||
$group->getTargetLocale()
|
||||
);
|
||||
foreach ($translatedUnits as $unitId => $text) {
|
||||
$translatedUnits[$unitId] = $this->protectedTextProcessor->restore($text, $restoreMaps[$unitId] ?? []);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($fields as $field) {
|
||||
$code = (string)$field['code'];
|
||||
if (!isset($htmlFragments[$code])) {
|
||||
if (isset($translatedUnits[$code])) {
|
||||
$result[$code] = $translatedUnits[$code];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$nodeTranslations = [];
|
||||
foreach ($fieldUnits[$code] ?? [] as $unitId) {
|
||||
[, $nodeId] = explode('::', $unitId, 2);
|
||||
$nodeTranslations[$nodeId] = $translatedUnits[$unitId] ?? '';
|
||||
}
|
||||
|
||||
$translatedHtml = $htmlFragments[$code]->applyTranslations($nodeTranslations);
|
||||
$errors = $this->htmlValidator->validate($translatedHtml);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'Translated HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
$result[$code] = $translatedHtml;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Plugin\Adminhtml;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Cms\Ui\Component\Listing\Column\BlockActions;
|
||||
use Magento\Framework\UrlInterface;
|
||||
|
||||
class AddCmsBlockRowTranslateAction
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly UrlInterface $urlBuilder
|
||||
) {
|
||||
}
|
||||
|
||||
public function afterPrepareDataSource(BlockActions $subject, array $dataSource): array
|
||||
{
|
||||
if (!$this->config->isEnabled() || empty($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
$columnName = (string)$subject->getData('name');
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
if (empty($item['block_id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$item[$columnName]['translate'] = [
|
||||
'href' => $this->urlBuilder->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'cms_block', 'entity_id' => (int)$item['block_id']]
|
||||
),
|
||||
'ariaLabel' => __('Translate ') . ($item['title'] ?? ''),
|
||||
'label' => __('Translate'),
|
||||
'hidden' => false,
|
||||
];
|
||||
}
|
||||
|
||||
return $dataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Plugin\Adminhtml;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Cms\Ui\Component\Listing\Column\PageActions;
|
||||
use Magento\Framework\UrlInterface;
|
||||
|
||||
class AddCmsPageRowTranslateAction
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly UrlInterface $urlBuilder
|
||||
) {
|
||||
}
|
||||
|
||||
public function afterPrepareDataSource(PageActions $subject, array $dataSource): array
|
||||
{
|
||||
if (!$this->config->isEnabled() || empty($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
$columnName = (string)$subject->getData('name');
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
if (empty($item['page_id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$item[$columnName]['translate'] = [
|
||||
'href' => $this->urlBuilder->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'cms_page', 'entity_id' => (int)$item['page_id']]
|
||||
),
|
||||
'ariaLabel' => __('Translate ') . ($item['title'] ?? ''),
|
||||
'label' => __('Translate'),
|
||||
'hidden' => false,
|
||||
];
|
||||
}
|
||||
|
||||
return $dataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Plugin\Adminhtml;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Catalog\Block\Adminhtml\Product as ProductListBlock;
|
||||
use Magento\Framework\View\LayoutInterface;
|
||||
|
||||
class AddProductListTranslateButton
|
||||
{
|
||||
public function __construct(private readonly Config $config)
|
||||
{
|
||||
}
|
||||
|
||||
public function beforeSetLayout(ProductListBlock $subject, LayoutInterface $layout): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
return [$layout];
|
||||
}
|
||||
|
||||
$url = $subject->getUrl('esun_translation/translate/index', ['entity_type' => 'product']);
|
||||
$message = __('Select exactly one product to translate.');
|
||||
|
||||
$subject->addButton(
|
||||
'Esun_Translation_translate',
|
||||
[
|
||||
'label' => __('Translate'),
|
||||
'class' => 'action-secondary',
|
||||
'onclick' => sprintf(
|
||||
<<<'JS'
|
||||
(function () {
|
||||
require(['uiRegistry', 'Magento_Ui/js/modal/alert'], function (registry, alert) {
|
||||
var selections = null;
|
||||
registry.get(function (component) {
|
||||
if (!selections
|
||||
&& component
|
||||
&& component.name
|
||||
&& component.name.indexOf('product_listing') === 0
|
||||
&& component.name.indexOf('.ids') !== -1
|
||||
&& typeof component.selected === 'function'
|
||||
) {
|
||||
selections = component;
|
||||
}
|
||||
});
|
||||
|
||||
var selected = selections ? selections.selected() : [];
|
||||
var excluded = selections && typeof selections.excluded === 'function' ? selections.excluded() : [];
|
||||
|
||||
if (excluded === false || selected.length !== 1) {
|
||||
alert({
|
||||
title: '%s',
|
||||
content: '%s'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLocation('%sentity_id/' + selected[0] + '/');
|
||||
});
|
||||
}())
|
||||
JS,
|
||||
(string)__('Esun Translation'),
|
||||
(string)$message,
|
||||
$url
|
||||
),
|
||||
],
|
||||
0,
|
||||
35
|
||||
);
|
||||
|
||||
return [$layout];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Plugin\Adminhtml;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Catalog\Ui\Component\Listing\Columns\ProductActions;
|
||||
use Magento\Framework\UrlInterface;
|
||||
|
||||
class AddProductRowTranslateAction
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly UrlInterface $urlBuilder
|
||||
) {
|
||||
}
|
||||
|
||||
public function afterPrepareDataSource(ProductActions $subject, array $dataSource): array
|
||||
{
|
||||
if (!$this->config->isEnabled() || empty($dataSource['data']['items'])) {
|
||||
return $dataSource;
|
||||
}
|
||||
|
||||
$columnName = (string)$subject->getData('name');
|
||||
foreach ($dataSource['data']['items'] as &$item) {
|
||||
if (empty($item['entity_id'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$item[$columnName]['translate'] = [
|
||||
'href' => $this->urlBuilder->getUrl(
|
||||
'esun_translation/translate/index',
|
||||
['entity_type' => 'product', 'entity_id' => (int)$item['entity_id']]
|
||||
),
|
||||
'ariaLabel' => __('Translate ') . ($item['name'] ?? ''),
|
||||
'label' => __('Translate'),
|
||||
'hidden' => false,
|
||||
];
|
||||
}
|
||||
|
||||
return $dataSource;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
# Esun_Translation 安装与使用说明
|
||||
|
||||
## 模块说明
|
||||
|
||||
`Esun_Translation` 是 Magento 2 后台 AI 辅助多语言翻译模块。当前支持:
|
||||
|
||||
当前版本:`1.2.2`
|
||||
|
||||
- 产品:编辑页按钮、产品列表顶部按钮、产品列表行操作。
|
||||
- CMS Page:编辑页按钮、列表行操作。
|
||||
- CMS Block:编辑页按钮、列表行操作。
|
||||
|
||||
模块按配置的语言组列出目标 Store View,管理员打开统一翻译工作台后,可以调用 OpenAI-compatible Chat Completions API 生成翻译结果,并在人工确认后写入对应 Store View 或 CMS store-specific 副本。
|
||||
|
||||
## 安装步骤
|
||||
|
||||
将压缩包中的目录放到 Magento 根目录:
|
||||
|
||||
```text
|
||||
app/code/Esun/Translation
|
||||
```
|
||||
|
||||
执行:
|
||||
|
||||
```bash
|
||||
php bin/magento module:enable Esun_Translation
|
||||
php bin/magento setup:upgrade
|
||||
php bin/magento cache:flush
|
||||
```
|
||||
|
||||
生产模式下再执行:
|
||||
|
||||
```bash
|
||||
php bin/magento setup:di:compile
|
||||
php bin/magento setup:static-content:deploy -f
|
||||
php bin/magento cache:flush
|
||||
```
|
||||
|
||||
确认模块状态:
|
||||
|
||||
```bash
|
||||
php bin/magento module:status Esun_Translation
|
||||
```
|
||||
|
||||
## 后台配置
|
||||
|
||||
入口:
|
||||
|
||||
```text
|
||||
Stores > Configuration > Services > Esun Translation
|
||||
```
|
||||
|
||||
### General
|
||||
|
||||
- `Enabled`:启用或关闭模块。
|
||||
- `Source Locale`:源语言,例如 `en`。
|
||||
- `Source Store ID`:产品源 Store ID,通常为 `0`。CMS 使用当前打开的 Page/Block 作为源内容。
|
||||
- `Translatable Product Attributes`:产品可翻译属性 code,逗号或换行分隔。
|
||||
- `Language Store View Groups`:语言和 Store View 映射,每行一个语言组。
|
||||
|
||||
语言组格式:
|
||||
|
||||
```text
|
||||
语言名称|目标语言代码|store_code_1,store_code_2
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
English|en|us_EN,de_EN
|
||||
German|de|us_DE,de_DE
|
||||
French|fr|us_FR,de_FR
|
||||
```
|
||||
|
||||
### AI Provider
|
||||
|
||||
- `Provider`:当前支持 `OpenAI Compatible`。
|
||||
- `API Base URL`:默认 `https://api.openai.com/v1`。
|
||||
- `API Key`:AI 接口密钥,使用 Magento encrypted config 保存。
|
||||
- `Model`:模型名称。
|
||||
- `Temperature`:建议 `0.2`。
|
||||
- `Timeout Seconds`:建议 `60`。
|
||||
|
||||
模块会优先要求 AI 返回符合 JSON Schema 的严格 JSON:
|
||||
|
||||
```json
|
||||
{"translations":{"field_key":"translated text"}}
|
||||
```
|
||||
|
||||
服务端会校验所有请求字段必须存在,且不得返回额外字段。
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 产品翻译
|
||||
|
||||
入口:
|
||||
|
||||
```text
|
||||
Catalog > Products
|
||||
```
|
||||
|
||||
可在产品编辑页点击 `Translate`,也可在产品列表行操作中点击 `Translate`。列表顶部的 `Translate` 按钮要求只选择一个产品。
|
||||
|
||||
### CMS Page 翻译
|
||||
|
||||
入口:
|
||||
|
||||
```text
|
||||
Content > Elements > Pages
|
||||
```
|
||||
|
||||
可在 Page 编辑页点击 `Translate`,也可在 Page 列表行操作中点击 `Translate`。
|
||||
|
||||
应用时,模块会按目标 Store View 查找相同 `identifier` 的 Page:
|
||||
|
||||
- 找到时更新该 Page 的翻译字段。
|
||||
- 找不到时创建一个绑定到目标 Store View 的 Page 副本。
|
||||
- 如果源 Page 绑定 `All Store Views` 且目标副本不存在,会拒绝自动创建,避免 identifier 冲突。
|
||||
|
||||
### CMS Block 翻译
|
||||
|
||||
入口:
|
||||
|
||||
```text
|
||||
Content > Elements > Blocks
|
||||
```
|
||||
|
||||
操作方式与 CMS Page 一致。Block 使用相同 `identifier` 和目标 Store View 匹配或创建副本。
|
||||
|
||||
### 翻译工作台
|
||||
|
||||
1. 选择语言组,例如 `German: us_DE, de_DE`。
|
||||
2. 点击语言组旁边的 `Translate`。
|
||||
3. 弹窗左侧是源内容,右侧是目标语言当前内容。
|
||||
4. 可人工修改左侧源内容作为本次 AI 输入。
|
||||
5. 点击弹窗右上角 `Translate` 调用 AI。
|
||||
6. 检查并修改右侧结果。
|
||||
7. 点击 `Apply` 写入目标 Store View。
|
||||
|
||||
## HTML 字段处理
|
||||
|
||||
产品 `description`、`short_description`,以及 CMS `content` 会按 HTML 处理:
|
||||
|
||||
1. 服务端解析 HTML。
|
||||
2. 只提取可翻译文本节点。
|
||||
3. 跳过 `script`、`style`、`code`、`pre`。
|
||||
4. 保护 Magento directive、URL、占位符等内容。
|
||||
5. AI 只翻译文本节点。
|
||||
6. 服务端写回原始 DOM 结构。
|
||||
7. 应用前重新校验 HTML。
|
||||
|
||||
应用前会拦截危险 HTML,例如 `<script>`、事件属性、`javascript:` URL、损坏的 Magento directive。
|
||||
|
||||
`1.2.2` 修复了 Magento media directive 在 HTML 属性中被 DOM 解析器改写的问题,例如:
|
||||
|
||||
- `{{media url=wysiwyg/precision.png}}` 不会再被转成 `%7B%7Bmedia%20url=wysiwyg/precision.png%7D%7D`。
|
||||
- `{{media url=".renditions/wysiwyg/product_details/demo.png"}}` 会在 directive 内还原为 `{{media url=".renditions/wysiwyg/product_details/demo.png"}}`。
|
||||
|
||||
## 权限
|
||||
|
||||
新增 ACL:
|
||||
|
||||
```text
|
||||
Esun_Translation::config
|
||||
Esun_Translation::translate_product
|
||||
Esun_Translation::apply_product_translation
|
||||
Esun_Translation::translate_cms_page
|
||||
Esun_Translation::apply_cms_page_translation
|
||||
Esun_Translation::translate_cms_block
|
||||
Esun_Translation::apply_cms_block_translation
|
||||
```
|
||||
|
||||
如管理员看不到按钮,请检查:
|
||||
|
||||
```text
|
||||
System > Permissions > User Roles
|
||||
```
|
||||
|
||||
## 验证方法
|
||||
|
||||
PHP 语法检查:
|
||||
|
||||
```bash
|
||||
find app/code/Esun/Translation -name "*.php" -print0 | xargs -0 -n1 php -l
|
||||
```
|
||||
|
||||
Windows PowerShell:
|
||||
|
||||
```powershell
|
||||
Get-ChildItem -Recurse -Filter *.php app\code\Esun\Translation | ForEach-Object { php -l $_.FullName }
|
||||
```
|
||||
|
||||
单元测试:
|
||||
|
||||
```bash
|
||||
php vendor/bin/phpunit app/code/Esun/Translation/Test/Unit
|
||||
```
|
||||
|
||||
后台手工测试:
|
||||
|
||||
1. 配置并启用模块。
|
||||
2. 配置至少一个目标语言组。
|
||||
3. 分别从产品、CMS Page、CMS Block 打开翻译工作台。
|
||||
4. 点击语言组 `Translate`,确认字段加载正常。
|
||||
5. 点击弹窗内 `Translate`,确认 AI 返回后右侧字段被填充。
|
||||
6. 修改右侧内容并点击 `Apply`。
|
||||
7. 切换目标 Store View 检查产品字段或 CMS 副本内容。
|
||||
|
||||
## 卸载
|
||||
|
||||
```bash
|
||||
php bin/magento module:disable Esun_Translation
|
||||
php bin/magento setup:upgrade
|
||||
php bin/magento cache:flush
|
||||
```
|
||||
|
||||
删除代码目录:
|
||||
|
||||
```text
|
||||
app/code/Esun/Translation
|
||||
```
|
||||
|
||||
本模块不创建数据库表。旧 `Evebit_ProductTranslation` 配置会在 `setup:upgrade` 时自动复制到新的 `esun_translation/*` 配置路径。
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Setup\Patch\Data;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Setup\ModuleDataSetupInterface;
|
||||
use Magento\Framework\Setup\Patch\DataPatchInterface;
|
||||
|
||||
class MigrateOldConfig implements DataPatchInterface
|
||||
{
|
||||
private const OLD_PREFIX = 'evebit_product_translation/';
|
||||
private const NEW_PREFIX = 'esun_translation/';
|
||||
|
||||
public function __construct(
|
||||
private readonly ModuleDataSetupInterface $moduleDataSetup,
|
||||
private readonly ResourceConnection $resourceConnection
|
||||
) {
|
||||
}
|
||||
|
||||
public function apply(): self
|
||||
{
|
||||
$this->moduleDataSetup->getConnection()->startSetup();
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$table = $this->resourceConnection->getTableName('core_config_data');
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()
|
||||
->from($table)
|
||||
->where('path LIKE ?', self::OLD_PREFIX . '%')
|
||||
);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$newPath = self::NEW_PREFIX . substr((string)$row['path'], strlen(self::OLD_PREFIX));
|
||||
$exists = $connection->fetchOne(
|
||||
$connection->select()
|
||||
->from($table, ['config_id'])
|
||||
->where('scope = ?', $row['scope'])
|
||||
->where('scope_id = ?', $row['scope_id'])
|
||||
->where('path = ?', $newPath)
|
||||
->limit(1)
|
||||
);
|
||||
if ($exists) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$connection->insert($table, [
|
||||
'scope' => $row['scope'],
|
||||
'scope_id' => $row['scope_id'],
|
||||
'path' => $newPath,
|
||||
'value' => $row['value'],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->moduleDataSetup->getConnection()->endSetup();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public static function getDependencies(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getAliases(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Test\Unit\Model\Ai;
|
||||
|
||||
use Esun\Translation\Model\Ai\OpenAiCompatibleTranslator;
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Framework\HTTP\Client\Curl;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ReflectionMethod;
|
||||
|
||||
class OpenAiCompatibleTranslatorTest extends TestCase
|
||||
{
|
||||
public function testItAcceptsSchemaCompliantTranslations(): void
|
||||
{
|
||||
$translator = $this->createTranslator();
|
||||
|
||||
self::assertSame(
|
||||
['name' => 'PLA-Matte DE'],
|
||||
$this->normalize($translator, ['name' => 'PLA-Matte'], ['translations' => ['name' => 'PLA-Matte DE']])
|
||||
);
|
||||
}
|
||||
|
||||
public function testItRejectsMissingTranslationKeys(): void
|
||||
{
|
||||
$translator = $this->createTranslator();
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('AI response is missing translation key "name".');
|
||||
|
||||
$this->normalize($translator, ['name' => 'PLA-Matte'], ['translations' => []]);
|
||||
}
|
||||
|
||||
public function testItRejectsUnexpectedTranslationKeys(): void
|
||||
{
|
||||
$translator = $this->createTranslator();
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('AI response contains unexpected translation key "description".');
|
||||
|
||||
$this->normalize(
|
||||
$translator,
|
||||
['name' => 'PLA-Matte'],
|
||||
['translations' => ['name' => 'PLA-Matte DE', 'description' => 'Beschreibung']]
|
||||
);
|
||||
}
|
||||
|
||||
public function testItRejectsResponsesWithoutTranslationsObject(): void
|
||||
{
|
||||
$translator = $this->createTranslator();
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$this->expectExceptionMessage('AI response must be a JSON object with a "translations" object.');
|
||||
|
||||
$this->normalize($translator, ['name' => 'PLA-Matte'], ['name' => 'PLA-Matte DE']);
|
||||
}
|
||||
|
||||
public function testItUsesExplicitTranslationsPromptWhenJsonSchemaIsUnsupported(): void
|
||||
{
|
||||
$config = $this->createMock(Config::class);
|
||||
$config->method('getApiKey')->willReturn('test-key');
|
||||
$config->method('getApiBaseUrl')->willReturn('https://example.test');
|
||||
$config->method('getModel')->willReturn('test-model');
|
||||
$config->method('getTemperature')->willReturn(0.2);
|
||||
$config->method('getTimeout')->willReturn(10);
|
||||
|
||||
$json = new Json();
|
||||
$payloads = [];
|
||||
$curl = $this->createMock(Curl::class);
|
||||
$curl->method('setTimeout');
|
||||
$curl->method('addHeader');
|
||||
$curl->expects(self::exactly(2))
|
||||
->method('post')
|
||||
->willReturnCallback(function (string $url, string $payload) use (&$payloads): void {
|
||||
$payloads[] = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
|
||||
});
|
||||
$curl->expects(self::exactly(2))
|
||||
->method('getStatus')
|
||||
->willReturnOnConsecutiveCalls(400, 200);
|
||||
$curl->expects(self::exactly(2))
|
||||
->method('getBody')
|
||||
->willReturnOnConsecutiveCalls(
|
||||
'{"error":{"message":"This response_format type is unavailable now"}}',
|
||||
'{"choices":[{"message":{"content":"{\"translations\":{\"name\":\"PLA-Matte\"}}"}}]}'
|
||||
);
|
||||
|
||||
$translator = new OpenAiCompatibleTranslator(
|
||||
$config,
|
||||
$curl,
|
||||
$json,
|
||||
$this->createMock(LoggerInterface::class)
|
||||
);
|
||||
|
||||
self::assertSame(['name' => 'PLA-Matte'], $translator->translate(['name' => 'PLA-Matte'], 'en', 'de'));
|
||||
self::assertSame('json_schema', $payloads[0]['response_format']['type']);
|
||||
self::assertSame('json_object', $payloads[1]['response_format']['type']);
|
||||
self::assertStringContainsString('{"translations":{"field_key":"translated text"}}', $payloads[1]['messages'][0]['content']);
|
||||
self::assertStringContainsString('__ESUN_TRANSLATION_PRESERVE_0__', $payloads[1]['messages'][0]['content']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $sourceTexts
|
||||
* @param array<mixed> $translated
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function normalize(OpenAiCompatibleTranslator $translator, array $sourceTexts, array $translated): array
|
||||
{
|
||||
$method = new ReflectionMethod(OpenAiCompatibleTranslator::class, 'normalizeTranslations');
|
||||
$method->setAccessible(true);
|
||||
|
||||
return $method->invoke($translator, $sourceTexts, $translated);
|
||||
}
|
||||
|
||||
private function createTranslator(?LoggerInterface $logger = null): OpenAiCompatibleTranslator
|
||||
{
|
||||
return new OpenAiCompatibleTranslator(
|
||||
$this->createMock(Config::class),
|
||||
$this->createMock(Curl::class),
|
||||
new Json(),
|
||||
$logger ?: $this->createMock(LoggerInterface::class)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Test\Unit\Model\Ai;
|
||||
|
||||
use Esun\Translation\Model\Ai\ProtectedTextProcessor;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class ProtectedTextProcessorTest extends TestCase
|
||||
{
|
||||
public function testItRestoresProtectedTokens(): void
|
||||
{
|
||||
$processor = new ProtectedTextProcessor();
|
||||
[$protected, $map] = $processor->protect('Use {{media url="a.jpg"}} and https://example.com/%1.');
|
||||
|
||||
self::assertStringContainsString('__ESUN_TRANSLATION_PRESERVE_0__', $protected);
|
||||
self::assertSame(
|
||||
'Use {{media url="a.jpg"}} and https://example.com/%1.',
|
||||
$processor->restore($protected, $map)
|
||||
);
|
||||
}
|
||||
|
||||
public function testItRejectsMissingProtectedTokens(): void
|
||||
{
|
||||
$processor = new ProtectedTextProcessor();
|
||||
[, $map] = $processor->protect('Use {{media url="a.jpg"}}.');
|
||||
|
||||
$this->expectException(\RuntimeException::class);
|
||||
$processor->restore('translated without token', $map);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Test\Unit\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class EntityPoolTest extends TestCase
|
||||
{
|
||||
public function testItReturnsConfiguredEntity(): void
|
||||
{
|
||||
$entity = $this->createMock(TranslatableEntityInterface::class);
|
||||
$pool = new EntityPool(['cms_page' => $entity]);
|
||||
|
||||
self::assertSame($entity, $pool->get('cms_page'));
|
||||
self::assertSame(['cms_page'], $pool->getTypes());
|
||||
}
|
||||
|
||||
public function testItRejectsUnsupportedEntityType(): void
|
||||
{
|
||||
$pool = new EntityPool();
|
||||
|
||||
$this->expectException(\InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Unsupported translation entity type "unknown".');
|
||||
|
||||
$pool->get('unknown');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Test\Unit\Model\Html;
|
||||
|
||||
use Esun\Translation\Model\Html\HtmlTextExtractor;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class HtmlTextExtractorTest extends TestCase
|
||||
{
|
||||
public function testItTranslatesTextNodesWithoutChangingTags(): void
|
||||
{
|
||||
$extractor = new HtmlTextExtractor();
|
||||
$fragment = $extractor->extract(
|
||||
'<p class="intro">Fast <strong>printing</strong> {{media url="a.jpg"}}</p><img src="a.jpg">'
|
||||
);
|
||||
|
||||
self::assertSame(
|
||||
['html_0' => 'Fast ', 'html_1' => 'printing', 'html_2' => ' {{media url="a.jpg"}}'],
|
||||
$fragment->getTexts()
|
||||
);
|
||||
|
||||
$html = $fragment->applyTranslations([
|
||||
'html_0' => 'Schneller ',
|
||||
'html_1' => 'Druck',
|
||||
'html_2' => ' {{media url="a.jpg"}}',
|
||||
]);
|
||||
|
||||
self::assertStringContainsString('<p class="intro">Schneller <strong>Druck</strong>', $html);
|
||||
self::assertStringContainsString('<img src="a.jpg">', $html);
|
||||
}
|
||||
|
||||
public function testItPreservesMagentoDirectivesInsideHtmlAttributes(): void
|
||||
{
|
||||
$extractor = new HtmlTextExtractor();
|
||||
$fragment = $extractor->extract(
|
||||
'<figure class="pagebuilder-image">'
|
||||
. '<img src="{{media url=wysiwyg/precision.png}}" alt="Precision image">'
|
||||
. '<figcaption>High precision sample image</figcaption>'
|
||||
. '</figure>'
|
||||
);
|
||||
|
||||
$html = $fragment->applyTranslations([
|
||||
'html_0' => 'Hochpraezises Beispielbild',
|
||||
]);
|
||||
|
||||
self::assertStringContainsString('src="{{media url=wysiwyg/precision.png}}"', $html);
|
||||
self::assertStringNotContainsString('%7B%7Bmedia%20url=wysiwyg/precision.png%7D%7D', $html);
|
||||
self::assertStringContainsString('<figcaption>Hochpraezises Beispielbild</figcaption>', $html);
|
||||
}
|
||||
|
||||
public function testItPreservesQuotedMagentoDirectivesInsideHtmlAttributes(): void
|
||||
{
|
||||
$extractor = new HtmlTextExtractor();
|
||||
$fragment = $extractor->extract(
|
||||
'<figure class="pagebuilder-image">'
|
||||
. '<img src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"'
|
||||
. ' alt="" width="1000" height="444">'
|
||||
. '<figcaption>PETG luminous filament</figcaption>'
|
||||
. '</figure>'
|
||||
);
|
||||
|
||||
$html = $fragment->applyTranslations([
|
||||
'html_0' => 'PETG-Leuchtfilament',
|
||||
]);
|
||||
|
||||
self::assertStringContainsString(
|
||||
'src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"',
|
||||
$html
|
||||
);
|
||||
self::assertStringNotContainsString('".renditions/wysiwyg/product_details/petg_luminous_filament.png"', $html);
|
||||
self::assertStringContainsString('<figcaption>PETG-Leuchtfilament</figcaption>', $html);
|
||||
}
|
||||
|
||||
public function testItNormalizesEncodedDirectiveQuotesInsideHtmlAttributes(): void
|
||||
{
|
||||
$extractor = new HtmlTextExtractor();
|
||||
$fragment = $extractor->extract(
|
||||
'<figure class="pagebuilder-image">'
|
||||
. '<img src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"'
|
||||
. ' alt="" width="1000" height="444">'
|
||||
. '<figcaption>PETG luminous filament</figcaption>'
|
||||
. '</figure>'
|
||||
);
|
||||
|
||||
$html = $fragment->applyTranslations([
|
||||
'html_0' => 'PETG-Leuchtfilament',
|
||||
]);
|
||||
|
||||
self::assertStringContainsString(
|
||||
'src="{{media url=".renditions/wysiwyg/product_details/petg_luminous_filament.png"}}"',
|
||||
$html
|
||||
);
|
||||
self::assertStringNotContainsString('".renditions/wysiwyg/product_details/petg_luminous_filament.png"', $html);
|
||||
self::assertStringContainsString('<figcaption>PETG-Leuchtfilament</figcaption>', $html);
|
||||
}
|
||||
|
||||
public function testValidatorRejectsDangerousHtml(): void
|
||||
{
|
||||
$validator = new HtmlTranslationValidator();
|
||||
|
||||
self::assertSame([], $validator->validate('<p>Safe content</p>'));
|
||||
self::assertNotSame([], $validator->validate('<p onclick="alert(1)">Unsafe</p>'));
|
||||
self::assertNotSame([], $validator->validate('<script>alert(1)</script>'));
|
||||
}
|
||||
|
||||
public function testValidatorAllowsPageBuilderFigureHtml(): void
|
||||
{
|
||||
$validator = new HtmlTranslationValidator();
|
||||
|
||||
self::assertSame(
|
||||
[],
|
||||
$validator->validate(
|
||||
'<figure class="pagebuilder-image" data-content-type="image">'
|
||||
. '<img src="{{media url=.renditions/wysiwyg/product_details/demo.png}}" alt="">'
|
||||
. '<figcaption>Product image</figcaption>'
|
||||
. '</figure>'
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "esun/module-translation",
|
||||
"description": "Admin AI translation workflow for Magento 2 products and CMS content.",
|
||||
"version": "1.2.2",
|
||||
"type": "magento2-module",
|
||||
"license": "proprietary",
|
||||
"autoload": {
|
||||
"files": [
|
||||
"registration.php"
|
||||
],
|
||||
"psr-4": {
|
||||
"Esun\\Translation\\": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Magento_Backend::stores">
|
||||
<resource id="Magento_Backend::stores_settings">
|
||||
<resource id="Magento_Config::config">
|
||||
<resource id="Esun_Translation::config" title="Esun Translation Config" sortOrder="910"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
<resource id="Magento_Catalog::catalog">
|
||||
<resource id="Magento_Catalog::catalog_inventory">
|
||||
<resource id="Magento_Catalog::products">
|
||||
<resource id="Esun_Translation::translate_product" title="Translate Products" sortOrder="911"/>
|
||||
<resource id="Esun_Translation::apply_product_translation" title="Apply Product Translations" sortOrder="912"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
<resource id="Magento_Backend::content">
|
||||
<resource id="Magento_Backend::content_elements">
|
||||
<resource id="Magento_Cms::page">
|
||||
<resource id="Esun_Translation::translate_cms_page" title="Translate CMS Pages" sortOrder="913"/>
|
||||
<resource id="Esun_Translation::apply_cms_page_translation" title="Apply CMS Page Translations" sortOrder="914"/>
|
||||
</resource>
|
||||
<resource id="Magento_Cms::block">
|
||||
<resource id="Esun_Translation::translate_cms_block" title="Translate CMS Blocks" sortOrder="915"/>
|
||||
<resource id="Esun_Translation::apply_cms_block_translation" title="Apply CMS Block Translations" sortOrder="916"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
|
||||
<router id="admin">
|
||||
<route id="esun_translation" frontName="esun_translation">
|
||||
<module name="Esun_Translation" before="Magento_Backend"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,60 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
|
||||
<system>
|
||||
<tab id="services" translate="label" sortOrder="900">
|
||||
<label>Services</label>
|
||||
</tab>
|
||||
<section id="esun_translation" translate="label" sortOrder="910" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Esun Translation</label>
|
||||
<tab>services</tab>
|
||||
<resource>Esun_Translation::config</resource>
|
||||
<group id="general" translate="label" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>General</label>
|
||||
<field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Enabled</label>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
</field>
|
||||
<field id="source_locale" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Source Locale</label>
|
||||
<comment>Locale name passed to the AI service for default content values.</comment>
|
||||
</field>
|
||||
<field id="source_store_id" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Source Store ID</label>
|
||||
<comment>Use 0 for default/admin product values. CMS content uses the selected source item values.</comment>
|
||||
</field>
|
||||
<field id="translatable_attributes" translate="label comment" type="textarea" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Translatable Product Attributes</label>
|
||||
<comment>Comma-separated product attribute codes. CMS Page and CMS Block use built-in field sets.</comment>
|
||||
</field>
|
||||
<field id="language_groups" translate="label comment" type="textarea" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Language Store View Groups</label>
|
||||
<comment>One group per line: Label|target_locale|store_code_1,store_code_2. Example: German|de|us_DE,de_DE</comment>
|
||||
</field>
|
||||
</group>
|
||||
<group id="ai" translate="label" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>AI Provider</label>
|
||||
<field id="provider" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Provider</label>
|
||||
<source_model>Esun\Translation\Model\Config\Source\Provider</source_model>
|
||||
</field>
|
||||
<field id="api_base_url" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>API Base URL</label>
|
||||
</field>
|
||||
<field id="api_key" translate="label" type="obscure" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>API Key</label>
|
||||
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
|
||||
</field>
|
||||
<field id="model" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Model</label>
|
||||
</field>
|
||||
<field id="temperature" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Temperature</label>
|
||||
</field>
|
||||
<field id="timeout" translate="label" type="text" sortOrder="60" showInDefault="1" showInWebsite="0" showInStore="0">
|
||||
<label>Timeout Seconds</label>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default>
|
||||
<esun_translation>
|
||||
<general>
|
||||
<enabled>0</enabled>
|
||||
<source_locale>en</source_locale>
|
||||
<source_store_id>0</source_store_id>
|
||||
<translatable_attributes>name,short_description,description,meta_title,meta_keyword,meta_description</translatable_attributes>
|
||||
<language_groups>English|en|us_EN,de_EN
|
||||
German|de|us_DE,de_DE</language_groups>
|
||||
</general>
|
||||
<ai>
|
||||
<provider>openai_compatible</provider>
|
||||
<api_base_url>https://api.openai.com/v1</api_base_url>
|
||||
<model>gpt-4.1-mini</model>
|
||||
<temperature>0.2</temperature>
|
||||
<timeout>60</timeout>
|
||||
</ai>
|
||||
</esun_translation>
|
||||
</default>
|
||||
</config>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<preference for="Esun\Translation\Api\TranslatorInterface"
|
||||
type="Esun\Translation\Model\Ai\OpenAiCompatibleTranslator"/>
|
||||
<type name="Esun\Translation\Model\Entity\EntityPool">
|
||||
<arguments>
|
||||
<argument name="entities" xsi:type="array">
|
||||
<item name="product" xsi:type="object">Esun\Translation\Model\Entity\ProductEntity</item>
|
||||
<item name="cms_page" xsi:type="object">Esun\Translation\Model\Entity\CmsPageEntity</item>
|
||||
<item name="cms_block" xsi:type="object">Esun\Translation\Model\Entity\CmsBlockEntity</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
<type name="Magento\Catalog\Ui\Component\Listing\Columns\ProductActions">
|
||||
<plugin name="Esun_Translation_product_row_action"
|
||||
type="Esun\Translation\Plugin\Adminhtml\AddProductRowTranslateAction"/>
|
||||
</type>
|
||||
<type name="Magento\Cms\Ui\Component\Listing\Column\PageActions">
|
||||
<plugin name="Esun_Translation_cms_page_row_action"
|
||||
type="Esun\Translation\Plugin\Adminhtml\AddCmsPageRowTranslateAction"/>
|
||||
</type>
|
||||
<type name="Magento\Cms\Ui\Component\Listing\Column\BlockActions">
|
||||
<plugin name="Esun_Translation_cms_block_row_action"
|
||||
type="Esun\Translation\Plugin\Adminhtml\AddCmsBlockRowTranslateAction"/>
|
||||
</type>
|
||||
<type name="Magento\Config\Model\Config\TypePool">
|
||||
<arguments>
|
||||
<argument name="sensitive" xsi:type="array">
|
||||
<item name="esun_translation/ai/api_key" xsi:type="string">1</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun_Translation">
|
||||
<sequence>
|
||||
<module name="Magento_Catalog"/>
|
||||
<module name="Magento_Backend"/>
|
||||
<module name="Magento_Cms"/>
|
||||
<module name="Magento_Config"/>
|
||||
<module name="Magento_Store"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun_Translation',
|
||||
__DIR__
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<update handle="styles"/>
|
||||
<body>
|
||||
<referenceContainer name="content">
|
||||
<block class="Esun\Translation\Block\Adminhtml\Translation\Workspace"
|
||||
name="esun.translation.workspace"
|
||||
template="Esun_Translation::translation/workspace.phtml"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,317 @@
|
||||
<?php
|
||||
/** @var \Esun\Translation\Block\Adminhtml\Translation\Workspace $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
$configJson = $block->getConfigJson();
|
||||
$entityId = (int)$block->getEntityId();
|
||||
$entityLabel = $block->getEntityLabel();
|
||||
$entityTitle = $block->getEntityTitle();
|
||||
?>
|
||||
<div class="esun-translation" data-config='<?= $escaper->escapeHtmlAttr($configJson) ?>'>
|
||||
<div class="page-main-actions">
|
||||
<div class="page-actions">
|
||||
<?php if ($entityId): ?>
|
||||
<span class="esun-translation-context">
|
||||
<?= $escaper->escapeHtml(__('%1 #%2', $entityLabel, $entityId)) ?>
|
||||
<?php if ($entityTitle !== ''): ?>
|
||||
<span><?= $escaper->escapeHtml($entityTitle) ?></span>
|
||||
<?php endif; ?>
|
||||
</span>
|
||||
<a class="action-secondary" href="<?= $escaper->escapeUrl($block->getBackUrl()) ?>">
|
||||
<?= $escaper->escapeHtml(__('Back')) ?>
|
||||
</a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!$block->isEnabled()): ?>
|
||||
<div class="message message-warning">
|
||||
<div><?= $escaper->escapeHtml(__('Esun Translation is disabled in configuration.')) ?></div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!$entityId): ?>
|
||||
<div class="message message-warning">
|
||||
<div>
|
||||
<?= $escaper->escapeHtml(__('Open Esun Translation from a product, CMS page, or CMS block edit page/listing.')) ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="admin__fieldset">
|
||||
<div class="admin__field">
|
||||
<div class="admin__field-label">
|
||||
<label><?= $escaper->escapeHtml(__('Languages')) ?></label>
|
||||
</div>
|
||||
<div class="admin__field-control" id="esun-language-list"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="esun-translation-editor" style="display:none;">
|
||||
<div class="esun-editor-toolbar">
|
||||
<strong id="esun-editor-title"></strong>
|
||||
<button type="button" class="action-secondary" id="esun-run-translate">
|
||||
<?= $escaper->escapeHtml(__('Translate')) ?>
|
||||
</button>
|
||||
<button type="button" class="action-primary" id="esun-apply-translation">
|
||||
<?= $escaper->escapeHtml(__('Apply')) ?>
|
||||
</button>
|
||||
</div>
|
||||
<div id="esun-editor-fields"></div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.esun-translation-context {
|
||||
display: inline-block;
|
||||
font-weight: 600;
|
||||
margin-right: 12px;
|
||||
padding: 7px 0;
|
||||
}
|
||||
.esun-translation-context span {
|
||||
color: #666;
|
||||
font-weight: 400;
|
||||
margin-left: 8px;
|
||||
}
|
||||
.esun-translation .esun-language-row {
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #e3e3e3;
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
justify-content: space-between;
|
||||
max-width: 760px;
|
||||
padding: 12px 0;
|
||||
}
|
||||
.esun-translation .esun-language-stores {
|
||||
color: #666;
|
||||
margin-left: 10px;
|
||||
}
|
||||
.esun-translation .esun-language-row.is-disabled {
|
||||
opacity: .65;
|
||||
}
|
||||
.esun-editor-toolbar {
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #ddd;
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 16px;
|
||||
padding-bottom: 12px;
|
||||
}
|
||||
.esun-editor-toolbar strong {
|
||||
margin-right: auto;
|
||||
}
|
||||
.esun-field {
|
||||
border-bottom: 1px solid #e5e5e5;
|
||||
margin-bottom: 16px;
|
||||
padding-bottom: 16px;
|
||||
}
|
||||
.esun-field-label {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.esun-field-columns {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
}
|
||||
.esun-field textarea {
|
||||
min-height: 130px;
|
||||
resize: vertical;
|
||||
width: 100%;
|
||||
}
|
||||
@media (max-width: 767px) {
|
||||
.esun-field-columns {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
require([
|
||||
'jquery',
|
||||
'Magento_Ui/js/modal/modal',
|
||||
'Magento_Ui/js/modal/alert',
|
||||
'mage/translate'
|
||||
], function ($, modal, alert, $t) {
|
||||
'use strict';
|
||||
|
||||
var root = $('.esun-translation');
|
||||
var config = root.data('config');
|
||||
var currentLanguage = null;
|
||||
var currentFields = [];
|
||||
|
||||
var editor = $('#esun-translation-editor').modal({
|
||||
type: 'slide',
|
||||
title: $t('Esun Translation'),
|
||||
modalClass: 'esun-translation-modal',
|
||||
buttons: []
|
||||
});
|
||||
|
||||
function entityId() {
|
||||
return parseInt(config.entityId, 10) || 0;
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
alert({title: $t('Esun Translation'), content: message});
|
||||
}
|
||||
|
||||
function renderLanguages() {
|
||||
var list = $('#esun-language-list').empty();
|
||||
var sourceLocale = String(config.sourceLocale || '').toLowerCase();
|
||||
|
||||
if (!config.languages.length) {
|
||||
list.append($('<div/>').addClass('message message-warning').text($t('No valid language groups are configured.')));
|
||||
return;
|
||||
}
|
||||
|
||||
config.languages.forEach(function (language) {
|
||||
var targetLocale = String(language.target_locale || '').toLowerCase();
|
||||
var isSourceLanguage = sourceLocale && sourceLocale === targetLocale;
|
||||
var row = $('<div/>').addClass('esun-language-row').toggleClass('is-disabled', isSourceLanguage);
|
||||
var label = $('<div/>').append($('<strong/>').text(language.label + ':'));
|
||||
label.append($('<span/>').addClass('esun-language-stores').text(language.store_codes.join(', ')));
|
||||
row.append(label);
|
||||
row.append($('<button/>', {
|
||||
type: 'button',
|
||||
disabled: isSourceLanguage,
|
||||
title: isSourceLanguage ? $t('This language matches the source language.') : ''
|
||||
}).addClass('action-secondary').text($t('Translate')).on('click', function () {
|
||||
if (!isSourceLanguage) {
|
||||
openEditor(language);
|
||||
}
|
||||
}));
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
function openEditor(language) {
|
||||
if (!entityId()) {
|
||||
showError($t('Enter a valid content ID first.'));
|
||||
return;
|
||||
}
|
||||
|
||||
currentLanguage = language;
|
||||
$('#esun-editor-title').text(language.label + ' - ' + language.store_codes.join(', '));
|
||||
$('#esun-editor-fields').text($t('Loading...'));
|
||||
|
||||
$.ajax({
|
||||
url: config.urls.fields,
|
||||
type: 'GET',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
entity_type: config.entityType,
|
||||
entity_id: entityId(),
|
||||
language: language.label
|
||||
}
|
||||
}).done(function (response) {
|
||||
if (!response.success) {
|
||||
showError(response.message || $t('Unable to load translatable fields.'));
|
||||
return;
|
||||
}
|
||||
currentFields = response.fields || [];
|
||||
renderFields(currentFields, {});
|
||||
editor.modal('openModal');
|
||||
}).fail(function () {
|
||||
showError($t('Unable to load translatable fields.'));
|
||||
});
|
||||
}
|
||||
|
||||
function renderFields(fields, translations, sourceOverrides) {
|
||||
var container = $('#esun-editor-fields').empty();
|
||||
sourceOverrides = sourceOverrides || {};
|
||||
|
||||
if (!fields.length) {
|
||||
container.text($t('No translatable fields are available.'));
|
||||
return;
|
||||
}
|
||||
|
||||
fields.forEach(function (field) {
|
||||
var value = translations[field.code] !== undefined ? translations[field.code] : field.target_value;
|
||||
var sourceValue = sourceOverrides[field.code] !== undefined ? sourceOverrides[field.code] : field.source_value;
|
||||
var row = $('<div/>').addClass('esun-field').attr('data-code', field.code);
|
||||
row.append($('<div/>').addClass('esun-field-label').text(field.label + ' (' + field.code + ')'));
|
||||
var columns = $('<div/>').addClass('esun-field-columns');
|
||||
columns.append($('<textarea/>').addClass('admin__control-textarea esun-source-value').val(sourceValue));
|
||||
columns.append($('<textarea/>').addClass('admin__control-textarea esun-target-value').val(value));
|
||||
row.append(columns);
|
||||
container.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
function collectSourceOverrides() {
|
||||
var sourceOverrides = {};
|
||||
$('.esun-field').each(function () {
|
||||
sourceOverrides[$(this).data('code')] = $(this).find('.esun-source-value').val();
|
||||
});
|
||||
|
||||
return sourceOverrides;
|
||||
}
|
||||
|
||||
$('#esun-run-translate').on('click', function () {
|
||||
if (!currentLanguage) {
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceOverrides = collectSourceOverrides();
|
||||
$('#esun-run-translate').prop('disabled', true);
|
||||
$.ajax({
|
||||
url: config.urls.translate,
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
form_key: config.formKey,
|
||||
entity_type: config.entityType,
|
||||
entity_id: entityId(),
|
||||
language: currentLanguage.label,
|
||||
source_overrides: sourceOverrides
|
||||
}
|
||||
}).done(function (response) {
|
||||
if (!response.success) {
|
||||
showError(response.message || $t('Translation failed.'));
|
||||
return;
|
||||
}
|
||||
renderFields(currentFields, response.translations || {}, sourceOverrides);
|
||||
}).fail(function () {
|
||||
showError($t('Translation failed.'));
|
||||
}).always(function () {
|
||||
$('#esun-run-translate').prop('disabled', false);
|
||||
});
|
||||
});
|
||||
|
||||
$('#esun-apply-translation').on('click', function () {
|
||||
var fields = {};
|
||||
$('.esun-field').each(function () {
|
||||
fields[$(this).data('code')] = $(this).find('.esun-target-value').val();
|
||||
});
|
||||
|
||||
$('#esun-apply-translation').prop('disabled', true);
|
||||
$.ajax({
|
||||
url: config.urls.apply,
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
form_key: config.formKey,
|
||||
entity_type: config.entityType,
|
||||
entity_id: entityId(),
|
||||
language: currentLanguage.label,
|
||||
fields: fields
|
||||
}
|
||||
}).done(function (response) {
|
||||
if (!response.success) {
|
||||
showError(response.message || $t('Apply failed.'));
|
||||
return;
|
||||
}
|
||||
alert({title: $t('Esun Translation'), content: response.message || $t('Translations applied.')});
|
||||
editor.modal('closeModal');
|
||||
}).fail(function () {
|
||||
showError($t('Apply failed.'));
|
||||
}).always(function () {
|
||||
$('#esun-apply-translation').prop('disabled', false);
|
||||
});
|
||||
});
|
||||
|
||||
if (entityId()) {
|
||||
renderLanguages();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
|
||||
<settings>
|
||||
<buttons>
|
||||
<button name="esun_cms_block_translate"
|
||||
class="Esun\Translation\Block\Adminhtml\Cms\Block\Edit\Button\Translate"/>
|
||||
</buttons>
|
||||
</settings>
|
||||
</form>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
|
||||
<settings>
|
||||
<buttons>
|
||||
<button name="esun_cms_page_translate"
|
||||
class="Esun\Translation\Block\Adminhtml\Cms\Page\Edit\Button\Translate"/>
|
||||
</buttons>
|
||||
</settings>
|
||||
</form>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
|
||||
<settings>
|
||||
<buttons>
|
||||
<button name="esun_product_translate"
|
||||
class="Esun\Translation\Block\Adminhtml\Product\Edit\Button\Translate"/>
|
||||
</buttons>
|
||||
</settings>
|
||||
</form>
|
||||
Reference in New Issue
Block a user