This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Api;
interface TranslationProviderInterface
{
/**
* @param array<string, array{value:string,is_html:bool}> $fields
* @return array<string, string>
*/
public function translate(array $fields, string $sourceLanguage, string $targetLanguage): array;
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Category\Edit\Button;
use Magento\Catalog\Block\Adminhtml\Category\AbstractCategory;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class Translate extends AbstractCategory implements ButtonProviderInterface
{
private function getCurrentStoreFromRequest(): int
{
$store = (int)$this->getRequest()->getParam('store', 0);
if ($store <= 0) {
$store = (int)$this->getRequest()->getParam('store_id', 0);
}
return $store > 0 ? $store : 0;
}
public function getButtonData(): array
{
$category = $this->getCategory();
if (!$category || !$category->getId()) {
return [];
}
$config = [
'entityType' => 'category',
'entityId' => (int)$category->getId(),
'sourceStoreId' => $this->getCurrentStoreFromRequest(),
'storesUrl' => $this->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $this->getUrl('localetranslate/translation/fields'),
'applyUrl' => $this->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $this->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
return [
'label' => __('Translate'),
'class' => 'action-secondary',
'on_click' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 35,
];
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Cms\Block\Edit\Button;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class Translate extends \Magento\Backend\Block\Widget\Container implements ButtonProviderInterface
{
private function getCurrentStoreFromRequest(): int
{
$store = (int)$this->getRequest()->getParam('store', 0);
if ($store <= 0) {
$store = (int)$this->getRequest()->getParam('store_id', 0);
}
return $store > 0 ? $store : 0;
}
public function getButtonData(): array
{
$blockId = (int)$this->getRequest()->getParam('block_id');
if ($blockId <= 0) {
return [];
}
$config = [
'entityType' => 'cms_block',
'entityId' => $blockId,
'sourceStoreId' => $this->getCurrentStoreFromRequest(),
'storesUrl' => $this->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $this->getUrl('localetranslate/translation/fields'),
'applyUrl' => $this->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $this->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
return [
'label' => __('Translate'),
'class' => 'action-secondary',
'on_click' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 30,
];
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Cms\Page\Edit\Button;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class Translate extends \Magento\Backend\Block\Widget\Container implements ButtonProviderInterface
{
private function getCurrentStoreFromRequest(): int
{
$store = (int)$this->getRequest()->getParam('store', 0);
if ($store <= 0) {
$store = (int)$this->getRequest()->getParam('store_id', 0);
}
return $store > 0 ? $store : 0;
}
public function getButtonData(): array
{
$pageId = (int)$this->getRequest()->getParam('page_id');
if ($pageId <= 0) {
return [];
}
$config = [
'entityType' => 'cms_page',
'entityId' => $pageId,
'sourceStoreId' => $this->getCurrentStoreFromRequest(),
'storesUrl' => $this->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $this->getUrl('localetranslate/translation/fields'),
'applyUrl' => $this->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $this->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
return [
'label' => __('Translate'),
'class' => 'action-secondary',
'on_click' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 30,
];
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Log;
use Magento\Backend\Block\Widget\Context;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class ClearAllButton implements ButtonProviderInterface
{
public function __construct(private readonly Context $context)
{
}
public function getButtonData(): array
{
$message = __('Clear all Translation API Log records? This action cannot be undone.');
$url = $this->context->getUrlBuilder()->getUrl('localetranslate/log/clearAll');
return [
'label' => __('Clear All Logs'),
'class' => 'delete',
'on_click' => 'deleteConfirm('
. json_encode((string)$message, JSON_HEX_APOS | JSON_HEX_QUOT)
. ', '
. json_encode($url, JSON_HEX_APOS | JSON_HEX_QUOT)
. ', {"data": {}})',
'sort_order' => 10,
'aclResource' => 'Esun_MultiLocaleTranslation::translation_log_delete',
];
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Product\Edit\Button;
use Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic;
class Translate extends Generic
{
private function getCurrentStoreFromRequest(): int
{
$store = (int)$this->context->getRequestParam('store', 0);
return $store > 0 ? $store : 0;
}
public function getButtonData(): array
{
$product = $this->getProduct();
if (!$product || !$product->getId()) {
return [];
}
$config = [
'entityType' => 'product',
'entityId' => (int)$product->getId(),
'sourceStoreId' => $this->getCurrentStoreFromRequest(),
'storesUrl' => $this->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $this->getUrl('localetranslate/translation/fields'),
'applyUrl' => $this->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $this->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
return [
'label' => __('Translate'),
'class' => 'action-secondary',
'on_click' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 35,
];
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Queue;
use Magento\Backend\Block\Widget\Context;
use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface;
class ClearAllButton implements ButtonProviderInterface
{
public function __construct(private readonly Context $context)
{
}
public function getButtonData(): array
{
$message = __(
'Clear all translation queue records? Pending jobs will be removed. A job already being processed may still finish and write its translation.'
);
$url = $this->context->getUrlBuilder()->getUrl('localetranslate/queue/clearAll');
return [
'label' => __('Clear All Queue'),
'class' => 'delete',
'on_click' => 'deleteConfirm('
. json_encode((string)$message, JSON_HEX_APOS | JSON_HEX_QUOT)
. ', '
. json_encode($url, JSON_HEX_APOS | JSON_HEX_QUOT)
. ', {"data": {}})',
'sort_order' => 10,
'aclResource' => 'Esun_MultiLocaleTranslation::queue_delete',
];
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\ProviderConfig;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\FormKey;
class Form extends Template
{
public function __construct(
Context $context,
private readonly StoreViewProvider $storeViewProvider,
private readonly ProviderConfig $providerConfig,
private readonly SelectionRegistry $selectionRegistry,
private readonly FormKey $formKeyService,
array $data = []
) {
parent::__construct($context, $data);
}
public function getSelection(): ?array
{
return $this->selectionRegistry->get($this->getToken());
}
public function getToken(): string
{
return (string)$this->getRequest()->getParam('token');
}
public function getStoreGroups(): array
{
return $this->storeViewProvider->getStoreViewGroups();
}
public function getProviders(): array
{
return $this->providerConfig->getEnabledOptions();
}
public function getDefaultProvider(): string
{
return $this->providerConfig->getDefaultProvider();
}
public function getSubmitUrl(): string
{
return $this->getUrl('localetranslate/queue/add');
}
public function getQueueUrl(): string
{
return $this->getUrl('localetranslate/queue/index');
}
public function getFormKeyValue(): string
{
return $this->formKeyService->getFormKey();
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Block\Adminhtml\Translate;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Data\Form\FormKey;
class Index extends Template
{
public function __construct(
Context $context,
private readonly StoreViewProvider $storeViewProvider,
private readonly FormKey $formKeyProvider,
array $data = []
) {
parent::__construct($context, $data);
}
public function getEntityType(): string
{
return (string)$this->getRequest()->getParam('entity_type', 'product');
}
public function getEntityId(): int
{
return (int)$this->getRequest()->getParam('entity_id', 0);
}
public function getSourceStoreId(): int
{
$storeId = (int)$this->getRequest()->getParam('source_store_id', 0);
return $storeId > 0 ? $storeId : 0;
}
public function getSourceStoreIdName(): string
{
$sourceStoreId = $this->getSourceStoreId();
if ($sourceStoreId <= 0) {
return __('Default Store View')->render();
}
foreach ($this->getStoreOptions() as $storeOption) {
if ((int)$storeOption['store_id'] === $sourceStoreId) {
return (string)$storeOption['label'];
}
}
return __('Default Value (Store ID: %1)', $sourceStoreId)->render();
}
public function getStoreOptions(): array
{
return $this->storeViewProvider->getStoreViewOptions();
}
public function getFieldsUrl(): string
{
return $this->getUrl('localetranslate/translation/fields');
}
public function getApplyUrl(): string
{
return $this->getUrl('localetranslate/translation/apply');
}
public function getFormKeyValue(): string
{
return $this->formKeyProvider->getFormKey();
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Log;
use Esun\MultiLocaleTranslation\Model\LogCleaner;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Redirect;
class ClearAll extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation_log_delete';
public function __construct(
Action\Context $context,
private readonly LogCleaner $logCleaner
) {
parent::__construct($context);
}
public function execute(): Redirect
{
try {
$deleted = $this->logCleaner->clearAll();
$this->messageManager->addSuccessMessage(
__('%1 Translation API Log record(s) cleared.', $deleted)
);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Log;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation_log';
public function __construct(Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute(): Page
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_MultiLocaleTranslation::translation_log');
$page->getConfig()->getTitle()->prepend(__('Translation API Log'));
return $page;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Log;
use Esun\MultiLocaleTranslation\Model\ResourceModel\Log\CollectionFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Ui\Component\MassAction\Filter;
class MassDelete extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation_log_delete';
public function __construct(
Action\Context $context,
private readonly Filter $filter,
private readonly CollectionFactory $collectionFactory
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$deleted = 0;
foreach ($collection as $log) {
$log->delete();
$deleted++;
}
$this->messageManager->addSuccessMessage(
__('A total of %1 translation log(s) have been deleted.', $deleted)
);
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\QueueManager;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
class Add extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(
Action\Context $context,
private readonly QueueManager $queueManager,
private readonly SelectionRegistry $selectionRegistry
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$token = (string)$this->getRequest()->getParam('token');
try {
$selection = $this->selectionRegistry->get($token);
$entityType = $selection['entity_type'] ?? (string)$this->getRequest()->getParam('entity_type');
$this->assertBlogPermission((string)$entityType);
$entityIds = $selection['entity_ids'] ?? $this->parseIds(
(string)$this->getRequest()->getParam('entity_ids')
);
$result = $this->queueManager->enqueue(
$entityType,
$entityIds,
(int)$this->getRequest()->getParam('source_store_id'),
(array)$this->getRequest()->getParam('target_store_ids', []),
(string)$this->getRequest()->getParam('provider')
);
$this->selectionRegistry->clear($token);
$this->messageManager->addSuccessMessage(
__('%1 task(s) added to the translation queue. %2 duplicate active task(s) skipped.',
$result['created'],
$result['skipped'])
);
return $this->resultRedirectFactory->create()->setPath('*/*/index', [
'batch_id' => $result['batch_id'],
]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
return $this->resultRedirectFactory->create()->setPath('*/*/new', ['token' => $token]);
}
}
/** @return int[] */
private function parseIds(string $value): array
{
$parts = preg_split('/[^0-9]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
return array_values(array_unique(array_map('intval', $parts ?: [])));
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\QueueManager;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Redirect;
class ClearAll extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_delete';
public function __construct(
Action\Context $context,
private readonly QueueManager $queueManager
) {
parent::__construct($context);
}
public function execute(): Redirect
{
try {
$result = $this->queueManager->clearAll();
$this->messageManager->addSuccessMessage(
__('%1 translation queue task(s) cleared.', $result['deleted'])
);
if ($result['processing'] > 0) {
$this->messageManager->addWarningMessage(
__('%1 task(s) were already processing and may still finish.', $result['processing'])
);
}
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
}
return $this->resultRedirectFactory->create()->setPath('*/*/index');
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation_queue';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute(): Page
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_MultiLocaleTranslation::translation_queue');
$page->getConfig()->getTitle()->prepend(__('Translation Queue'));
return $page;
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\ResourceModel\Queue\CollectionFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Ui\Component\MassAction\Filter;
class MassDelete extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_delete';
public function __construct(
Action\Context $context,
private readonly Filter $filter,
private readonly CollectionFactory $collectionFactory
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$deleted = 0;
$skipped = 0;
foreach ($collection as $task) {
if ($task->getData('status') === 'processing') {
$skipped++;
continue;
}
$task->delete();
$deleted++;
}
$this->messageManager->addSuccessMessage(__('%1 queue task(s) deleted.', $deleted));
if ($skipped > 0) {
$this->messageManager->addWarningMessage(__('%1 processing task(s) were not deleted.', $skipped));
}
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\ResourceModel\Queue\CollectionFactory;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Ui\Component\MassAction\Filter;
class MassRetry extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_retry';
public function __construct(
Action\Context $context,
private readonly Filter $filter,
private readonly CollectionFactory $collectionFactory
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$collection = $this->filter->getCollection($this->collectionFactory->create());
$retried = 0;
foreach ($collection as $task) {
if ($task->getData('status') !== 'failed') {
continue;
}
$task->setData('status', 'pending');
$task->setData('error_message', null);
$task->setData('started_at', null);
$task->setData('finished_at', null);
$task->save();
$retried++;
}
$this->messageManager->addSuccessMessage(__('%1 failed task(s) returned to the queue.', $retried));
return $this->resultRedirectFactory->create()->setPath('*/*/');
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Magento\Backend\App\Action;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class NewAction extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(Action\Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute(): Page
{
$page = $this->pageFactory->create();
$page->setActiveMenu('Esun_MultiLocaleTranslation::batch_translation');
$page->getConfig()->getTitle()->prepend(__('Batch Translation'));
return $page;
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Cms\Model\ResourceModel\Block\CollectionFactory as BlockCollectionFactory;
use Magento\Cms\Model\ResourceModel\Page\CollectionFactory as PageCollectionFactory;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Ui\Component\MassAction\Filter;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory as BlogPostCollectionFactory;
class Prepare extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(
Action\Context $context,
private readonly Filter $filter,
private readonly ProductCollectionFactory $productCollectionFactory,
private readonly PageCollectionFactory $pageCollectionFactory,
private readonly BlockCollectionFactory $blockCollectionFactory,
private readonly BlogPostCollectionFactory $blogPostCollectionFactory,
private readonly SelectionRegistry $selectionRegistry
) {
parent::__construct($context);
}
public function execute(): Redirect
{
try {
$entityType = (string)$this->getRequest()->getParam('entity_type');
$this->assertBlogPermission($entityType);
$collection = $this->collection($entityType);
$selected = $this->filter->getCollection($collection)->getAllIds();
if ($selected === []) {
throw new \InvalidArgumentException((string)__('Select at least one item.'));
}
$token = $this->selectionRegistry->save($entityType, array_map('intval', $selected));
return $this->resultRedirectFactory->create()->setPath('*/*/new', ['token' => $token]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
return $this->resultRedirectFactory->create()->setPath('*/*/new');
}
}
private function collection(string $entityType): AbstractDb
{
return match ($entityType) {
'product' => $this->productCollectionFactory->create(),
'cms_page' => $this->pageCollectionFactory->create(),
'cms_block' => $this->blockCollectionFactory->create(),
'blog_post' => $this->blogPostCollectionFactory->create(),
default => throw new \InvalidArgumentException((string)__('Unsupported batch entity type.')),
};
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Redirect;
class PrepareCategories extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(
Action\Context $context,
private readonly SelectionRegistry $selectionRegistry
) {
parent::__construct($context);
}
public function execute(): Redirect
{
try {
$categoryIds = $this->parseIds((string)$this->getRequest()->getParam('entity_ids'));
if ($categoryIds === []) {
throw new \InvalidArgumentException((string)__('Select at least one category.'));
}
$token = $this->selectionRegistry->save('category', $categoryIds);
return $this->resultRedirectFactory->create()->setPath('*/*/new', ['token' => $token]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
return $this->resultRedirectFactory->create()->setPath('catalog/category/index');
}
}
/** @return int[] */
private function parseIds(string $value): array
{
$parts = preg_split('/[^0-9]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
return array_values(array_unique(array_filter(array_map('intval', $parts ?: []))));
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Magento\Backend\App\Action;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Redirect;
class PrepareWikiCategories extends Action implements HttpPostActionInterface
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(
Action\Context $context,
private readonly SelectionRegistry $selectionRegistry
) {
parent::__construct($context);
}
public function execute(): Redirect
{
try {
if (!$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
$categoryIds = array_values(array_unique(array_filter(array_map(
'intval',
(array)$this->getRequest()->getParam('entity_ids', [])
))));
if ($categoryIds === []) {
throw new \InvalidArgumentException((string)__('Select at least one Wiki category.'));
}
$token = $this->selectionRegistry->save('wiki_category', $categoryIds);
return $this->resultRedirectFactory->create()->setPath('*/*/new', ['token' => $token]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
return $this->resultRedirectFactory->create()->setPath('esun_wiki/category/index');
}
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translate;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
class Index extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation';
public function __construct(Context $context, private readonly PageFactory $pageFactory)
{
parent::__construct($context);
}
public function execute(): Page
{
$resultPage = $this->pageFactory->create();
$resultPage->getConfig()->getTitle()->prepend(__('Locale Translate'));
return $resultPage;
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\EntityPool;
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 = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly EntityPool $entityPool
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
try {
$entityType = (string)$this->getRequest()->getParam('entity_type', '');
$entityId = (int)$this->getRequest()->getParam('entity_id');
$targetStoreId = (int)$this->getRequest()->getParam('target_store_id');
$sourceStoreId = (int)$this->getRequest()->getParam('source_store_id');
$fields = $this->getRequest()->getParam('fields', []);
$useDefault = $this->getRequest()->getParam('use_default', []);
if ($entityType === '' || $entityId <= 0 || $targetStoreId <= 0
|| !is_array($fields) || !is_array($useDefault)
) {
throw new \InvalidArgumentException(__('Invalid request.'));
}
if ($sourceStoreId > 0 && $sourceStoreId === $targetStoreId) {
throw new \InvalidArgumentException(__('Target store view cannot be same as source store view.'));
}
$this->assertBlogPermission($entityType);
$entity = $this->entityPool->get($entityType);
$entity->apply($entityId, $targetStoreId, $fields, $useDefault);
return $result->setData([
'success' => true,
'message' => __('Translation saved.')
]);
} catch (\Throwable $exception) {
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}
@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\LocaleResolver;
use Esun\MultiLocaleTranslation\Model\ProviderPool;
use Esun\MultiLocaleTranslation\Model\TranslationLogger;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
class AutoTranslate extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly ProviderPool $providerPool,
private readonly LocaleResolver $localeResolver,
private readonly TranslationLogger $translationLogger
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
$providerCode = (string)$this->getRequest()->getParam('provider', 'deepl');
$entityType = (string)$this->getRequest()->getParam('entity_type');
$entityId = (int)$this->getRequest()->getParam('entity_id');
$sourceStoreId = (int)$this->getRequest()->getParam('source_store_id');
$targetStoreId = (int)$this->getRequest()->getParam('target_store_id');
$fields = $this->getRequest()->getParam('fields', []);
$sourceLanguage = '';
$targetLanguage = '';
try {
if ($targetStoreId <= 0 || !is_array($fields) || $fields === []) {
throw new \InvalidArgumentException((string)__('Invalid automatic translation request.'));
}
if ($sourceStoreId > 0 && $sourceStoreId === $targetStoreId) {
throw new \InvalidArgumentException((string)__('Target store view cannot be same as source store view.'));
}
$this->assertBlogPermission($entityType);
$sourceLanguage = $this->localeResolver->getLanguageCode(
$sourceStoreId,
$providerCode,
false
);
$targetLanguage = $this->localeResolver->getLanguageCode(
$targetStoreId,
$providerCode,
true
);
$translations = $sourceLanguage !== '' && $sourceLanguage === $targetLanguage
? $this->copyFieldValues($fields)
: $this->providerPool->get($providerCode)->translate(
$fields,
$sourceLanguage,
$targetLanguage
);
try {
$this->translationLogger->logSuccess(
$providerCode,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$fields,
$translations,
$sourceLanguage === $targetLanguage ? 'copied' : 'success'
);
} catch (\Throwable) {
// Logging must never change a successful translation response.
}
return $result->setData([
'success' => true,
'provider' => $providerCode,
'source_language' => $sourceLanguage !== '' ? $sourceLanguage : 'auto',
'target_language' => $targetLanguage,
'translations' => $translations,
]);
} catch (\Throwable $exception) {
try {
$this->translationLogger->logFailure(
$providerCode,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
is_array($fields) ? $fields : [],
$exception->getMessage()
);
} catch (\Throwable) {
// Logging must never hide the original translation error.
}
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
/**
* @param array<string, mixed> $fields
* @return array<string, string>
*/
private function copyFieldValues(array $fields): array
{
$result = [];
foreach ($fields as $code => $field) {
if (!is_array($field) || !array_key_exists('value', $field)) {
continue;
}
$result[(string)$code] = (string)$field['value'];
}
return $result;
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\EntityPool;
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 = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly EntityPool $entityPool
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
try {
$entityType = (string)$this->getRequest()->getParam('entity_type', '');
$entityId = (int)$this->getRequest()->getParam('entity_id');
$targetStoreId = (int)$this->getRequest()->getParam('target_store_id');
$sourceStoreId = (int)$this->getRequest()->getParam('source_store_id');
if ($entityType === '' || $entityId <= 0 || $targetStoreId <= 0) {
throw new \InvalidArgumentException(__('Invalid request.'));
}
$this->assertBlogPermission($entityType);
$entity = $this->entityPool->get($entityType);
$fields = $entity->getFields($entityId, $sourceStoreId, $targetStoreId);
return $result->setData([
'success' => true,
'fields' => $fields
]);
} catch (\Throwable $exception) {
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Esun\MultiLocaleTranslation\Model\ProviderConfig;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
class Stores extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly StoreViewProvider $storeViewProvider,
private readonly ProviderConfig $providerConfig
) {
parent::__construct($context);
}
public function execute(): Json
{
return $this->jsonFactory->create()->setData([
'success' => true,
'stores' => $this->storeViewProvider->getStoreViewOptions(),
'providers' => $this->providerConfig->getEnabledOptions(),
'default_provider' => $this->providerConfig->getDefaultProvider(),
]);
}
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
class BlogPostFields
{
public const FIELDS = [
'name' => ['label' => 'Post Name', 'is_html' => false],
'short_description' => ['label' => 'Short Description', 'is_html' => true],
'post_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 static function codes(): array
{
return array_keys(self::FIELDS);
}
public static function baseValue(string $field, mixed $value): string
{
$value = is_string($value) ? $value : (string)($value ?? '');
if (!in_array($field, ['meta_title', 'meta_keywords', 'meta_description'], true)) {
return $value;
}
$decoded = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
return $value;
}
return (string)($decoded[0] ?? $decoded['0'] ?? '');
}
}
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\Blog\Model\Post;
class BlogPostTranslationApplier
{
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function apply(Post $post): void
{
if (!$this->isFrontend() || !$post->getId()) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$translations = $this->translationRepository->getTranslations(
(int)$post->getId(),
$storeId,
CmsTranslationRepository::ENTITY_BLOG_POST,
BlogPostFields::codes()
);
$this->applyValues($post, $translations);
}
/** @param Post[] $posts */
public function applyMany(array $posts): void
{
if (!$this->isFrontend() || $posts === []) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$postIds = [];
foreach ($posts as $post) {
if ($post instanceof Post && $post->getId()) {
$postIds[] = (int)$post->getId();
}
}
$translations = $this->translationRepository->getTranslationsForEntities(
$postIds,
$storeId,
CmsTranslationRepository::ENTITY_BLOG_POST,
BlogPostFields::codes()
);
foreach ($posts as $post) {
if (!$post instanceof Post || !$post->getId()) {
continue;
}
$this->applyValues($post, $translations[(int)$post->getId()] ?? []);
}
}
private function applyValues(Post $post, array $translations): void
{
foreach (BlogPostFields::codes() as $field) {
if (array_key_exists($field, $translations)) {
$post->setData($field, $translations[$field]);
}
}
}
private function isFrontend(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
class CmsTranslationRepository
{
public const ENTITY_PAGE = 'page';
public const ENTITY_BLOCK = 'block';
public const ENTITY_BLOG_POST = 'blog_post';
public const ENTITY_WIKI_CATEGORY = 'wiki_category';
public const ENTITY_WIKI_HOMEPAGE = 'wiki_homepage';
private const TABLE_NAME = 'esun_localetranslation_cms';
public function __construct(private readonly ResourceConnection $resource)
{
}
public function getTranslations(int $entityId, int $storeId, string $entityType, array $fields = []): array
{
if (!$this->isSupportedType($entityType) || $entityId <= 0 || $storeId <= 0) {
return [];
}
$connection = $this->getConnection();
$select = $connection->select()
->from(
$this->resource->getTableName(self::TABLE_NAME),
['field_name', 'translated_value']
)->where('entity_type = ?', $entityType)
->where('entity_id = ?', $entityId)
->where('store_id = ?', $storeId);
if ($fields !== []) {
$select->where('field_name IN (?)', $fields);
}
return (array)$connection->fetchPairs($select);
}
public function saveTranslations(int $entityId, int $storeId, string $entityType, array $translations): void
{
if (!$this->isSupportedType($entityType) || $entityId <= 0 || $storeId <= 0) {
return;
}
$connection = $this->getConnection();
$tableName = $this->resource->getTableName(self::TABLE_NAME);
$now = date('Y-m-d H:i:s');
$rows = [];
foreach ($translations as $field => $value) {
if (!$field) {
continue;
}
$rows[] = [
'entity_type' => $entityType,
'entity_id' => $entityId,
'store_id' => $storeId,
'field_name' => (string)$field,
'translated_value' => is_string($value) ? $value : (string)$value,
'created_at' => $now,
'updated_at' => $now,
];
}
if ($rows === []) {
return;
}
$connection->insertOnDuplicate(
$tableName,
$rows,
['translated_value', 'updated_at']
);
}
/** @return array<int, array<string, string>> */
public function getTranslationsForEntities(
array $entityIds,
int $storeId,
string $entityType,
array $fields = []
): array {
$entityIds = array_values(array_unique(array_filter(array_map('intval', $entityIds))));
if (!$this->isSupportedType($entityType) || $entityIds === [] || $storeId <= 0) {
return [];
}
$select = $this->getConnection()->select()
->from(
$this->resource->getTableName(self::TABLE_NAME),
['entity_id', 'field_name', 'translated_value']
)->where('entity_type = ?', $entityType)
->where('entity_id IN (?)', $entityIds)
->where('store_id = ?', $storeId);
if ($fields !== []) {
$select->where('field_name IN (?)', $fields);
}
$result = [];
foreach ($this->getConnection()->fetchAll($select) as $row) {
$result[(int)$row['entity_id']][(string)$row['field_name']] = (string)$row['translated_value'];
}
return $result;
}
/** @return array<int, int[]> */
public function getTranslatedStoreIdsForEntities(array $entityIds, string $entityType): array
{
$entityIds = array_values(array_unique(array_filter(array_map('intval', $entityIds))));
if (!$this->isSupportedType($entityType) || $entityIds === []) {
return [];
}
$select = $this->getConnection()->select()
->from(
$this->resource->getTableName(self::TABLE_NAME),
['entity_id', 'store_id']
)->where('entity_type = ?', $entityType)
->where('entity_id IN (?)', $entityIds)
->group(['entity_id', 'store_id']);
$result = [];
foreach ($this->getConnection()->fetchAll($select) as $row) {
$result[(int)$row['entity_id']][] = (int)$row['store_id'];
}
return $result;
}
public function clearTranslations(int $entityId, int $storeId, string $entityType): void
{
if (!$this->isSupportedType($entityType) || $entityId <= 0 || $storeId <= 0) {
return;
}
$connection = $this->getConnection();
$connection->delete(
$this->resource->getTableName(self::TABLE_NAME),
[
'entity_type = ?' => $entityType,
'entity_id = ?' => $entityId,
'store_id = ?' => $storeId
]
);
}
public function clearEntityTranslations(int $entityId, string $entityType): void
{
if (!$this->isSupportedType($entityType) || $entityId <= 0) {
return;
}
$this->getConnection()->delete(
$this->resource->getTableName(self::TABLE_NAME),
[
'entity_type = ?' => $entityType,
'entity_id = ?' => $entityId,
]
);
}
public function deleteTranslations(
int $entityId,
int $storeId,
string $entityType,
array $fields
): void {
$fields = array_values(array_filter(array_map('strval', $fields)));
if (!$this->isSupportedType($entityType) || $entityId <= 0 || $storeId <= 0 || $fields === []) {
return;
}
$connection = $this->getConnection();
$connection->delete(
$this->resource->getTableName(self::TABLE_NAME),
[
'entity_type = ?' => $entityType,
'entity_id = ?' => $entityId,
'store_id = ?' => $storeId,
'field_name IN (?)' => $fields,
]
);
}
private function isSupportedType(string $entityType): bool
{
return in_array($entityType, [
self::ENTITY_PAGE,
self::ENTITY_BLOCK,
self::ENTITY_BLOG_POST,
self::ENTITY_WIKI_CATEGORY,
self::ENTITY_WIKI_HOMEPAGE,
], true);
}
private function getConnection(): AdapterInterface
{
return $this->resource->getConnection();
}
}
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Backend;
use Magento\Config\Model\Config\Backend\File;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\DriverInterface;
class ServiceAccountFile extends File
{
private const REQUIRED_FIELDS = ['type', 'project_id', 'private_key', 'client_email'];
private string $oldCredentialFile = '';
private string $credentialFileToDelete = '';
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
\Magento\Config\Model\Config\Backend\File\RequestData\RequestDataInterface $requestData,
Filesystem $filesystem,
private readonly DriverInterface $fileDriver,
?\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
?\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
parent::__construct(
$context,
$registry,
$config,
$cacheTypeList,
$uploaderFactory,
$requestData,
$filesystem,
$resource,
$resourceCollection,
$data
);
$this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$this->_maxFileSize = 64;
}
public function beforeSave(): static
{
$this->oldCredentialFile = basename((string)$this->getOldValue());
$file = $this->getFileData();
$deleteRequested = is_array($this->getValue()) && !empty($this->getValue()['delete']);
if ($file !== []) {
$this->validateServiceAccountFile((string)$file['tmp_name']);
}
parent::beforeSave();
$newFile = basename((string)$this->getValue());
if ($file !== [] && $newFile !== '') {
$this->fileDriver->changePermissions($this->getCredentialPath($newFile), 0600);
}
if ($this->oldCredentialFile !== ''
&& ($deleteRequested || ($newFile !== '' && $newFile !== $this->oldCredentialFile))
) {
$this->credentialFileToDelete = $this->oldCredentialFile;
}
return $this;
}
public function afterSave(): static
{
parent::afterSave();
if ($this->credentialFileToDelete !== '') {
$oldPath = $this->getCredentialPath($this->credentialFileToDelete);
if ($this->fileDriver->isExists($oldPath)) {
$this->fileDriver->deleteFile($oldPath);
}
}
return $this;
}
protected function _getAllowedExtensions(): array
{
return ['json'];
}
private function validateServiceAccountFile(string $path): void
{
try {
$credentials = json_decode(
$this->fileDriver->fileGetContents($path),
true,
32,
JSON_THROW_ON_ERROR
);
} catch (\Throwable $exception) {
throw new LocalizedException(__('The service account JSON file is invalid.'));
}
if (!is_array($credentials) || ($credentials['type'] ?? '') !== 'service_account') {
throw new LocalizedException(__('The uploaded JSON is not a Google service account key.'));
}
foreach (self::REQUIRED_FIELDS as $field) {
if (!is_string($credentials[$field] ?? null) || trim($credentials[$field]) === '') {
throw new LocalizedException(__('The service account JSON is missing "%1".', $field));
}
}
$privateKey = openssl_pkey_get_private($credentials['private_key']);
if ($privateKey === false) {
throw new LocalizedException(__('The service account private key is invalid.'));
}
}
private function getCredentialPath(string $filename): string
{
return $this->_mediaDirectory->getAbsolutePath(
'esun/multilocale_translation/google/' . basename($filename)
);
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config;
use Magento\Framework\App\Config\ScopeConfigInterface;
class SkippedFields
{
private const XML_PATH = 'esun_multilocale_translation/general/skipped_fields';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig
) {
}
public function isSkipped(string $entityType, string $field): bool
{
$value = $this->scopeConfig->getValue(self::XML_PATH);
if (!is_string($value) || trim($value) === '') {
return false;
}
$skippedFields = array_filter(array_map('trim', explode(',', $value)));
return in_array($entityType . '.' . $field, $skippedFields, true);
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class DeepLApiUrl implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
[
'value' => 'https://api-free.deepl.com/v2/translate',
'label' => 'https://api-free.deepl.com/v2/translate',
],
[
'value' => 'https://api.deepl.com/v2/translate',
'label' => 'https://api.deepl.com/v2/translate',
],
];
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class DeepLFormality implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'default', 'label' => __('Default')],
['value' => 'prefer_more', 'label' => __('Prefer formal')],
['value' => 'prefer_less', 'label' => __('Prefer informal')],
];
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class GoogleLocation implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'global', 'label' => __('Global (standard translation)')],
['value' => 'us-central1', 'label' => __('US Central 1 (required for Glossary)')],
];
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class LogStatus implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'success', 'label' => __('Success')],
['value' => 'failed', 'label' => __('Failed')],
['value' => 'copied', 'label' => __('Copied (same language)')],
];
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class QueueStatus implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'pending', 'label' => __('Pending')],
['value' => 'processing', 'label' => __('Processing')],
['value' => 'success', 'label' => __('Success')],
['value' => 'failed', 'label' => __('Failed')],
];
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class SkippedFields implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
$this->group('Category', 'category', [
'name' => 'Name',
'description' => 'Description',
'meta_title' => 'Meta Title',
'meta_keywords' => 'Meta Keywords',
'meta_description' => 'Meta Description',
]),
$this->group('Product', 'product', [
'name' => 'Name',
'description' => 'Description',
'short_description' => 'Short Description',
'meta_title' => 'Meta Title',
'meta_keyword' => 'Meta Keywords',
'meta_description' => 'Meta Description',
]),
$this->group('CMS Page', 'cms_page', [
'title' => 'Title',
'content_heading' => 'Content Heading',
'content' => 'Content',
'meta_title' => 'Meta Title',
'meta_keywords' => 'Meta Keywords',
'meta_description' => 'Meta Description',
]),
$this->group('CMS Block', 'cms_block', [
'title' => 'Title',
'content' => 'Content',
]),
$this->group('Blog Post', 'blog_post', [
'name' => 'Post Name',
'short_description' => 'Short Description',
'post_content' => 'Content',
'meta_title' => 'Meta Title',
'meta_keywords' => 'Meta Keywords',
'meta_description' => 'Meta Description',
]),
$this->group('Wiki Category', 'wiki_category', [
'title' => 'Title',
'summary' => 'Summary',
'content' => 'Content',
'meta_title' => 'Meta Title',
'meta_description' => 'Meta Description',
'meta_keywords' => 'Meta Keywords',
]),
$this->group('Wiki Homepage', 'wiki_homepage', [
'title' => 'Title',
'content' => 'Content',
'meta_title' => 'Meta Title',
'meta_description' => 'Meta Description',
'meta_keywords' => 'Meta Keywords',
]),
];
}
private function group(string $label, string $entityType, array $fields): array
{
$options = [];
foreach ($fields as $field => $fieldLabel) {
$options[] = [
'value' => $entityType . '.' . $field,
'label' => __($fieldLabel),
];
}
return ['label' => __($label), 'value' => $options];
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Magento\Framework\Data\OptionSourceInterface;
class StoreViews implements OptionSourceInterface
{
public function __construct(private readonly StoreViewProvider $storeViewProvider)
{
}
public function toOptionArray(): array
{
$options = [['value' => 0, 'label' => __('Default Store View (0)')]];
foreach ($this->storeViewProvider->getStoreViewOptions() as $store) {
$options[] = [
'value' => $store['store_id'],
'label' => sprintf(
'%s / %s (%s)',
$store['label'],
$store['website'],
$store['code']
),
];
}
return $options;
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Config\Source;
use Magento\Framework\Data\OptionSourceInterface;
class TranslationProvider implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'deepl', 'label' => __('DeepL')],
['value' => 'google', 'label' => __('Google Cloud Translation V3')],
];
}
}
@@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Mageplaza\Blog\Model\Post;
use Mageplaza\Blog\Model\PostFactory;
class BlogPostEntity implements TranslatableEntityInterface
{
public function __construct(
private readonly PostFactory $postFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$post = $this->loadPost($entityId);
$baseValues = $this->getBaseValues($post);
$sourceValues = $sourceStoreId > 0
? array_replace($baseValues, $this->getTranslations($entityId, $sourceStoreId))
: $baseValues;
$targetTranslations = $this->getTranslations($entityId, $targetStoreId);
$fields = [];
foreach (BlogPostFields::FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('blog_post', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($sourceValues[$field] ?? ''),
'target_value' => (string)($targetTranslations[$field] ?? $baseValues[$field] ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetTranslations),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$this->loadPost($entityId);
$defaultFields = [];
$translations = [];
foreach (BlogPostFields::codes() as $field) {
if ($this->skippedFields->isSkipped('blog_post', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
continue;
}
if (array_key_exists($field, $fields)) {
$translations[$field] = (string)$fields[$field];
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOG_POST,
$defaultFields
);
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOG_POST,
$translations
);
}
private function loadPost(int $entityId): Post
{
$post = $this->postFactory->create()->load($entityId);
if (!$post->getId()) {
throw NoSuchEntityException::singleField('post_id', $entityId);
}
return $post;
}
private function getBaseValues(Post $post): array
{
$values = [];
foreach (BlogPostFields::codes() as $field) {
$values[$field] = BlogPostFields::baseValue($field, $post->getData($field));
}
return $values;
}
private function getTranslations(int $entityId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$entityId,
$storeId,
CmsTranslationRepository::ENTITY_BLOG_POST,
BlogPostFields::codes()
);
}
}
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
use Magento\Catalog\Model\ResourceModel\Category as CategoryResource;
use Magento\Framework\Exception\NoSuchEntityException;
class CategoryEntity implements TranslatableEntityInterface
{
private const TRANSLATABLE_FIELDS = [
'name' => ['label' => 'Category Name', 'is_html' => false],
'description' => ['label' => 'Description', '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 CategoryFactory $categoryFactory,
private readonly CategoryResource $categoryResource,
private readonly ScopeOverriddenValue $scopeOverriddenValue,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$source = $this->getCategory($entityId, $sourceStoreId);
$target = $this->getCategory($entityId, $targetStoreId);
$fields = [];
foreach (self::TRANSLATABLE_FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('category', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($source->getData($field) ?? ''),
'target_value' => (string)($target->getData($field) ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => $targetStoreId > 0 && !$this->scopeOverriddenValue->containsValue(
CategoryInterface::class,
$target,
$field,
$targetStoreId
),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$category = $this->getCategory($entityId, $targetStoreId);
foreach (array_keys(self::TRANSLATABLE_FIELDS) as $field) {
if ($this->skippedFields->isSkipped('category', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$category->setData($field, null);
continue;
}
if (!array_key_exists($field, $fields)) {
continue;
}
$category->setData($field, (string)$fields[$field]);
}
$this->categoryResource->save($category);
}
private function getCategory(int $entityId, int $storeId): CategoryInterface
{
/** @var Category $category */
$category = $this->categoryFactory->create();
$category->setStoreId(max(0, $storeId))->load($entityId);
if (!$category->getId()) {
throw NoSuchEntityException::singleField('id', $entityId);
}
return $category;
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Cms\Model\Block;
use Magento\Cms\Model\BlockFactory;
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 BlockFactory $blockFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$source = $this->loadBlock($entityId, $sourceStoreId);
$targetValues = $this->translationRepository->getTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOCK,
array_keys(self::FIELDS)
);
$fields = [];
foreach (self::FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('cms_block', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($source->getData($field) ?? ''),
'target_value' => (string)($targetValues[$field] ?? $source->getData($field) ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetValues),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$defaultFields = [];
foreach (array_keys(array_filter($useDefault)) as $field) {
if (isset(self::FIELDS[$field]) && !$this->skippedFields->isSkipped('cms_block', $field)) {
$defaultFields[] = $field;
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOCK,
$defaultFields
);
$fields = array_diff_key($fields, array_flip($defaultFields));
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOCK,
$this->filterFields($fields)
);
}
private function loadBlock(int $entityId, int $storeId): Block
{
$block = $this->blockFactory->create();
$block->setStoreId($storeId > 0 ? $storeId : 0)->load($entityId);
return $block;
}
private function filterFields(array $fields): array
{
$result = [];
foreach (array_keys(self::FIELDS) as $field) {
if ($this->skippedFields->isSkipped('cms_block', $field)
|| !array_key_exists($field, $fields)
) {
continue;
}
$result[$field] = (string)$fields[$field];
}
return $result;
}
}
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
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 PageFactory $pageFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$source = $this->loadPage($entityId, $sourceStoreId);
$targetValues = $this->translationRepository->getTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_PAGE,
array_keys(self::FIELDS)
);
$fields = [];
foreach (self::FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('cms_page', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($source->getData($field) ?? ''),
'target_value' => (string)($targetValues[$field] ?? $source->getData($field) ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetValues),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$defaultFields = [];
foreach (array_keys(array_filter($useDefault)) as $field) {
if (isset(self::FIELDS[$field]) && !$this->skippedFields->isSkipped('cms_page', $field)) {
$defaultFields[] = $field;
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_PAGE,
$defaultFields
);
$fields = array_diff_key($fields, array_flip($defaultFields));
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_PAGE,
$this->filterFields($fields)
);
}
private function loadPage(int $entityId, int $storeId): Page
{
$page = $this->pageFactory->create();
$page->setStoreId($storeId > 0 ? $storeId : 0)->load($entityId);
return $page;
}
private function filterFields(array $fields): array
{
$result = [];
foreach (array_keys(self::FIELDS) as $field) {
if ($this->skippedFields->isSkipped('cms_page', $field)
|| !array_key_exists($field, $fields)
) {
continue;
}
$result[$field] = (string)$fields[$field];
}
return $result;
}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
class ProductEntity implements TranslatableEntityInterface
{
private const TRANSLATABLE_FIELDS = [
'name' => ['label' => 'Name', 'is_html' => false],
'description' => ['label' => 'Description', 'is_html' => true],
'short_description' => ['label' => 'Short Description', 'is_html' => true],
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
'meta_keyword' => ['label' => 'Meta Keywords', 'is_html' => false],
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
];
public function __construct(
private readonly ProductRepositoryInterface $productRepository,
private readonly ScopeOverriddenValue $scopeOverriddenValue,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$source = $this->getProduct($entityId, $sourceStoreId);
$target = $this->getProduct($entityId, $targetStoreId);
$fields = [];
foreach (self::TRANSLATABLE_FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('product', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($source->getData($field) ?? ''),
'target_value' => (string)($target->getData($field) ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => $targetStoreId > 0 && !$this->scopeOverriddenValue->containsValue(
ProductInterface::class,
$target,
$field,
$targetStoreId
),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$product = $this->getProduct($entityId, $targetStoreId, true);
foreach (array_keys(self::TRANSLATABLE_FIELDS) as $field) {
if ($this->skippedFields->isSkipped('product', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$product->setData($field, null);
continue;
}
if (!array_key_exists($field, $fields)) {
continue;
}
$product->setData($field, (string)$fields[$field]);
}
$this->productRepository->save($product);
}
private function getProduct(int $entityId, int $storeId, bool $forceReload = false): ProductInterface
{
$storeId = $storeId > 0 ? $storeId : null;
$product = $this->productRepository->getById($entityId, true, $storeId, $forceReload);
return $product;
}
}
@@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Esun\MultiLocaleTranslation\Model\WikiFields;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\CategoryFactory;
use Magento\Framework\Exception\NoSuchEntityException;
class WikiCategoryEntity implements TranslatableEntityInterface
{
public function __construct(
private readonly CategoryFactory $categoryFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$category = $this->loadCategory($entityId);
$baseValues = $this->getBaseValues($category);
$sourceValues = $sourceStoreId > 0
? array_replace($baseValues, $this->getTranslations($entityId, $sourceStoreId))
: $baseValues;
$targetTranslations = $this->getTranslations($entityId, $targetStoreId);
$fields = [];
foreach (WikiFields::CATEGORY as $field => $meta) {
if ($this->skippedFields->isSkipped('wiki_category', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($sourceValues[$field] ?? ''),
'target_value' => (string)($targetTranslations[$field] ?? $baseValues[$field] ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetTranslations),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$this->loadCategory($entityId);
$defaultFields = [];
$translations = [];
foreach (WikiFields::categoryCodes() as $field) {
if ($this->skippedFields->isSkipped('wiki_category', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
} elseif (array_key_exists($field, $fields)) {
$translations[$field] = (string)$fields[$field];
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$defaultFields
);
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$translations
);
}
private function loadCategory(int $entityId): Category
{
$category = $this->categoryFactory->create()->load($entityId);
if (!$category->getId()) {
throw NoSuchEntityException::singleField('category_id', $entityId);
}
return $category;
}
private function getBaseValues(Category $category): array
{
$values = [];
foreach (WikiFields::categoryCodes() as $field) {
$values[$field] = (string)($category->getData($field) ?? '');
}
return $values;
}
private function getTranslations(int $entityId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$entityId,
$storeId,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
WikiFields::categoryCodes()
);
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Esun\MultiLocaleTranslation\Model\WikiFields;
use Esun\Wiki\Model\Homepage;
use Esun\Wiki\Model\ResourceModel\Homepage\CollectionFactory;
use Magento\Framework\Exception\NoSuchEntityException;
class WikiHomepageEntity implements TranslatableEntityInterface
{
public function __construct(
private readonly CollectionFactory $collectionFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$homepage = $this->loadHomepage($entityId);
$baseValues = $this->getBaseValues($homepage);
$sourceValues = $sourceStoreId > 0
? array_replace($baseValues, $this->getTranslations($entityId, $sourceStoreId))
: $baseValues;
$targetTranslations = $this->getTranslations($entityId, $targetStoreId);
$fields = [];
foreach (WikiFields::HOMEPAGE as $field => $meta) {
if ($this->skippedFields->isSkipped('wiki_homepage', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($sourceValues[$field] ?? ''),
'target_value' => (string)($targetTranslations[$field] ?? $baseValues[$field] ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetTranslations),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$this->loadHomepage($entityId);
$defaultFields = [];
$translations = [];
foreach (WikiFields::homepageCodes() as $field) {
if ($this->skippedFields->isSkipped('wiki_homepage', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
} elseif (array_key_exists($field, $fields)) {
$translations[$field] = (string)$fields[$field];
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE,
$defaultFields
);
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE,
$translations
);
}
private function loadHomepage(int $entityId): Homepage
{
$homepage = $this->collectionFactory->create()
->addFieldToFilter('homepage_id', $entityId)
->setPageSize(1)
->getFirstItem();
if (!$homepage->getId()) {
throw NoSuchEntityException::singleField('homepage_id', $entityId);
}
return $homepage;
}
private function getBaseValues(Homepage $homepage): array
{
$values = [];
foreach (WikiFields::homepageCodes() as $field) {
$values[$field] = (string)($homepage->getData($field) ?? '');
}
return $values;
}
private function getTranslations(int $entityId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$entityId,
$storeId,
CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE,
WikiFields::homepageCodes()
);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use InvalidArgumentException;
class EntityPool
{
public function __construct(private readonly array $entities = [])
{
}
public function get(string $entityType): TranslatableEntityInterface
{
if (!isset($this->entities[$entityType])) {
throw new InvalidArgumentException(sprintf('Unsupported entity type "%s".', $entityType));
}
$entity = $this->entities[$entityType];
if (!$entity instanceof TranslatableEntityInterface) {
throw new InvalidArgumentException(sprintf('Entity "%s" is misconfigured.', $entityType));
}
return $entity;
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Google;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\CurlFactory;
class AccessToken
{
private const TOKEN_URL = 'https://oauth2.googleapis.com/token';
private const SCOPE = 'https://www.googleapis.com/auth/cloud-translation';
private const CACHE_PREFIX = 'ESUN_GOOGLE_TRANSLATION_TOKEN_';
public function __construct(
private readonly Credentials $credentials,
private readonly CurlFactory $curlFactory,
private readonly CacheInterface $cache
) {
}
public function get(): string
{
$credentials = $this->credentials->get();
$cacheKey = self::CACHE_PREFIX . strtoupper(hash('sha256', $credentials['client_email']));
$cached = (string)$this->cache->load($cacheKey);
if ($cached !== '') {
return $cached;
}
$now = time();
$header = ['alg' => 'RS256', 'typ' => 'JWT'];
if (!empty($credentials['private_key_id'])) {
$header['kid'] = $credentials['private_key_id'];
}
$claims = [
'iss' => $credentials['client_email'],
'scope' => self::SCOPE,
'aud' => self::TOKEN_URL,
'iat' => $now,
'exp' => $now + 3600,
];
$unsignedJwt = $this->base64UrlEncode($this->encodeJson($header))
. '.' . $this->base64UrlEncode($this->encodeJson($claims));
$privateKey = openssl_pkey_get_private($credentials['private_key']);
$signature = '';
if ($privateKey === false
|| !openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256)
) {
throw new LocalizedException(__('Unable to sign the Google service account request.'));
}
$assertion = $unsignedJwt . '.' . $this->base64UrlEncode($signature);
$client = $this->curlFactory->create();
$client->setTimeout(30);
$client->setHeaders(['Content-Type' => 'application/x-www-form-urlencoded']);
$client->post(self::TOKEN_URL, http_build_query([
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $assertion,
], '', '&', PHP_QUERY_RFC3986));
$response = json_decode((string)$client->getBody(), true);
$token = is_array($response) ? (string)($response['access_token'] ?? '') : '';
if ($client->getStatus() < 200 || $client->getStatus() >= 300 || $token === '') {
$message = is_array($response)
? (string)($response['error_description'] ?? $response['error'] ?? '')
: '';
throw new LocalizedException(
__('Google service account authentication failed (HTTP %1): %2',
$client->getStatus(),
$message ?: 'Unknown error')
);
}
$lifetime = max(60, min(3300, (int)($response['expires_in'] ?? 3600) - 300));
$this->cache->save($token, $cacheKey, [], $lifetime);
return $token;
}
private function base64UrlEncode(string $value): string
{
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
}
private function encodeJson(array $value): string
{
return json_encode(
$value,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Google;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
class Credentials
{
private const XML_PATH_FILE = 'esun_multilocale_translation/google/credentials_file';
private ?array $credentials = null;
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly Filesystem $filesystem
) {
}
/**
* @return array<string, string>
*/
public function get(): array
{
if ($this->credentials !== null) {
return $this->credentials;
}
$filename = basename((string)$this->scopeConfig->getValue(self::XML_PATH_FILE));
if ($filename === '') {
throw new LocalizedException(__('Google service account JSON is not configured.'));
}
$directory = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR);
$relativePath = 'esun/multilocale_translation/google/' . $filename;
if (!$directory->isFile($relativePath)) {
throw new LocalizedException(__('The configured Google service account JSON file was not found.'));
}
try {
$data = json_decode($directory->readFile($relativePath), true, 32, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
throw new LocalizedException(__('The configured Google service account JSON is invalid.'));
}
if (!is_array($data)
|| ($data['type'] ?? '') !== 'service_account'
|| empty($data['project_id'])
|| empty($data['client_email'])
|| empty($data['private_key'])
) {
throw new LocalizedException(__('The configured JSON is not a valid Google service account key.'));
}
$this->credentials = array_map(
static fn (mixed $value): string => is_scalar($value) ? (string)$value : '',
$data
);
return $this->credentials;
}
}
@@ -0,0 +1,257 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Html;
class TranslatableTextExtractor
{
private const IGNORED_TAGS = ['code', 'noscript', 'script', 'style', 'svg', 'template'];
/**
* @return array<int, array{offset:int,length:int,text:string}>
*/
public function extract(string $html, int $maxFragmentBytes): array
{
$ranges = $this->findTextRanges($html);
$fragments = [];
foreach ($ranges as [$rangeOffset, $rangeLength]) {
foreach ($this->findEncodedTextRanges($html, $rangeOffset, $rangeLength) as [$offset, $length]) {
$value = substr($html, $offset, $length);
if ($value === '' || preg_match('/\S/u', $value) !== 1) {
continue;
}
preg_match('/\A(\s*)/u', $value, $leadingMatch);
preg_match('/(\s*)\z/u', $value, $trailingMatch);
$leadingBytes = strlen($leadingMatch[1] ?? '');
$trailingBytes = strlen($trailingMatch[1] ?? '');
$textLength = strlen($value) - $leadingBytes - $trailingBytes;
if ($textLength <= 0) {
continue;
}
$textOffset = $offset + $leadingBytes;
$text = substr($html, $textOffset, $textLength);
foreach ($this->splitText($text, $maxFragmentBytes) as [$partOffset, $part]) {
$fragments[] = [
'offset' => $textOffset + $partOffset,
'length' => strlen($part),
'text' => $part,
];
}
}
}
return $fragments;
}
/**
* @return array<int, array{0:int,1:int}>
*/
private function findTextRanges(string $html): array
{
$ranges = [];
$length = strlen($html);
$cursor = 0;
$textStart = 0;
$ignoredTag = null;
while ($cursor < $length) {
$tagStart = strpos($html, '<', $cursor);
if ($tagStart === false) {
break;
}
$tagEnd = $this->findTagEnd($html, $tagStart);
if ($tagEnd === null) {
$cursor = $tagStart + 1;
continue;
}
$tag = substr($html, $tagStart, $tagEnd - $tagStart);
if ($ignoredTag === null && $tagStart > $textStart) {
$ranges[] = [$textStart, $tagStart - $textStart];
}
if (preg_match('/^<\s*(\/?)\s*([a-z][a-z0-9:-]*)/i', $tag, $match) === 1) {
$isClosing = $match[1] === '/';
$tagName = strtolower($match[2]);
if ($ignoredTag === null && !$isClosing && in_array($tagName, self::IGNORED_TAGS, true)
&& !str_ends_with(rtrim($tag), '/>')
) {
$ignoredTag = $tagName;
} elseif ($ignoredTag === $tagName && $isClosing) {
$ignoredTag = null;
}
}
$cursor = $tagEnd;
$textStart = $tagEnd;
}
if ($ignoredTag === null && $textStart < $length) {
$ranges[] = [$textStart, $length - $textStart];
}
return $ranges;
}
private function findTagEnd(string $html, int $start): ?int
{
if (substr($html, $start, 4) === '<!--') {
$end = strpos($html, '-->', $start + 4);
return $end === false ? null : $end + 3;
}
if (substr($html, $start, 9) === '<![CDATA[') {
$end = strpos($html, ']]>', $start + 9);
return $end === false ? null : $end + 3;
}
if (preg_match('/\A<\s*(?:\/?\s*[a-z]|!doctype\b|\?)/i', substr($html, $start, 32)) !== 1) {
return null;
}
$length = strlen($html);
$quote = null;
for ($index = $start + 1; $index < $length; $index++) {
$character = $html[$index];
if ($quote !== null) {
if ($character === $quote) {
$quote = null;
}
continue;
}
if ($character === '"' || $character === "'") {
$quote = $character;
} elseif ($character === '>') {
return $index + 1;
}
}
return null;
}
/**
* Split a normal HTML text range again when Page Builder stores HTML tags as &lt;...&gt;.
*
* @return array<int, array{0:int,1:int}>
*/
private function findEncodedTextRanges(string $html, int $offset, int $length): array
{
$ranges = [];
$limit = $offset + $length;
$cursor = $offset;
$textStart = $offset;
$ignoredTag = null;
$foundTag = false;
while ($cursor < $limit) {
$tagStart = stripos($html, '&lt;', $cursor);
if ($tagStart === false || $tagStart >= $limit) {
break;
}
$tagEnd = $this->findEncodedTagEnd($html, $tagStart, $limit);
if ($tagEnd === null) {
$cursor = $tagStart + 4;
continue;
}
$encodedTag = substr($html, $tagStart, $tagEnd - $tagStart);
$tag = html_entity_decode($encodedTag, ENT_QUOTES | ENT_HTML5, 'UTF-8');
if (preg_match('/^<\s*(?:\/?\s*[a-z][a-z0-9:-]*|!--|!doctype\b|\?)/i', $tag) !== 1) {
$cursor = $tagStart + 4;
continue;
}
$foundTag = true;
if ($ignoredTag === null && $tagStart > $textStart) {
$ranges[] = [$textStart, $tagStart - $textStart];
}
if (preg_match('/^<\s*(\/?)\s*([a-z][a-z0-9:-]*)/i', $tag, $match) === 1) {
$isClosing = $match[1] === '/';
$tagName = strtolower($match[2]);
if ($ignoredTag === null && !$isClosing && in_array($tagName, self::IGNORED_TAGS, true)
&& !str_ends_with(rtrim($tag), '/>')
) {
$ignoredTag = $tagName;
} elseif ($ignoredTag === $tagName && $isClosing) {
$ignoredTag = null;
}
}
$cursor = $tagEnd;
$textStart = $tagEnd;
}
if (!$foundTag) {
return [[$offset, $length]];
}
if ($ignoredTag === null && $textStart < $limit) {
$ranges[] = [$textStart, $limit - $textStart];
}
return $ranges;
}
private function findEncodedTagEnd(string $html, int $start, int $limit): ?int
{
if (strncasecmp(substr($html, $start, 7), '&lt;!--', 7) === 0) {
$end = stripos($html, '--&gt;', $start + 7);
return $end === false || $end >= $limit ? null : $end + 6;
}
$quote = null;
for ($index = $start + 4; $index < $limit; $index++) {
$character = $html[$index];
if ($quote !== null) {
if ($character === $quote) {
$quote = null;
}
continue;
}
if ($character === '"' || $character === "'") {
$quote = $character;
} elseif (strncasecmp(substr($html, $index, 4), '&gt;', 4) === 0) {
return $index + 4;
}
}
return null;
}
/**
* @return array<int, array{0:int,1:string}>
*/
private function splitText(string $text, int $maxBytes): array
{
$parts = [];
$offset = 0;
$length = strlen($text);
while ($offset < $length) {
$remaining = substr($text, $offset);
if (strlen($remaining) <= $maxBytes) {
$parts[] = [$offset, $remaining];
break;
}
$candidate = mb_strcut($remaining, 0, $maxBytes, 'UTF-8');
$splitAt = strlen($candidate);
if (preg_match_all('/\s+/u', $candidate, $matches, PREG_OFFSET_CAPTURE) > 0) {
$last = end($matches[0]);
$whitespaceEnd = $last[1] + strlen($last[0]);
if ($whitespaceEnd >= (int)($maxBytes / 2)) {
$splitAt = $whitespaceEnd;
}
}
$parts[] = [$offset, substr($text, $offset, $splitAt)];
$offset += $splitAt;
}
return $parts;
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class LocaleResolver
{
private const LOCALE_PATH = 'general/locale/code';
private const DEFAULT_SOURCE_LANGUAGE_PATH =
'esun_multilocale_translation/general/default_source_language';
private const GOOGLE_LANGUAGE_MAP = [
'zh_CN' => 'zh-CN',
'zh_Hans_CN' => 'zh-CN',
'zh_TW' => 'zh-TW',
'zh_Hant_TW' => 'zh-TW',
'nb_NO' => 'no',
];
private const DEEPL_TARGET_LANGUAGE_MAP = [
'en_US' => 'EN-US',
'en_GB' => 'EN-GB',
'en_AU' => 'EN-GB',
'pt_BR' => 'PT-BR',
'pt_PT' => 'PT-PT',
'zh_CN' => 'ZH-HANS',
'zh_Hans_CN' => 'ZH-HANS',
'zh_TW' => 'ZH-HANT',
'zh_Hant_TW' => 'ZH-HANT',
];
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
{
}
public function getLanguageCode(int $storeId, string $provider, bool $target): string
{
if ($storeId <= 0) {
$locale = (string)$this->scopeConfig->getValue(self::DEFAULT_SOURCE_LANGUAGE_PATH);
} else {
$locale = (string)$this->scopeConfig->getValue(
self::LOCALE_PATH,
ScopeInterface::SCOPE_STORE,
$storeId
);
}
if ($locale === '') {
throw new \RuntimeException((string)__('The Locale is not configured for this Store View.'));
}
if ($provider === 'deepl') {
if ($target && isset(self::DEEPL_TARGET_LANGUAGE_MAP[$locale])) {
return self::DEEPL_TARGET_LANGUAGE_MAP[$locale];
}
return strtoupper($this->getBaseLanguage($locale));
}
if (isset(self::GOOGLE_LANGUAGE_MAP[$locale])) {
return self::GOOGLE_LANGUAGE_MAP[$locale];
}
return $this->getBaseLanguage($locale);
}
private function getBaseLanguage(string $locale): string
{
$parts = preg_split('/[_-]/', $locale);
$language = strtolower((string)($parts[0] ?? ''));
if ($language === '') {
throw new \RuntimeException((string)__('Invalid Locale "%1".', $locale));
}
return $language;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\Model\AbstractModel;
class Log extends AbstractModel
{
protected function _construct(): void
{
$this->_init(\Esun\MultiLocaleTranslation\Model\ResourceModel\Log::class);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\ResourceConnection;
class LogCleaner
{
private const TABLE_NAME = 'esun_localetranslation_log';
public function __construct(private readonly ResourceConnection $resourceConnection)
{
}
public function clearAll(): int
{
return $this->resourceConnection->getConnection()->delete(
$this->resourceConnection->getTableName(self::TABLE_NAME)
);
}
}
@@ -0,0 +1,298 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Provider;
use Esun\MultiLocaleTranslation\Api\TranslationProviderInterface;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\CurlFactory;
class DeepL implements TranslationProviderInterface
{
private const FREE_API_URL = 'https://api-free.deepl.com/v2/translate';
private const PRO_API_URL = 'https://api.deepl.com/v2/translate';
private const XML_PATH_ENABLED = 'esun_multilocale_translation/deepl/enabled';
private const XML_PATH_API_URL = 'esun_multilocale_translation/deepl/api_url';
private const XML_PATH_AUTH_KEY = 'esun_multilocale_translation/deepl/auth_key';
private const XML_PATH_FORMALITY = 'esun_multilocale_translation/deepl/formality';
private const XML_PATH_TIMEOUT = 'esun_multilocale_translation/deepl/timeout';
private const MAX_BATCH_BYTES = 90000;
private const MAX_BATCH_ITEMS = 50;
private const MAX_HTML_FRAGMENT_BYTES = 30000;
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly EncryptorInterface $encryptor,
private readonly CurlFactory $curlFactory,
private readonly TranslatableTextExtractor $textExtractor
) {
}
public function translate(array $fields, string $sourceLanguage, string $targetLanguage): array
{
if (!$this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED)) {
throw new LocalizedException(__('DeepL automatic translation is disabled in configuration.'));
}
$authKey = $this->getAuthKey();
if ($authKey === '') {
throw new LocalizedException(__('DeepL Auth Key is not configured.'));
}
$textFields = [];
$htmlFields = [];
$placeholderMaps = [];
foreach ($fields as $code => $field) {
if (!is_array($field)) {
continue;
}
$value = (string)($field['value'] ?? '');
if ($value === '') {
continue;
}
$format = !empty($field['is_html']) ? 'html' : 'text';
[$preparedValue, $placeholderMaps[(string)$code]] = $this->protectMagentoDirectives($value);
if ($format === 'html') {
$htmlFields[(string)$code] = $preparedValue;
} else {
$textFields[(string)$code] = $preparedValue;
}
}
$translated = [];
foreach ($this->createBatches($textFields) as $batch) {
$translated += $this->translateBatch(
$batch,
$sourceLanguage,
$targetLanguage,
'text',
$authKey
);
}
foreach ($htmlFields as $code => $value) {
$translated[$code] = $this->translateHtml(
$value,
$sourceLanguage,
$targetLanguage,
$authKey
);
}
foreach ($translated as $code => $value) {
$translated[$code] = $this->restoreMagentoDirectives(
$value,
$placeholderMaps[$code] ?? [],
$code
);
}
return $translated;
}
private function translateHtml(
string $html,
string $sourceLanguage,
string $targetLanguage,
string $authKey
): string {
$fragments = $this->textExtractor->extract($html, self::MAX_HTML_FRAGMENT_BYTES);
if ($fragments === []) {
return $html;
}
$values = [];
foreach ($fragments as $index => $fragment) {
$values[(string)$index] = $fragment['text'];
}
$translations = [];
foreach ($this->createBatches($values) as $batch) {
$translations += $this->translateBatch(
$batch,
$sourceLanguage,
$targetLanguage,
'html',
$authKey
);
}
for ($index = count($fragments) - 1; $index >= 0; $index--) {
$fragment = $fragments[$index];
$translation = $translations[(string)$index] ?? null;
if ($translation === null) {
throw new LocalizedException(__('DeepL did not return every HTML text fragment. Nothing was saved.'));
}
$html = substr($html, 0, $fragment['offset'])
. $translation
. substr($html, $fragment['offset'] + $fragment['length']);
}
return $html;
}
private function getAuthKey(): string
{
$encrypted = trim((string)$this->scopeConfig->getValue(self::XML_PATH_AUTH_KEY));
if ($encrypted === '') {
return '';
}
try {
return trim((string)$this->encryptor->decrypt($encrypted));
} catch (\Throwable) {
return '';
}
}
/**
* @param array<string, string> $values
* @return array<int, array<string, string>>
*/
private function createBatches(array $values): array
{
$batches = [];
$batch = [];
$bytes = 0;
foreach ($values as $code => $value) {
$valueBytes = strlen($value);
if ($valueBytes > self::MAX_BATCH_BYTES) {
throw new LocalizedException(__('Field "%1" is too large for DeepL translation.', $code));
}
if ($batch !== [] && ($bytes + $valueBytes > self::MAX_BATCH_BYTES
|| count($batch) >= self::MAX_BATCH_ITEMS)
) {
$batches[] = $batch;
$batch = [];
$bytes = 0;
}
$batch[$code] = $value;
$bytes += $valueBytes;
}
if ($batch !== []) {
$batches[] = $batch;
}
return $batches;
}
/**
* @param array<string, string> $batch
* @return array<string, string>
*/
private function translateBatch(
array $batch,
string $sourceLanguage,
string $targetLanguage,
string $format,
string $authKey
): array {
$requestData = [
'text' => array_values($batch),
'source_lang' => $sourceLanguage,
'target_lang' => $targetLanguage,
'preserve_formatting' => true,
'show_billed_characters' => true,
'model_type' => 'prefer_quality_optimized',
];
if ($format === 'html') {
$requestData['tag_handling'] = 'html';
$requestData['tag_handling_version'] = 'v2';
}
$formality = (string)$this->scopeConfig->getValue(self::XML_PATH_FORMALITY);
if (in_array($formality, ['prefer_more', 'prefer_less'], true)) {
$requestData['formality'] = $formality;
}
$client = $this->curlFactory->create();
$client->setTimeout(max(5, min(120, (int)$this->scopeConfig->getValue(self::XML_PATH_TIMEOUT))));
$client->setHeaders([
'Authorization' => 'DeepL-Auth-Key ' . $authKey,
'Content-Type' => 'application/json; charset=utf-8',
]);
$client->post(
$this->getApiUrl(),
json_encode(
$requestData,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
)
);
$response = json_decode((string)$client->getBody(), true);
if ($client->getStatus() < 200 || $client->getStatus() >= 300) {
$message = is_array($response) ? (string)($response['message'] ?? '') : '';
throw new LocalizedException(
__('DeepL translation failed (HTTP %1): %2',
$client->getStatus(),
$message ?: 'Unknown error')
);
}
$items = is_array($response) ? ($response['translations'] ?? null) : null;
if (!is_array($items) || count($items) !== count($batch)) {
throw new LocalizedException(__('DeepL returned an invalid translation response.'));
}
$result = [];
$codes = array_keys($batch);
foreach ($items as $index => $item) {
$result[$codes[$index]] = is_array($item) ? (string)($item['text'] ?? '') : '';
}
return $result;
}
private function getApiUrl(): string
{
$url = (string)$this->scopeConfig->getValue(self::XML_PATH_API_URL);
if ($url === self::PRO_API_URL) {
return self::PRO_API_URL;
}
return self::FREE_API_URL;
}
/**
* @return array{0:string,1:array<string,string>}
*/
private function protectMagentoDirectives(string $value): array
{
$placeholders = [];
$prepared = preg_replace_callback(
'/\{\{.*?\}\}/s',
static function (array $matches) use (&$placeholders): string {
$token = 'ESUNMLT' . strtoupper(bin2hex(random_bytes(10)));
$placeholders[$token] = $matches[0];
return $token;
},
$value
);
return [$prepared ?? $value, $placeholders];
}
/**
* @param array<string, string> $placeholders
*/
private function restoreMagentoDirectives(string $value, array $placeholders, string $fieldCode): string
{
foreach ($placeholders as $token => $directive) {
if (!str_contains($value, $token)) {
throw new LocalizedException(
__('DeepL changed a Magento directive placeholder in field "%1". Nothing was saved.', $fieldCode)
);
}
$value = str_replace($token, $directive, $value);
}
return $value;
}
}
@@ -0,0 +1,312 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Provider;
use Esun\MultiLocaleTranslation\Api\TranslationProviderInterface;
use Esun\MultiLocaleTranslation\Model\Google\AccessToken;
use Esun\MultiLocaleTranslation\Model\Google\Credentials;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\CurlFactory;
class Google implements TranslationProviderInterface
{
private const API_BASE_URL = 'https://translation.googleapis.com/v3/projects/';
private const XML_PATH_ENABLED = 'esun_multilocale_translation/google/enabled';
private const XML_PATH_LOCATION = 'esun_multilocale_translation/google/location';
private const XML_PATH_GLOSSARY_ID = 'esun_multilocale_translation/google/glossary_id';
private const XML_PATH_GLOSSARY_IGNORE_CASE = 'esun_multilocale_translation/google/glossary_ignore_case';
private const XML_PATH_TIMEOUT = 'esun_multilocale_translation/google/timeout';
private const MAX_BATCH_CODEPOINTS = 25000;
private const MAX_BATCH_ITEMS = 100;
private const MAX_HTML_FRAGMENT_BYTES = 25000;
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly Credentials $credentials,
private readonly AccessToken $accessToken,
private readonly CurlFactory $curlFactory,
private readonly TranslatableTextExtractor $textExtractor
) {
}
public function translate(array $fields, string $sourceLanguage, string $targetLanguage): array
{
if (!$this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED)) {
throw new LocalizedException(__('Google automatic translation is disabled in configuration.'));
}
if ($sourceLanguage === '' || $targetLanguage === '') {
throw new LocalizedException(__('Google V3 requires both source and target languages.'));
}
$location = $this->getLocation();
$glossaryId = $this->getGlossaryId();
if ($glossaryId !== '' && $location !== 'us-central1') {
throw new LocalizedException(__('Google glossaries require the us-central1 location.'));
}
$textFields = [];
$htmlFields = [];
$placeholderMaps = [];
foreach ($fields as $code => $field) {
if (!is_array($field)) {
continue;
}
$value = (string)($field['value'] ?? '');
if ($value === '') {
continue;
}
[$preparedValue, $placeholderMaps[(string)$code]] = $this->protectMagentoDirectives($value);
if (!empty($field['is_html'])) {
$htmlFields[(string)$code] = $preparedValue;
} else {
$textFields[(string)$code] = $preparedValue;
}
}
$translated = [];
foreach ($this->createBatches($textFields) as $batch) {
$translated += $this->translateBatch(
$batch,
$sourceLanguage,
$targetLanguage,
'text/plain',
$location,
$glossaryId
);
}
foreach ($htmlFields as $code => $value) {
$translated[$code] = $this->translateHtml(
$value,
$sourceLanguage,
$targetLanguage,
$location,
$glossaryId
);
}
foreach ($translated as $code => $value) {
$translated[$code] = $this->restoreMagentoDirectives(
$value,
$placeholderMaps[$code] ?? [],
$code
);
}
return $translated;
}
private function translateHtml(
string $html,
string $sourceLanguage,
string $targetLanguage,
string $location,
string $glossaryId
): string {
$fragments = $this->textExtractor->extract($html, self::MAX_HTML_FRAGMENT_BYTES);
if ($fragments === []) {
return $html;
}
$values = [];
foreach ($fragments as $index => $fragment) {
$values[(string)$index] = $fragment['text'];
}
$translations = [];
foreach ($this->createBatches($values) as $batch) {
$translations += $this->translateBatch(
$batch,
$sourceLanguage,
$targetLanguage,
'text/html',
$location,
$glossaryId
);
}
for ($index = count($fragments) - 1; $index >= 0; $index--) {
$fragment = $fragments[$index];
$translation = $translations[(string)$index] ?? null;
if ($translation === null) {
throw new LocalizedException(__('Google did not return every HTML text fragment. Nothing was saved.'));
}
$html = substr($html, 0, $fragment['offset'])
. $translation
. substr($html, $fragment['offset'] + $fragment['length']);
}
return $html;
}
/**
* @param array<string, string> $values
* @return array<int, array<string, string>>
*/
private function createBatches(array $values): array
{
$batches = [];
$batch = [];
$codepoints = 0;
foreach ($values as $code => $value) {
$valueCodepoints = mb_strlen($value, 'UTF-8');
if ($valueCodepoints > self::MAX_BATCH_CODEPOINTS) {
throw new LocalizedException(
__('Field "%1" is too large for synchronous Google V3 translation.', $code)
);
}
if ($batch !== [] && ($codepoints + $valueCodepoints > self::MAX_BATCH_CODEPOINTS
|| count($batch) >= self::MAX_BATCH_ITEMS)
) {
$batches[] = $batch;
$batch = [];
$codepoints = 0;
}
$batch[$code] = $value;
$codepoints += $valueCodepoints;
}
if ($batch !== []) {
$batches[] = $batch;
}
return $batches;
}
/**
* @param array<string, string> $batch
* @return array<string, string>
*/
private function translateBatch(
array $batch,
string $sourceLanguage,
string $targetLanguage,
string $mimeType,
string $location,
string $glossaryId
): array {
$credentials = $this->credentials->get();
$projectId = $credentials['project_id'];
$parent = 'projects/' . $projectId . '/locations/' . $location;
$requestData = [
'contents' => array_values($batch),
'sourceLanguageCode' => $sourceLanguage,
'targetLanguageCode' => $targetLanguage,
'mimeType' => $mimeType,
'model' => $parent . '/models/general/nmt',
];
if ($glossaryId !== '') {
$requestData['glossaryConfig'] = [
'glossary' => $parent . '/glossaries/' . $glossaryId,
'ignoreCase' => $this->scopeConfig->isSetFlag(self::XML_PATH_GLOSSARY_IGNORE_CASE),
];
}
$payload = json_encode(
$requestData,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
);
$client = $this->curlFactory->create();
$client->setTimeout(max(5, min(120, (int)$this->scopeConfig->getValue(self::XML_PATH_TIMEOUT))));
$client->setHeaders([
'Authorization' => 'Bearer ' . $this->accessToken->get(),
'Content-Type' => 'application/json; charset=utf-8',
'x-goog-user-project' => $projectId,
]);
$client->post(
self::API_BASE_URL . rawurlencode($projectId)
. '/locations/' . rawurlencode($location) . ':translateText',
$payload
);
$response = json_decode((string)$client->getBody(), true);
if ($client->getStatus() < 200 || $client->getStatus() >= 300) {
$message = is_array($response) ? (string)($response['error']['message'] ?? '') : '';
throw new LocalizedException(
__('Google V3 translation failed (HTTP %1): %2',
$client->getStatus(),
$message ?: 'Unknown error')
);
}
$responseKey = $glossaryId !== '' ? 'glossaryTranslations' : 'translations';
$items = is_array($response) ? ($response[$responseKey] ?? null) : null;
if (!is_array($items) || count($items) !== count($batch)) {
throw new LocalizedException(__('Google V3 returned an invalid translation response.'));
}
$result = [];
$codes = array_keys($batch);
foreach ($items as $index => $item) {
$value = is_array($item) ? (string)($item['translatedText'] ?? '') : '';
$result[$codes[$index]] = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
return $result;
}
private function getLocation(): string
{
$location = trim((string)$this->scopeConfig->getValue(self::XML_PATH_LOCATION)) ?: 'global';
if (!preg_match('/^[a-z0-9-]+$/', $location)) {
throw new LocalizedException(__('The configured Google location is invalid.'));
}
return $location;
}
private function getGlossaryId(): string
{
$glossaryId = trim((string)$this->scopeConfig->getValue(self::XML_PATH_GLOSSARY_ID));
if ($glossaryId !== '' && !preg_match('/^[a-zA-Z0-9_-]+$/', $glossaryId)) {
throw new LocalizedException(__('The configured Google Glossary ID is invalid.'));
}
return $glossaryId;
}
/**
* @return array{0:string,1:array<string,string>}
*/
private function protectMagentoDirectives(string $value): array
{
$placeholders = [];
$prepared = preg_replace_callback(
'/\{\{.*?\}\}/s',
static function (array $matches) use (&$placeholders): string {
$token = 'ESUNMLT' . strtoupper(bin2hex(random_bytes(10)));
$placeholders[$token] = $matches[0];
return $token;
},
$value
);
return [$prepared ?? $value, $placeholders];
}
/**
* @param array<string, string> $placeholders
*/
private function restoreMagentoDirectives(string $value, array $placeholders, string $fieldCode): string
{
foreach ($placeholders as $token => $directive) {
if (!str_contains($value, $token)) {
throw new LocalizedException(
__('Google changed a Magento directive placeholder in field "%1". Nothing was saved.', $fieldCode)
);
}
$value = str_replace($token, $directive, $value);
}
return $value;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
class ProviderConfig
{
private const XML_PATH_DEFAULT_PROVIDER = 'esun_multilocale_translation/general/default_provider';
private const PROVIDERS = [
'deepl' => ['label' => 'DeepL', 'enabled_path' => 'esun_multilocale_translation/deepl/enabled'],
'google' => [
'label' => 'Google Cloud Translation V3',
'enabled_path' => 'esun_multilocale_translation/google/enabled',
],
];
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
{
}
/**
* @return array<int, array{code:string,label:string}>
*/
public function getEnabledOptions(): array
{
$result = [];
foreach (self::PROVIDERS as $code => $provider) {
if (!$this->scopeConfig->isSetFlag($provider['enabled_path'])) {
continue;
}
$result[] = ['code' => $code, 'label' => $provider['label']];
}
return $result;
}
public function getDefaultProvider(): string
{
$configured = (string)$this->scopeConfig->getValue(self::XML_PATH_DEFAULT_PROVIDER);
foreach ($this->getEnabledOptions() as $provider) {
if ($provider['code'] === $configured) {
return $configured;
}
}
return (string)($this->getEnabledOptions()[0]['code'] ?? '');
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Esun\MultiLocaleTranslation\Api\TranslationProviderInterface;
use Magento\Framework\Exception\LocalizedException;
class ProviderPool
{
/**
* @param array<string, TranslationProviderInterface> $providers
*/
public function __construct(private readonly array $providers = [])
{
}
public function get(string $code): TranslationProviderInterface
{
$provider = $this->providers[$code] ?? null;
if (!$provider instanceof TranslationProviderInterface) {
throw new LocalizedException(__('Translation provider "%1" is not available.', $code));
}
return $provider;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Framework\Model\AbstractModel;
class Queue extends AbstractModel
{
protected function _construct(): void
{
$this->_init(\Esun\MultiLocaleTranslation\Model\ResourceModel\Queue::class);
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Queue;
use Magento\Framework\App\Config\ScopeConfigInterface;
class CronConsumer
{
private const XML_PATH_TASKS_PER_RUN = 'esun_multilocale_translation/queue/tasks_per_run';
private const XML_PATH_TIME_LIMIT = 'esun_multilocale_translation/queue/time_limit';
public function __construct(
private readonly QueueProcessor $queueProcessor,
private readonly ScopeConfigInterface $scopeConfig
) {
}
public function execute(): void
{
$tasksPerRun = min(50, max(1, (int)$this->scopeConfig->getValue(self::XML_PATH_TASKS_PER_RUN)));
$timeLimit = min(300, max(10, (int)$this->scopeConfig->getValue(self::XML_PATH_TIME_LIMIT)));
$this->queueProcessor->process($tasksPerRun, $timeLimit);
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Queue;
use Esun\MultiLocaleTranslation\Model\EntityPool;
use Esun\MultiLocaleTranslation\Model\ProviderConfig;
use Esun\MultiLocaleTranslation\Model\StoreViewProvider;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\LocalizedException;
class QueueManager
{
private const TABLE_NAME = 'esun_localetranslation_queue';
public function __construct(
private readonly ResourceConnection $resourceConnection,
private readonly EntityPool $entityPool,
private readonly ProviderConfig $providerConfig,
private readonly StoreViewProvider $storeViewProvider
) {
}
/**
* @param int[] $entityIds
* @param int[] $targetStoreIds
* @return array{batch_id:string,created:int,skipped:int}
*/
public function enqueue(
string $entityType,
array $entityIds,
int $sourceStoreId,
array $targetStoreIds,
string $provider
): array {
$this->entityPool->get($entityType);
$enabledProviders = array_column($this->providerConfig->getEnabledOptions(), 'code');
if (!in_array($provider, $enabledProviders, true)) {
throw new LocalizedException(__('The selected translation provider is not enabled.'));
}
$validStoreIds = array_column($this->storeViewProvider->getStoreViewOptions(), 'store_id');
$entityIds = array_values(array_unique(array_filter(array_map('intval', $entityIds))));
$targetStoreIds = array_values(array_unique(array_filter(array_map('intval', $targetStoreIds))));
$targetStoreIds = array_values(array_intersect($targetStoreIds, $validStoreIds));
if ($sourceStoreId > 0) {
$targetStoreIds = array_values(array_diff($targetStoreIds, [$sourceStoreId]));
}
if ($entityIds === [] || $targetStoreIds === []) {
throw new LocalizedException(__('Select at least one entity and one target Store View.'));
}
$connection = $this->resourceConnection->getConnection();
$table = $this->resourceConnection->getTableName(self::TABLE_NAME);
$batchId = bin2hex(random_bytes(16));
$rows = [];
$skipped = 0;
foreach ($entityIds as $entityId) {
foreach ($targetStoreIds as $targetStoreId) {
$existing = (int)$connection->fetchOne(
$connection->select()
->from($table, 'COUNT(*)')
->where('entity_type = ?', $entityType)
->where('entity_id = ?', $entityId)
->where('source_store_id = ?', max(0, $sourceStoreId))
->where('target_store_id = ?', $targetStoreId)
->where('provider = ?', $provider)
->where('status IN (?)', ['pending', 'processing'])
);
if ($existing > 0) {
$skipped++;
continue;
}
$rows[] = [
'batch_id' => $batchId,
'provider' => $provider,
'entity_type' => $entityType,
'entity_id' => $entityId,
'source_store_id' => max(0, $sourceStoreId),
'target_store_id' => $targetStoreId,
'status' => 'pending',
];
}
}
if ($rows !== []) {
$connection->insertMultiple($table, $rows);
}
return ['batch_id' => $batchId, 'created' => count($rows), 'skipped' => $skipped];
}
/** @return array{deleted:int,processing:int} */
public function clearAll(): array
{
$connection = $this->resourceConnection->getConnection();
$table = $this->resourceConnection->getTableName(self::TABLE_NAME);
$processing = (int)$connection->fetchOne(
$connection->select()
->from($table, 'COUNT(*)')
->where('status = ?', 'processing')
);
return [
'deleted' => $connection->delete($table),
'processing' => $processing,
];
}
}
@@ -0,0 +1,233 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Queue;
use Esun\MultiLocaleTranslation\Model\EntityPool;
use Esun\MultiLocaleTranslation\Model\LocaleResolver;
use Esun\MultiLocaleTranslation\Model\ProviderPool;
use Esun\MultiLocaleTranslation\Model\TranslationLogger;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Sql\Expression;
class QueueProcessor
{
private const TABLE_NAME = 'esun_localetranslation_queue';
public function __construct(
private readonly ResourceConnection $resourceConnection,
private readonly EntityPool $entityPool,
private readonly ProviderPool $providerPool,
private readonly LocaleResolver $localeResolver,
private readonly TranslationLogger $translationLogger
) {
}
public function process(int $limit = 10, int $timeLimit = 50): int
{
$processed = 0;
$startedAt = microtime(true);
$limit = min(50, max(1, $limit));
$timeLimit = min(300, max(10, $timeLimit));
for ($index = 0; $index < $limit; $index++) {
if ($processed > 0 && microtime(true) - $startedAt >= $timeLimit) {
break;
}
$task = $this->claimNext();
if ($task === null) {
break;
}
$this->processTask($task);
$processed++;
}
return $processed;
}
/** @return array<string, mixed>|null */
private function claimNext(): ?array
{
$connection = $this->resourceConnection->getConnection();
$table = $this->resourceConnection->getTableName(self::TABLE_NAME);
while (true) {
$queueId = (int)$connection->fetchOne(
$connection->select()->from($table, 'queue_id')
->where('status = ?', 'pending')
->order('queue_id ASC')
->limit(1)
);
if ($queueId <= 0) {
return null;
}
$affected = $connection->update(
$table,
[
'status' => 'processing',
'attempts' => new Expression('attempts + 1'),
'started_at' => new Expression('CURRENT_TIMESTAMP'),
'finished_at' => null,
'error_message' => null,
],
['queue_id = ?' => $queueId, 'status = ?' => 'pending']
);
if ($affected === 1) {
$task = $connection->fetchRow(
$connection->select()->from($table)->where('queue_id = ?', $queueId)
);
return is_array($task) ? $task : null;
}
}
}
/** @param array<string, mixed> $task */
private function processTask(array $task): void
{
$queueId = (int)$task['queue_id'];
$provider = (string)$task['provider'];
$entityType = (string)$task['entity_type'];
$entityId = (int)$task['entity_id'];
$sourceStoreId = (int)$task['source_store_id'];
$targetStoreId = (int)$task['target_store_id'];
$sourceLanguage = '';
$targetLanguage = '';
$providerFields = [];
try {
$entity = $this->entityPool->get($entityType);
foreach ($entity->getFields($entityId, $sourceStoreId, $targetStoreId) as $field) {
$value = (string)($field['source_value'] ?? '');
if ($value === '' || empty($field['code'])) {
continue;
}
$providerFields[(string)$field['code']] = [
'value' => $value,
'is_html' => !empty($field['is_html']),
];
}
$sourceLanguage = $this->localeResolver->getLanguageCode($sourceStoreId, $provider, false);
$targetLanguage = $this->localeResolver->getLanguageCode($targetStoreId, $provider, true);
if ($providerFields === []) {
$translations = [];
} elseif ($sourceLanguage !== '' && $sourceLanguage === $targetLanguage) {
$translations = $this->copyValues($providerFields);
} else {
$translations = $this->providerPool->get($provider)->translate(
$providerFields,
$sourceLanguage,
$targetLanguage
);
}
$entity->apply($entityId, $targetStoreId, $translations);
$this->safeLogSuccess(
$provider,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$providerFields,
$translations
);
$this->finish($queueId, 'success', null);
} catch (\Throwable $exception) {
$this->safeLogFailure(
$provider,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$providerFields,
$exception->getMessage()
);
$this->finish($queueId, 'failed', $exception->getMessage());
}
}
/** @param array<string, mixed> $fields @return array<string, string> */
private function copyValues(array $fields): array
{
$values = [];
foreach ($fields as $code => $field) {
$values[$code] = (string)($field['value'] ?? '');
}
return $values;
}
private function finish(int $queueId, string $status, ?string $error): void
{
$connection = $this->resourceConnection->getConnection();
$connection->update(
$this->resourceConnection->getTableName(self::TABLE_NAME),
[
'status' => $status,
'error_message' => $error,
'finished_at' => new Expression('CURRENT_TIMESTAMP'),
],
['queue_id = ?' => $queueId]
);
}
private function safeLogSuccess(
string $provider,
string $entityType,
int $entityId,
int $sourceStoreId,
int $targetStoreId,
string $sourceLanguage,
string $targetLanguage,
array $fields,
array $translations
): void {
try {
$this->translationLogger->logSuccess(
$provider,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$fields,
$translations,
$sourceLanguage === $targetLanguage ? 'copied' : 'success'
);
} catch (\Throwable) {
}
}
private function safeLogFailure(
string $provider,
string $entityType,
int $entityId,
int $sourceStoreId,
int $targetStoreId,
string $sourceLanguage,
string $targetLanguage,
array $fields,
string $error
): void {
try {
$this->translationLogger->logFailure(
$provider,
$entityType,
$entityId,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$fields,
$error
);
} catch (\Throwable) {
}
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Queue;
use Magento\Backend\Model\Session;
class SelectionRegistry
{
private const SESSION_PREFIX = 'esun_mlt_queue_selection_';
public function __construct(private readonly Session $session)
{
}
/** @param int[] $entityIds */
public function save(string $entityType, array $entityIds): string
{
$token = bin2hex(random_bytes(16));
$this->session->setData(self::SESSION_PREFIX . $token, [
'entity_type' => $entityType,
'entity_ids' => array_values(array_unique(array_map('intval', $entityIds))),
]);
return $token;
}
/** @return array{entity_type:string,entity_ids:int[]}|null */
public function get(string $token): ?array
{
if (preg_match('/^[a-f0-9]{32}$/', $token) !== 1) {
return null;
}
$selection = $this->session->getData(self::SESSION_PREFIX . $token);
return is_array($selection) ? $selection : null;
}
public function clear(string $token): void
{
if (preg_match('/^[a-f0-9]{32}$/', $token) === 1) {
$this->session->unsetData(self::SESSION_PREFIX . $token);
}
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Log extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_localetranslation_log', 'log_id');
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\ResourceModel\Log;
use Esun\MultiLocaleTranslation\Model\Log;
use Esun\MultiLocaleTranslation\Model\ResourceModel\Log as LogResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(Log::class, LogResource::class);
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Queue extends AbstractDb
{
protected function _construct(): void
{
$this->_init('esun_localetranslation_queue', 'queue_id');
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\ResourceModel\Queue;
use Esun\MultiLocaleTranslation\Model\Queue;
use Esun\MultiLocaleTranslation\Model\ResourceModel\Queue as QueueResource;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
protected function _construct(): void
{
$this->_init(Queue::class, QueueResource::class);
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class StoreViewProvider
{
public function __construct(
private readonly StoreManagerInterface $storeManager,
private readonly ScopeConfigInterface $scopeConfig
) {
}
/**
* @return array<int, array{store_id:int,label:string,code:string,website:string,group:string,locale:string}>
*/
public function getStoreViewOptions(): array
{
$result = [];
$stores = $this->storeManager->getStores(true, false);
foreach ($stores as $store) {
if (!$store instanceof Store) {
continue;
}
if (!(int)$store->getId()) {
continue;
}
if (!$store->isActive()) {
continue;
}
$result[] = [
'store_id' => (int)$store->getId(),
'code' => (string)$store->getCode(),
'label' => (string)$store->getName(),
'website' => (string)$store->getWebsite()->getName(),
'group' => (string)$store->getGroup()->getName(),
'locale' => (string)$this->scopeConfig->getValue(
'general/locale/code',
ScopeInterface::SCOPE_STORE,
(int)$store->getId()
),
];
}
return $result;
}
/**
* @return array<int, array{website:string,stores:array<int, array<string, mixed>>}>
*/
public function getStoreViewGroups(): array
{
$groups = [];
foreach ($this->getStoreViewOptions() as $store) {
$website = (string)$store['website'];
if (!isset($groups[$website])) {
$groups[$website] = [
'website' => $website,
'stores' => [],
];
}
$groups[$website]['stores'][] = $store;
}
return array_values($groups);
}
public function getDefaultSourceStoreId(): int
{
return Store::DEFAULT_STORE_ID;
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
interface TranslatableEntityInterface
{
/**
* @return array<int, array{
* code:string,
* label:string,
* source_value:string,
* target_value:string,
* is_html:bool,
* use_default:bool
* }>
*/
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array;
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void;
}
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Magento\Framework\App\ResourceConnection;
class TranslationLogger
{
private const TABLE_NAME = 'esun_localetranslation_log';
private const MAX_LOG_FRAGMENT_BYTES = 30000;
public function __construct(
private readonly ResourceConnection $resourceConnection,
private readonly TranslatableTextExtractor $textExtractor
) {
}
/**
* @param array<string, mixed> $fields
* @param array<string, string> $translations
*/
public function logSuccess(
string $provider,
string $entityType,
int $entityId,
int $sourceStoreId,
int $targetStoreId,
string $sourceLanguage,
string $targetLanguage,
array $fields,
array $translations,
string $status = 'success'
): void {
$rows = [];
foreach ($fields as $fieldName => $field) {
if (!is_array($field) || !array_key_exists('value', $field)) {
continue;
}
$fieldName = (string)$fieldName;
if (!array_key_exists($fieldName, $translations)) {
continue;
}
$isHtml = !empty($field['is_html']);
$sourceText = $this->textForLog((string)$field['value'], $isHtml);
$translatedText = $this->textForLog((string)$translations[$fieldName], $isHtml);
$rows[] = $this->buildRow(
$provider,
$entityType,
$entityId,
$fieldName,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$sourceText,
$translatedText,
$status,
null
);
}
$this->insertRows($rows);
}
/** @param array<string, mixed> $fields */
public function logFailure(
string $provider,
string $entityType,
int $entityId,
int $sourceStoreId,
int $targetStoreId,
string $sourceLanguage,
string $targetLanguage,
array $fields,
string $errorMessage
): void {
$rows = [];
foreach ($fields as $fieldName => $field) {
if (!is_array($field) || !array_key_exists('value', $field)) {
continue;
}
$sourceText = $this->textForLog((string)$field['value'], !empty($field['is_html']));
$rows[] = $this->buildRow(
$provider,
$entityType,
$entityId,
(string)$fieldName,
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
$sourceText,
null,
'failed',
$errorMessage
);
}
if ($rows === []) {
$rows[] = $this->buildRow(
$provider,
$entityType,
$entityId,
'',
$sourceStoreId,
$targetStoreId,
$sourceLanguage,
$targetLanguage,
'',
null,
'failed',
$errorMessage
);
}
$this->insertRows($rows);
}
private function textForLog(string $value, bool $isHtml): string
{
if (!$isHtml || $value === '') {
return $value;
}
$fragments = $this->textExtractor->extract($value, self::MAX_LOG_FRAGMENT_BYTES);
return trim(implode("\n", array_column($fragments, 'text')));
}
/** @return array<string, int|string|null> */
private function buildRow(
string $provider,
string $entityType,
int $entityId,
string $fieldName,
int $sourceStoreId,
int $targetStoreId,
string $sourceLanguage,
string $targetLanguage,
string $sourceText,
?string $translatedText,
string $status,
?string $errorMessage
): array {
return [
'provider' => substr($provider, 0, 32),
'entity_type' => $entityType !== '' ? substr($entityType, 0, 32) : null,
'entity_id' => $entityId > 0 ? $entityId : null,
'field_name' => $fieldName !== '' ? substr($fieldName, 0, 128) : null,
'source_store_id' => max(0, $sourceStoreId),
'target_store_id' => max(0, $targetStoreId),
'source_language' => $sourceLanguage !== '' ? substr($sourceLanguage, 0, 16) : null,
'target_language' => $targetLanguage !== '' ? substr($targetLanguage, 0, 16) : null,
'source_text' => $sourceText,
'translated_text' => $translatedText,
'status' => substr($status, 0, 16),
'error_message' => $errorMessage,
'character_count' => mb_strlen($sourceText, 'UTF-8'),
];
}
/** @param array<int, array<string, int|string|null>> $rows */
private function insertRows(array $rows): void
{
if ($rows === []) {
return;
}
$connection = $this->resourceConnection->getConnection();
$connection->insertMultiple(
$this->resourceConnection->getTableName(self::TABLE_NAME),
$rows
);
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
class WikiFields
{
public const CATEGORY = [
'title' => ['label' => 'Title', 'is_html' => false],
'summary' => ['label' => 'Summary', 'is_html' => false],
'content' => ['label' => 'Content', 'is_html' => true],
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
'meta_keywords' => ['label' => 'Meta Keywords', 'is_html' => false],
];
public const HOMEPAGE = [
'title' => ['label' => 'Title', 'is_html' => false],
'content' => ['label' => 'Content', 'is_html' => true],
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
'meta_keywords' => ['label' => 'Meta Keywords', 'is_html' => false],
];
public static function categoryCodes(): array
{
return array_keys(self::CATEGORY);
}
public static function homepageCodes(): array
{
return array_keys(self::HOMEPAGE);
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\Homepage;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class WikiTranslationApplier
{
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function apply(Category $entity): void
{
if (!$this->isFrontend() || !$entity->getId()) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$isHomepage = $entity instanceof Homepage;
$translations = $this->translationRepository->getTranslations(
(int)$entity->getId(),
$storeId,
$isHomepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$isHomepage ? WikiFields::homepageCodes() : WikiFields::categoryCodes()
);
$this->applyValues($entity, $translations);
}
/** @param Category[] $entities */
public function applyMany(array $entities, bool $homepage = false): void
{
if (!$this->isFrontend() || $entities === []) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$entityIds = [];
foreach ($entities as $entity) {
if ($entity instanceof Category && $entity->getId()) {
$entityIds[] = (int)$entity->getId();
}
}
$translations = $this->translationRepository->getTranslationsForEntities(
$entityIds,
$storeId,
$homepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$homepage ? WikiFields::homepageCodes() : WikiFields::categoryCodes()
);
foreach ($entities as $entity) {
if ($entity instanceof Category && $entity->getId()) {
$this->applyValues($entity, $translations[(int)$entity->getId()] ?? []);
}
}
}
private function applyValues(Category $entity, array $translations): void
{
foreach ($translations as $field => $value) {
$entity->setData($field, $value);
}
}
private function isFrontend(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Observer\Adminhtml;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Registry;
use Mageplaza\Blog\Block\Adminhtml\Post\Edit\Tab\Post as PostTab;
class PrepareBlogPostForm implements ObserverInterface
{
private const SHARED_FIELDS = [
'url_key',
'author_id',
'enabled',
'store_ids',
'image',
'categories_ids',
'topics_ids',
'tags_ids',
'in_rss',
'allow_comment',
'publish_date',
'layout',
];
public function __construct(
private readonly RequestInterface $request,
private readonly Registry $registry,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function execute(Observer $observer): void
{
$block = $observer->getData('block');
$post = $this->registry->registry('mageplaza_blog_post');
$storeId = max(0, (int)$this->request->getParam('store'));
if (!$block instanceof PostTab || !$post || !$post->getId() || $storeId <= 0) {
return;
}
$form = $block->getForm();
$translations = $this->translationRepository->getTranslations(
(int)$post->getId(),
$storeId,
CmsTranslationRepository::ENTITY_BLOG_POST,
BlogPostFields::codes()
);
$fieldset = $form->getElement('base_fieldset');
if ($fieldset && !$form->getElement('translation_store_id')) {
$fieldset->addField('translation_store_id', 'hidden', [
'name' => 'translation_store_id',
'value' => $storeId,
]);
}
foreach (BlogPostFields::codes() as $field) {
$element = $form->getElement($field);
if (!$element) {
continue;
}
if ($this->skippedFields->isSkipped('blog_post', $field)) {
$element->setDisabled(true);
$element->setData('after_element_html', (string)__('Skipped by translation configuration.'));
continue;
}
$hasTranslation = array_key_exists($field, $translations);
$element->setValue(
$hasTranslation
? $translations[$field]
: BlogPostFields::baseValue($field, $post->getData($field))
);
$element->setDisabled(!$hasTranslation);
$element->setData(
'after_element_html',
sprintf(
'<label class="esun-blog-use-default"><input type="checkbox" name="post[use_default][%1$s]" value="1" data-target="#post_%1$s"%2$s/> %3$s</label>',
$field,
$hasTranslation ? '' : ' checked="checked"',
__('Use Default Value')
)
);
}
foreach (self::SHARED_FIELDS as $field) {
$element = $form->getElement($field);
if ($element) {
$element->setDisabled(true);
}
}
}
}
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Registry;
use Mageplaza\Blog\Block\Adminhtml\Post\Edit;
class BlogPostEditButton
{
public function __construct(
private readonly Registry $registry,
private readonly AuthorizationInterface $authorization
) {
}
public function beforeToHtml(Edit $subject): array
{
$post = $this->registry->registry('mageplaza_blog_post');
if (!$post || !$post->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
return [];
}
$config = [
'entityType' => 'blog_post',
'entityId' => (int)$post->getId(),
'sourceStoreId' => max(0, (int)$subject->getRequest()->getParam('store')),
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
$subject->addButton('localetranslate_translate', [
'label' => __('Translate'),
'class' => 'action-secondary',
'onclick' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 30,
], 0, 30);
return [];
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use Esun\MultiLocaleTranslation\Model\Entity\BlogPostEntity;
use Magento\Framework\App\Cache\Manager as CacheManager;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Mageplaza\Blog\Controller\Adminhtml\Post\Save;
class BlogPostSave
{
public function __construct(
private readonly RequestInterface $request,
private readonly BlogPostEntity $blogPostEntity,
private readonly RedirectFactory $redirectFactory,
private readonly ManagerInterface $messageManager,
private readonly CacheManager $cacheManager,
private readonly AuthorizationInterface $authorization
) {
}
public function aroundExecute(Save $subject, callable $proceed): mixed
{
$postData = $this->request->getParam('post', []);
$postData = is_array($postData) ? $postData : [];
$storeId = max(0, (int)($postData['translation_store_id'] ?? 0));
if ($storeId <= 0) {
return $proceed();
}
$postId = (int)$this->request->getParam('id');
if ($postId <= 0) {
$this->messageManager->addErrorMessage(__('The blog post no longer exists.'));
return $this->redirectFactory->create()->setPath('mageplaza_blog/post/index');
}
if (!$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')) {
$this->messageManager->addErrorMessage(__('You are not allowed to save blog translations.'));
return $this->redirectToEdit($postId, $storeId);
}
try {
$fields = array_intersect_key($postData, array_flip(BlogPostFields::codes()));
$useDefault = is_array($postData['use_default'] ?? null) ? $postData['use_default'] : [];
$this->blogPostEntity->apply($postId, $storeId, $fields, $useDefault);
$this->cacheManager->clean(['full_page', 'block_html']);
$this->messageManager->addSuccessMessage(__('You saved the blog post translation.'));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the blog post translation: %1', $exception->getMessage())
);
}
return $this->redirectToEdit($postId, $storeId);
}
private function redirectToEdit(int $postId, int $storeId): Redirect
{
return $this->redirectFactory->create()->setPath(
'mageplaza_blog/post/edit',
['id' => $postId, 'store' => $storeId]
);
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Block\DataProvider;
use Magento\Framework\App\RequestInterface;
class CmsBlockDataProvider
{
private const FIELDS = [
'title' => 'general',
'content' => 'general',
];
public function __construct(
private readonly RequestInterface $request,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterGetData(DataProvider $subject, array $result): array
{
$blockId = (int)$this->request->getParam('block_id');
$storeId = (int)$this->request->getParam('store');
if ($blockId <= 0 || !isset($result[$blockId])) {
return $result;
}
$result[$blockId]['translation_store_id'] = $storeId;
if ($storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($blockId, $storeId);
foreach (array_keys(self::FIELDS) as $field) {
if (array_key_exists($field, $translations)) {
$result[$blockId][$field] = $translations[$field];
}
}
return $result;
}
public function afterGetMeta(DataProvider $subject, array $result): array
{
$blockId = (int)$this->request->getParam('block_id');
$storeId = (int)$this->request->getParam('store');
if ($blockId <= 0 || $storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($blockId, $storeId);
foreach (self::FIELDS as $field => $fieldset) {
$config = &$result[$fieldset]['children'][$field]['arguments']['data']['config'];
$config['service'] = ['template' => 'ui/form/element/helper/service'];
$config['disabled'] = !array_key_exists($field, $translations);
unset($config);
}
return $result;
}
private function getTranslations(int $blockId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$blockId,
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
array_keys(self::FIELDS)
);
}
}
@@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Controller\Adminhtml\Block\Save;
use Magento\Framework\App\Cache\Manager as CacheManager;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
class CmsBlockSave
{
private const FIELDS = [
'title',
'content',
];
public function __construct(
private readonly Http $request,
private readonly CmsTranslationRepository $translationRepository,
private readonly RedirectFactory $redirectFactory,
private readonly ManagerInterface $messageManager,
private readonly CacheManager $cacheManager
) {
}
public function aroundExecute(Save $subject, callable $proceed): mixed
{
$data = $this->request->getPostValue();
$storeId = (int)($data['translation_store_id'] ?? 0);
if ($storeId <= 0) {
return $proceed();
}
$blockId = (int)($data['block_id'] ?? $this->request->getParam('block_id'));
if ($blockId <= 0) {
$this->messageManager->addErrorMessage(__('The CMS block no longer exists.'));
return $this->redirectToIndex();
}
try {
$useDefault = is_array($data['use_default'] ?? null) ? $data['use_default'] : [];
$defaultFields = [];
$translations = [];
foreach (self::FIELDS as $field) {
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
continue;
}
if (array_key_exists($field, $data)) {
$translations[$field] = (string)$data[$field];
}
}
$this->translationRepository->deleteTranslations(
$blockId,
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
$defaultFields
);
$this->translationRepository->saveTranslations(
$blockId,
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
$translations
);
$this->cacheManager->clean(['full_page', 'block_html']);
$this->messageManager->addSuccessMessage(__('You saved the block translation.'));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the block translation: %1', $exception->getMessage())
);
}
return $this->redirectToEdit($blockId, $storeId);
}
private function redirectToEdit(int $blockId, int $storeId): Redirect
{
return $this->redirectFactory->create()->setPath(
'cms/block/edit',
['block_id' => $blockId, 'store' => $storeId]
);
}
private function redirectToIndex(): Redirect
{
return $this->redirectFactory->create()->setPath('cms/block/index');
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Page\DataProvider;
use Magento\Framework\App\RequestInterface;
class CmsPageDataProvider
{
private const FIELDSETS = [
'title' => 'general',
'content_heading' => 'content',
'content' => 'content',
'meta_title' => 'search_engine_optimisation',
'meta_keywords' => 'search_engine_optimisation',
'meta_description' => 'search_engine_optimisation',
];
public function __construct(
private readonly RequestInterface $request,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterGetData(DataProvider $subject, array $result): array
{
$pageId = (int)$this->request->getParam('page_id');
$storeId = (int)$this->request->getParam('store');
if ($pageId <= 0 || !isset($result[$pageId])) {
return $result;
}
$result[$pageId]['translation_store_id'] = $storeId;
if ($storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($pageId, $storeId);
foreach (array_keys(self::FIELDSETS) as $field) {
if (array_key_exists($field, $translations)) {
$result[$pageId][$field] = $translations[$field];
}
}
return $result;
}
public function afterGetMeta(DataProvider $subject, array $result): array
{
$pageId = (int)$this->request->getParam('page_id');
$storeId = (int)$this->request->getParam('store');
if ($pageId <= 0 || $storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($pageId, $storeId);
foreach (self::FIELDSETS as $field => $fieldset) {
$config = &$result[$fieldset]['children'][$field]['arguments']['data']['config'];
$config['service'] = ['template' => 'ui/form/element/helper/service'];
$config['disabled'] = !array_key_exists($field, $translations);
unset($config);
}
return $result;
}
private function getTranslations(int $pageId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$pageId,
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
array_keys(self::FIELDSETS)
);
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Controller\Adminhtml\Page\Save;
use Magento\Framework\App\Cache\Manager as CacheManager;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
class CmsPageSave
{
private const FIELDS = [
'title',
'content_heading',
'content',
'meta_title',
'meta_keywords',
'meta_description',
];
public function __construct(
private readonly Http $request,
private readonly CmsTranslationRepository $translationRepository,
private readonly RedirectFactory $redirectFactory,
private readonly ManagerInterface $messageManager,
private readonly CacheManager $cacheManager
) {
}
public function aroundExecute(Save $subject, callable $proceed): mixed
{
$data = $this->request->getPostValue();
$storeId = (int)($data['translation_store_id'] ?? 0);
if ($storeId <= 0) {
return $proceed();
}
$pageId = (int)($data['page_id'] ?? $this->request->getParam('page_id'));
if ($pageId <= 0) {
$this->messageManager->addErrorMessage(__('The CMS page no longer exists.'));
return $this->redirectToIndex();
}
try {
$useDefault = is_array($data['use_default'] ?? null) ? $data['use_default'] : [];
$defaultFields = [];
$translations = [];
foreach (self::FIELDS as $field) {
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
continue;
}
if (array_key_exists($field, $data)) {
$translations[$field] = (string)$data[$field];
}
}
$this->translationRepository->deleteTranslations(
$pageId,
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
$defaultFields
);
$this->translationRepository->saveTranslations(
$pageId,
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
$translations
);
$this->cacheManager->clean(['full_page', 'block_html']);
$this->messageManager->addSuccessMessage(__('You saved the page translation.'));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the page translation: %1', $exception->getMessage())
);
}
return $this->redirectToEdit($pageId, $storeId);
}
private function redirectToEdit(int $pageId, int $storeId): Redirect
{
return $this->redirectFactory->create()->setPath(
'cms/page/edit',
['page_id' => $pageId, 'store' => $storeId]
);
}
private function redirectToIndex(): Redirect
{
return $this->redirectFactory->create()->setPath('cms/page/index');
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\Wiki\Block\Adminhtml\Category\EditBlock;
use Magento\Framework\AuthorizationInterface;
class WikiCategoryTranslateButton
{
public function __construct(private readonly AuthorizationInterface $authorization)
{
}
public function afterToHtml(EditBlock $subject, string $html): string
{
$category = $subject->getCategory();
if (!$category->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
return $html;
}
return $this->addButton($subject, $html, 'wiki_category', (int)$category->getId());
}
private function addButton(EditBlock $subject, string $html, string $entityType, int $entityId): string
{
$config = [
'entityType' => $entityType,
'entityId' => $entityId,
'sourceStoreId' => 0,
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$button = sprintf(
'<button class="action-secondary" type="button" onclick="require([&quot;Esun_MultiLocaleTranslation/js/translate-modal&quot;],function(openModal){openModal(%s);});"><span>%s</span></button>',
htmlspecialchars((string)json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES),
__('Translate')
);
return preg_replace('/(<div class="page-actions">)/', '$1' . $button, $html, 1) ?? $html;
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\Wiki\Block\Adminhtml\Homepage\EditBlock;
use Magento\Framework\AuthorizationInterface;
class WikiHomepageTranslateButton
{
public function __construct(private readonly AuthorizationInterface $authorization)
{
}
public function afterToHtml(EditBlock $subject, string $html): string
{
$homepage = $subject->getHomepage();
if (!$homepage->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
return $html;
}
$config = [
'entityType' => 'wiki_homepage',
'entityId' => (int)$homepage->getId(),
'sourceStoreId' => 0,
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$button = sprintf(
'<button class="action-secondary" type="button" onclick="require([&quot;Esun_MultiLocaleTranslation/js/translate-modal&quot;],function(openModal){openModal(%s);});"><span>%s</span></button>',
htmlspecialchars((string)json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES),
__('Translate')
);
return preg_replace('/(<div class="page-actions">)/', '$1' . $button, $html, 1) ?? $html;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Blog;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Mageplaza\Blog\Model\Post;
class ApplyStoreTranslationToPost
{
public function __construct(
private readonly BlogPostTranslationApplier $translationApplier,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterLoad(Post $subject, Post $result): Post
{
$this->translationApplier->apply($result);
return $result;
}
public function afterDelete(Post $subject, Post $result): Post
{
$this->translationRepository->clearEntityTranslations(
(int)$subject->getId(),
CmsTranslationRepository::ENTITY_BLOG_POST
);
return $result;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Blog;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
class ApplyStoreTranslationToPostCollection
{
private bool $applying = false;
public function __construct(
private readonly BlogPostTranslationApplier $translationApplier
) {
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems());
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Cms;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Block;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class ApplyStoreTranslationToBlock
{
private const FIELDS = [
'title',
'content'
];
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function afterLoad(Block $subject, Block $result): Block
{
if (!$this->isFrontendArea()) {
return $result;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0 || !$subject->getId()) {
return $result;
}
$translations = $this->translationRepository->getTranslations(
(int)$subject->getId(),
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
self::FIELDS
);
foreach (self::FIELDS as $field) {
if (!array_key_exists($field, $translations)) {
continue;
}
$subject->setData($field, $translations[$field]);
}
return $result;
}
private function isFrontendArea(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Cms;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Page;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class ApplyStoreTranslationToPage
{
private const FIELDS = [
'title',
'content_heading',
'content',
'meta_title',
'meta_keywords',
'meta_description',
'layout_update_xml',
'custom_layout_update_xml',
'page_layout',
'custom_theme',
'custom_root_template',
'sort_order',
];
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function afterLoad(Page $subject, Page $result): Page
{
if (!$this->isFrontendArea()) {
return $result;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0 || !$subject->getId()) {
return $result;
}
$translations = $this->translationRepository->getTranslations(
(int)$subject->getId(),
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
self::FIELDS
);
foreach (self::FIELDS as $field) {
if (!array_key_exists($field, $translations)) {
continue;
}
$subject->setData($field, $translations[$field]);
}
return $result;
}
private function isFrontendArea(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\ResourceModel\Category\Collection;
class ApplyWikiCategoryCollectionTranslation
{
private bool $applying = false;
public function __construct(private readonly WikiTranslationApplier $translationApplier)
{
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems());
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\ResourceModel\Homepage\Collection;
class ApplyWikiHomepageCollectionTranslation
{
private bool $applying = false;
public function __construct(private readonly WikiTranslationApplier $translationApplier)
{
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems(), true);
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\Homepage;
class ApplyWikiTranslation
{
public function __construct(
private readonly WikiTranslationApplier $translationApplier,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterLoad(Category $subject, Category $result): Category
{
$this->translationApplier->apply($result);
return $result;
}
public function afterDelete(Category $subject, Category $result): Category
{
$this->translationRepository->clearEntityTranslations(
(int)$subject->getId(),
$subject instanceof Homepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY
);
return $result;
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\Wiki\Block\Wiki\View;
use Esun\Wiki\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Store\Model\StoreManagerInterface;
class SearchTranslatedCategories
{
/** @var array<int, array> */
private array $results = [];
public function __construct(
private readonly CollectionFactory $collectionFactory,
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager
) {
}
public function aroundGetSearchResults(View $subject, callable $proceed): array
{
$query = $subject->getSearchQuery();
$storeId = (int)$this->storeManager->getStore()->getId();
if ($query === '' || $storeId <= 0) {
return $proceed();
}
$cacheKey = spl_object_id($subject);
if (isset($this->results[$cacheKey])) {
return $this->results[$cacheKey];
}
$connection = $this->resourceConnection->getConnection();
$pattern = '%' . $query . '%';
$translatedIds = array_map('intval', $connection->fetchCol(
$connection->select()
->distinct(true)
->from($this->resourceConnection->getTableName('esun_localetranslation_cms'), ['entity_id'])
->where('entity_type = ?', CmsTranslationRepository::ENTITY_WIKI_CATEGORY)
->where('store_id = ?', $storeId)
->where('field_name IN (?)', ['title', 'summary', 'content'])
->where('translated_value LIKE ?', $pattern)
));
if ($translatedIds === []) {
return $this->results[$cacheKey] = $proceed();
}
$collection = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($storeId)
->addTreeOrder();
$adapter = $collection->getConnection();
$collection->getSelect()->where(implode(' OR ', [
$adapter->quoteInto('main_table.title LIKE ?', $pattern),
$adapter->quoteInto('main_table.slug LIKE ?', $pattern),
$adapter->quoteInto('main_table.summary LIKE ?', $pattern),
$adapter->quoteInto('main_table.content LIKE ?', $pattern),
$adapter->quoteInto('main_table.category_id IN (?)', $translatedIds),
]));
$results = [];
foreach ($collection as $category) {
if (!$subject->isCategoryClickable($category)) {
continue;
}
$results[] = $category;
if (count($results) >= 20) {
break;
}
}
return $this->results[$cacheKey] = $results;
}
}
@@ -0,0 +1,155 @@
## Esun MultiLocaleTranslation
这个模块是按你当前需求实现的“低复杂度维护”版:
- 后台支持“按实体弹窗翻译” Product / Category / CMS Page / CMS Block / Mageplaza Blog Post / Wiki Category / Wiki Homepage
- CMS Page / Block / Mageplaza Blog Post / Wiki 使用同一套实体 ID,不复制实体,使用额外翻译表进行同 ID 覆盖
- CMS Page / Block 编辑页提供 `Scope` 切换;切换 Store View 后原生表单直接显示并保存该语言内容
- 先保留现有 Magento 的多语言/多网站机制,只加一个轻量可控的翻译入口
- 支持 DeepL 和 Google Cloud Translation Advanced v3 自动翻译,弹窗可选择 Provider
### 已安装文件说明
- `Block/Adminhtml/*`:后台翻译弹窗和按钮入口
- `Controller/Adminhtml/Translation/*`:获取字段 / 保存字段 API
- `Model/Entity/*`:不同实体的可翻译字段映射
- `Plugin/Cms/*`:前台渲染时把 CMS 翻译覆盖到同一 page/block id
- `Plugin/Blog/*`:前台详情页和博客列表按 Store View 覆盖 Blog Post 译文
- `etc/db_schema.xml`:新增表 `esun_localetranslation_cms`
### 安装与生效(开发/测试环境)
```bash
php bin/magento module:enable Esun_MultiLocaleTranslation
php bin/magento setup:upgrade
php bin/magento cache:flush
```
清缓存后,检查后台:
1. 打开任意商品编辑页、分类编辑页、CMS 页面/区块、Mageplaza Blog Post 或 Wiki 编辑页
2. 页面右上角看到 `Translate` 按钮
3. 点击后在当前编辑页面打开弹窗,并自动加载除源语言外的全部 Store View
4. 也可以重新选择部分 Store View,再点 `Load Fields` 按需加载
5. 点 `Save All Translations`,一次保存当前显示的全部目标 Store View
自动翻译会按 Store View 逐个处理,并显示当前 Store、总进度、成功数和失败数。单个 Store 翻译失败不会中断其余 Store,结束后可根据提示检查失败项。
### 跳过不需要翻译的字段
配置位置:
`Stores > Configuration > Esun > Multi-Locale Translation > General > Skipped Fields`
- 默认不选择任何字段,继续翻译程序当前支持的全部字段。
- 选择后的字段不会出现在翻译弹窗中,也不会进入批量翻译 API 请求、翻译日志或目标 Store View 保存流程。
- 支持分别配置 Category、Product、CMS Page 和 CMS Block 的现有可翻译字段。
- 保存配置并刷新已打开的编辑页面后生效;此设置不会删除以前已保存的译文。
### 业务规则(和你需求一致)
- `entity_type`
- `product`:商品
- `category`:分类
- `cms_page`:CMS 页面(同 `page_id`)
- `cms_block`:CMS 区块(同 `block_id`)
- 源语言:`source_store_id`
- 可能是 `0`(默认值)
- 弹窗会显示 `Default Store View` 或具体 Store View 名称
- 目标语言:`target_store_id`
- 不能与源语言相同
### CMS Page / Block 原生 Scope
- 默认 Scope 编辑原始 `cms_page` / `cms_block` 数据。
- 选择具体 Store View 后,原生表单显示该 Store View 的翻译内容。
- CMS Page 可翻译 `title`、`content_heading`、`content` 和 SEO 字段。
- CMS Block 可翻译 `title` 和 `content`;`identifier`、启用状态和 Store View 分配继续共用默认数据。
- Mageplaza Blog Post 可翻译 `name`、`short_description`、`post_content` 和 SEO 字段;`url_key`、图片、作者、日期、状态、Store View 和关联数据继续共用默认数据。
- Blog Post 的 `url_key` 永不进入人工翻译、自动翻译或队列保存,因此所有语言继续使用原始 URL。
- Wiki Category 可翻译 `title`、`summary`、`content` 和 SEO 字段;`slug`、`custom_url_path`、层级、状态和功能开关继续共用默认数据。
- Wiki Homepage 可翻译 `title`、`content` 和 SEO 字段;前台会按当前 Store View 读取对应译文。
- 勾选 `Use Default Value` 后保存,会删除该字段的 Store View 翻译并继承默认值。
- Store View Scope 下保存不会修改默认 Page / Block,也不会创建新的 Page / Block ID。
### 数据库(CMS 同ID翻译)
表名:`esun_localetranslation_cms`
字段含义:
- `entity_type`: `page|block|blog_post`
- `entity_id`: CMS page_id、block_id 或 Mageplaza post_id(同站点复用同 ID)
- `store_id`: 目标 Store View ID
- `field_name`: title/content/...
- `translated_value`: 翻译结果
### Google V3 自动翻译
配置位置:
`Stores > Configuration > Esun > Multi-Locale Translation > Google Cloud Translation`
1. 在 Google Cloud 项目启用 Cloud Translation API。
2. 创建有 Cloud Translation 权限的 Service Account,并下载 JSON Key。
3. 后台上传 Service Account JSON、选择 Location,然后启用 Google 翻译。
4. 翻译弹窗点击 `Google Auto Translate`,检查结果后再点击保存。
JSON Key 会被验证并保存在 Magento `var/esun/multilocale_translation/google/` 私有目录,不会放入 `pub/media` 或输出到浏览器。Google 的所有 HTML 字段都会先提取可见文字、分批翻译,再按原位置写回;Page Builder HTML、CSS、JavaScript 和标签结构不会发送给 Google。
Default Scope 使用后台配置的源语言(默认 `en`);从具体 Store View 翻译时使用该 Store View 的 Locale。
不使用术语表时 Location 选择 `global`。使用 Google Glossary 时填写 Glossary ID,并把 Location 改为 `us-central1`。
后续增加其他 Provider 时,只需实现 `TranslationProviderInterface` 并注入 `ProviderPool`,实体保存逻辑无需变更。人工填写流程继续保留。
### DeepL 自动翻译
配置位置同样在:
`Stores > Configuration > Esun > Multi-Locale Translation`
1. General 中把 Default Translation Provider 设置为 `DeepL`。
2. 在 DeepL Translation API 中启用 DeepL。
3. API Free 选择 `https://api-free.deepl.com/v2/translate`;API Pro 选择 `https://api.deepl.com/v2/translate`。
4. 填写 DeepL API Key。Key 使用 Magento 加密配置保存,不会输出到浏览器。
5. 翻译弹窗选择 DeepL 并点击 `Auto Translate`。
DeepL 的所有 HTML 字段都会先提取可见文字、分批翻译,再按原位置写回。HTML 标签、注释、CSS、JavaScript、Magento 指令和编码后的代码块不会发送给 DeepL;文字片段使用 `tag_handling=html` 和 v2 标签算法。
### Translation API Log
后台菜单 `Esun > Translation API Log` 显示每个自动翻译字段的调用记录,包括:
- Provider、成功/失败状态、实体类型、实体 ID 和字段名
- 源/目标 Store View 与语言
- 原文、译文、字符数和调用时间
- 失败请求的错误信息(在 Columns 中打开 `Error` 列)
日志支持筛选、分页、列显示控制和批量删除。日志仅记录点击 `Auto Translate` 产生的结果;人工编辑和最终保存不重复记录。
HTML 字段的日志只保存和显示实际送去翻译的可见文字,不记录 Page Builder HTML、CSS、JavaScript 等结构代码;历史日志在列表显示时也会自动提取可见文字。
`Clear All Logs` 可在二次确认后一次清空全部 Translation API Log,不会删除队列或已保存译文。
### Batch Translation Queue
- Product、CMS Page、CMS Block、Mageplaza Blog Post 列表的批量操作中选择 `Add to Translation Queue`。
- Category 可在原生分类树中勾选多个节点后点击 `Translate Selected`,也可以在后台 `Esun > Batch Translation` 输入多个 Category ID。
- Wiki Category 可在 Wiki 分类列表勾选多个节点后点击 `Add Selected to Translation Queue`,再选择目标 Store Views 和翻译服务加入队列。
- 在确认页面选择 Source Store View、一个或多个 Target Store View 和 Provider。
- 每个“实体 × Target Store View”生成一条数据库队列任务;重复的 Pending/Processing 任务会跳过。
- Magento Cron 默认每分钟最多处理 10 条任务,并在约 50 秒后停止领取新任务;当前任务会执行完成。可在 `Esun > Translation Management > Configuration > Translation Queue` 调整(数量 1–50,时间 10–300 秒)。
- `Esun > Translation Queue` 查看 Pending、Processing、Success、Failed、执行次数和错误信息。
- Failed 任务可批量 `Retry Failed`,非 Processing 任务可批量删除。
- `Clear All Queue` 可在二次确认后清空所有队列记录;已被 Cron 取走并正在执行的任务无法中断,仍可能完成翻译写入。
队列依赖 Magento Cron。服务器必须已经配置每分钟执行:
```bash
* * * * * php /path/to/magento/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /path/to/magento/var/log/magento.cron.log
```
开发环境可手动执行一次 `php bin/magento cron:run`;若服务器没有 Magento Cron,任务会保持 Pending,不会丢失。
### 注意
- 插件不会改写现有 URL 或多站点主站映射逻辑
- 不建议与已有同名翻译覆盖逻辑并行写入 CMS 同字段,避免内容互相覆盖
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use PHPUnit\Framework\TestCase;
class BlogPostFieldsTest extends TestCase
{
public function testUrlKeyIsNotTranslatable(): void
{
self::assertNotContains('url_key', BlogPostFields::codes());
}
public function testReadsDefaultMetaValueFromMageplazaStoreJson(): void
{
self::assertSame(
'English meta title',
BlogPostFields::baseValue('meta_title', '{"0":"English meta title","2":"French title"}')
);
self::assertSame('Plain value', BlogPostFields::baseValue('meta_title', 'Plain value'));
self::assertSame('<p>Content</p>', BlogPostFields::baseValue('post_content', '<p>Content</p>'));
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Framework\App\State;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\Blog\Model\Post;
use PHPUnit\Framework\TestCase;
class BlogPostTranslationApplierTest extends TestCase
{
public function testAppliesCurrentStoreTranslationToPost(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
self::isType('array')
)->willReturn(['name' => 'Deutscher Titel']);
$post = $this->createMock(Post::class);
$post->method('getId')->willReturn(1101);
$post->expects(self::once())->method('setData')->with('name', 'Deutscher Titel')->willReturnSelf();
$this->createApplier($repository)->apply($post);
}
public function testAppliesCollectionTranslationsWithOneRepositoryQuery(): void
{
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('getTranslationsForEntities')->with(
[1101, 1102],
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
self::isType('array')
)->willReturn([
1101 => ['name' => 'Erster Titel'],
1102 => ['name' => 'Zweiter Titel'],
]);
$first = $this->createMock(Post::class);
$first->method('getId')->willReturn(1101);
$first->expects(self::once())->method('setData')->with('name', 'Erster Titel')->willReturnSelf();
$second = $this->createMock(Post::class);
$second->method('getId')->willReturn(1102);
$second->expects(self::once())->method('setData')->with('name', 'Zweiter Titel')->willReturnSelf();
$this->createApplier($repository)->applyMany([$first, $second]);
}
private function createApplier(CmsTranslationRepository $repository): BlogPostTranslationApplier
{
$store = $this->createMock(StoreInterface::class);
$store->method('getId')->willReturn(3);
$storeManager = $this->createMock(StoreManagerInterface::class);
$storeManager->method('getStore')->willReturn($store);
$state = $this->createMock(State::class);
$state->method('getAreaCode')->willReturn('frontend');
return new BlogPostTranslationApplier($repository, $storeManager, $state);
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Config;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Magento\Framework\App\Config\ScopeConfigInterface;
use PHPUnit\Framework\TestCase;
class SkippedFieldsTest extends TestCase
{
public function testRecognizesConfiguredFields(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturn(
'product.meta_keyword, cms_page.meta_keywords'
);
$config = new SkippedFields($scopeConfig);
self::assertTrue($config->isSkipped('product', 'meta_keyword'));
self::assertTrue($config->isSkipped('cms_page', 'meta_keywords'));
self::assertFalse($config->isSkipped('product', 'name'));
}
public function testEmptyConfigurationSkipsNothing(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturn(null);
self::assertFalse((new SkippedFields($scopeConfig))->isSkipped('category', 'name'));
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\BlogPostEntity;
use Mageplaza\Blog\Model\Post;
use Mageplaza\Blog\Model\PostFactory;
use PHPUnit\Framework\TestCase;
class BlogPostEntityTest extends TestCase
{
public function testLoadsSourceTranslationAndTargetFallbackFromSamePost(): void
{
$post = $this->createMock(Post::class);
$post->method('load')->with(1101)->willReturnSelf();
$post->method('getId')->willReturn(1101);
$post->method('getData')->willReturnMap([
['name', null, 'English title'],
['short_description', null, 'English summary'],
['post_content', null, '<p>English content</p>'],
['meta_title', null, 'English meta title'],
['meta_keywords', null, 'English keywords'],
['meta_description', null, 'English meta description'],
]);
$postFactory = $this->createMock(PostFactory::class);
$postFactory->method('create')->willReturn($post);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::exactly(2))->method('getTranslations')->willReturnOnConsecutiveCalls(
['name' => 'Titre français'],
[]
);
$skippedFields = $this->createMock(SkippedFields::class);
$fields = (new BlogPostEntity($postFactory, $repository, $skippedFields))->getFields(1101, 2, 3);
self::assertSame('Titre français', $fields[0]['source_value']);
self::assertSame('English title', $fields[0]['target_value']);
self::assertTrue($fields[0]['use_default']);
self::assertSame('post_content', $fields[2]['code']);
self::assertTrue($fields[2]['is_html']);
}
public function testSavesTranslationAndDeletesUseDefaultFields(): void
{
$post = $this->createMock(Post::class);
$post->method('load')->with(1101)->willReturnSelf();
$post->method('getId')->willReturn(1101);
$postFactory = $this->createMock(PostFactory::class);
$postFactory->method('create')->willReturn($post);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('deleteTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
['meta_keywords']
);
$repository->expects(self::once())->method('saveTranslations')->with(
1101,
3,
CmsTranslationRepository::ENTITY_BLOG_POST,
['name' => 'Deutscher Titel']
);
$entity = new BlogPostEntity(
$postFactory,
$repository,
$this->createMock(SkippedFields::class)
);
$entity->apply(
1101,
3,
['name' => 'Deutscher Titel', 'url_key' => 'must-not-be-saved'],
['meta_keywords' => true]
);
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\CategoryEntity;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\ResourceModel\Category as CategoryResource;
use PHPUnit\Framework\TestCase;
class CategoryEntityTest extends TestCase
{
public function testSavesTranslationUsingTargetStoreScope(): void
{
$category = $this->createMock(Category::class);
$category->expects(self::once())->method('setStoreId')->with(24)->willReturnSelf();
$category->expects(self::once())->method('load')->with(21)->willReturnSelf();
$category->method('getId')->willReturn(21);
$category->expects(self::once())->method('setData')->with('name', 'Résine très vendue')->willReturnSelf();
$categoryFactory = $this->createMock(CategoryFactory::class);
$categoryFactory->method('create')->willReturn($category);
$categoryResource = $this->createMock(CategoryResource::class);
$categoryResource->expects(self::once())->method('save')->with($category);
$entity = new CategoryEntity(
$categoryFactory,
$categoryResource,
$this->createMock(ScopeOverriddenValue::class),
$this->createMock(SkippedFields::class)
);
$entity->apply(21, 24, ['name' => 'Résine très vendue']);
}
public function testDoesNotSaveAConfiguredSkippedField(): void
{
$category = $this->createMock(Category::class);
$category->method('setStoreId')->willReturnSelf();
$category->method('load')->willReturnSelf();
$category->method('getId')->willReturn(21);
$category->expects(self::never())->method('setData');
$categoryFactory = $this->createMock(CategoryFactory::class);
$categoryFactory->method('create')->willReturn($category);
$categoryResource = $this->createMock(CategoryResource::class);
$categoryResource->expects(self::once())->method('save')->with($category);
$skippedFields = $this->createMock(SkippedFields::class);
$skippedFields->method('isSkipped')->willReturnCallback(
static fn(string $entityType, string $field): bool => $entityType === 'category' && $field === 'name'
);
$entity = new CategoryEntity(
$categoryFactory,
$categoryResource,
$this->createMock(ScopeOverriddenValue::class),
$skippedFields
);
$entity->apply(21, 24, ['name' => 'Should not be saved']);
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\WikiCategoryEntity;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\CategoryFactory;
use PHPUnit\Framework\TestCase;
class WikiCategoryEntityTest extends TestCase
{
public function testLoadsOnlyWikiContentFieldsAndNeverUrlFields(): void
{
$category = $this->createMock(Category::class);
$category->method('load')->with(12)->willReturnSelf();
$category->method('getId')->willReturn(12);
$category->method('getData')->willReturnMap([
['title', null, 'English title'],
['summary', null, 'English summary'],
['content', null, '<p>English content</p>'],
['meta_title', null, 'English meta'],
['meta_description', null, 'English description'],
['meta_keywords', null, 'English keywords'],
]);
$factory = $this->createMock(CategoryFactory::class);
$factory->method('create')->willReturn($category);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::exactly(2))->method('getTranslations')->willReturnOnConsecutiveCalls(
['title' => 'Deutscher Titel'],
[]
);
$fields = (new WikiCategoryEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->getFields(12, 16, 17);
self::assertSame('Deutscher Titel', $fields[0]['source_value']);
self::assertSame('English title', $fields[0]['target_value']);
self::assertSame('content', $fields[2]['code']);
self::assertTrue($fields[2]['is_html']);
self::assertNotContains('slug', array_column($fields, 'code'));
self::assertNotContains('custom_url_path', array_column($fields, 'code'));
}
public function testApplyFiltersUnknownAndUrlFields(): void
{
$category = $this->createMock(Category::class);
$category->method('load')->with(12)->willReturnSelf();
$category->method('getId')->willReturn(12);
$factory = $this->createMock(CategoryFactory::class);
$factory->method('create')->willReturn($category);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->expects(self::once())->method('saveTranslations')->with(
12,
17,
CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
['title' => 'Translated title']
);
(new WikiCategoryEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->apply(12, 17, [
'title' => 'Translated title',
'slug' => 'must-not-save',
'custom_url_path' => 'must-not-save',
]);
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\Entity\WikiHomepageEntity;
use Esun\Wiki\Model\Homepage;
use Esun\Wiki\Model\ResourceModel\Homepage\Collection;
use Esun\Wiki\Model\ResourceModel\Homepage\CollectionFactory;
use PHPUnit\Framework\TestCase;
class WikiHomepageEntityTest extends TestCase
{
public function testLoadsHomepageTranslationFields(): void
{
$homepage = $this->createMock(Homepage::class);
$homepage->method('getId')->willReturn(1);
$homepage->method('getData')->willReturnMap([
['title', null, 'Wiki'],
['content', null, '<p>Wiki content</p>'],
['meta_title', null, 'Wiki meta'],
['meta_description', null, 'Wiki description'],
['meta_keywords', null, 'Wiki keywords'],
]);
$collection = $this->createMock(Collection::class);
$collection->method('addFieldToFilter')->willReturnSelf();
$collection->method('setPageSize')->willReturnSelf();
$collection->method('getFirstItem')->willReturn($homepage);
$factory = $this->createMock(CollectionFactory::class);
$factory->method('create')->willReturn($collection);
$repository = $this->createMock(CmsTranslationRepository::class);
$repository->method('getTranslations')->willReturn([]);
$fields = (new WikiHomepageEntity(
$factory,
$repository,
$this->createMock(SkippedFields::class)
))->getFields(1, 0, 16);
self::assertSame(['title', 'content', 'meta_title', 'meta_description', 'meta_keywords'],
array_column($fields, 'code'));
self::assertTrue($fields[1]['is_html']);
}
}
@@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Html;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use PHPUnit\Framework\TestCase;
class TranslatableTextExtractorTest extends TestCase
{
private TranslatableTextExtractor $extractor;
protected function setUp(): void
{
$this->extractor = new TranslatableTextExtractor();
}
public function testExtractsVisibleTextWithoutChangingMarkupOffsets(): void
{
$html = '<div data-title="Keep"> Hello <strong>world</strong>! </div>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(['Hello', 'world', '!'], array_column($fragments, 'text'));
foreach ($fragments as $fragment) {
self::assertSame(
$fragment['text'],
substr($html, $fragment['offset'], $fragment['length'])
);
}
}
public function testIgnoresCodeAndEncodedMarkup(): void
{
$html = '<style>.hero { display:block }</style>'
. '<p>Translate me</p>'
. '<div>&lt;style&gt;.box { margin: 0 }&lt;/style&gt;</div>'
. '<script>console.log("Do not translate")</script>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(['Translate me'], array_column($fragments, 'text'));
}
public function testExtractsVisibleTextFromPageBuilderEncodedHtml(): void
{
$html = '<div data-content-type="html" data-element="main">'
. '&lt;div class="payment-label"&gt;Payment Methods&lt;/div&gt;'
. '&lt;style&gt;.hidden { display:none }&lt;/style&gt;'
. '&lt;p&gt;Secure Checkout &amp; Payment&lt;/p&gt;'
. '&lt;img src="{{media url=payment.png}}" alt="" /&gt;'
. '</div>';
$fragments = $this->extractor->extract($html, 30000);
self::assertSame(
['Payment Methods', 'Secure Checkout &amp; Payment'],
array_column($fragments, 'text')
);
foreach ($fragments as $fragment) {
self::assertSame(
$fragment['text'],
substr($html, $fragment['offset'], $fragment['length'])
);
}
}
public function testEncodedHtmlTextCanBeReplacedWithoutChangingPageBuilderMarkup(): void
{
$html = '<div data-content-type="html">&lt;p class="message"&gt;Original Text&lt;/p&gt;</div>';
$fragments = $this->extractor->extract($html, 30000);
$fragment = $fragments[0];
$translated = substr($html, 0, $fragment['offset'])
. 'Translated Text'
. substr($html, $fragment['offset'] + $fragment['length']);
self::assertSame(
'<div data-content-type="html">&lt;p class="message"&gt;Translated Text&lt;/p&gt;</div>',
$translated
);
}
public function testSplitsLargeTextAtUtf8SafeBoundaries(): void
{
$html = '<p>' . str_repeat('多语言内容 ', 20) . '</p>';
$fragments = $this->extractor->extract($html, 40);
self::assertGreaterThan(1, count($fragments));
self::assertSame(trim(str_repeat('多语言内容 ', 20)), implode('', array_column($fragments, 'text')));
foreach ($fragments as $fragment) {
self::assertLessThanOrEqual(40, strlen($fragment['text']));
self::assertSame(1, preg_match('//u', $fragment['text']));
}
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model;
use Esun\MultiLocaleTranslation\Model\LogCleaner;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use PHPUnit\Framework\TestCase;
class LogCleanerTest extends TestCase
{
public function testClearsEveryTranslationLogRecord(): void
{
$connection = $this->createMock(AdapterInterface::class);
$connection->expects(self::once())
->method('delete')
->with('esun_localetranslation_log')
->willReturn(504);
$resourceConnection = $this->createMock(ResourceConnection::class);
$resourceConnection->method('getConnection')->willReturn($connection);
$resourceConnection->method('getTableName')->willReturn('esun_localetranslation_log');
self::assertSame(504, (new LogCleaner($resourceConnection))->clearAll());
}
}
@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Provider;
use Esun\MultiLocaleTranslation\Model\Google\AccessToken;
use Esun\MultiLocaleTranslation\Model\Google\Credentials;
use Esun\MultiLocaleTranslation\Model\Html\TranslatableTextExtractor;
use Esun\MultiLocaleTranslation\Model\Provider\Google;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\HTTP\Client\CurlFactory;
use PHPUnit\Framework\TestCase;
class GoogleTest extends TestCase
{
public function testTranslatesOnlyVisibleHtmlTextAndRestoresMarkup(): void
{
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('isSetFlag')->willReturn(true);
$scopeConfig->method('getValue')->willReturnCallback(
static function (string $path): string {
return match (true) {
str_ends_with($path, '/location') => 'global',
str_ends_with($path, '/timeout') => '30',
default => '',
};
}
);
$credentials = $this->createMock(Credentials::class);
$credentials->method('get')->willReturn(['project_id' => 'test-project']);
$accessToken = $this->createMock(AccessToken::class);
$accessToken->method('get')->willReturn('test-token');
$curl = $this->createMock(Curl::class);
$curl->expects(self::once())->method('post')->with(
self::stringContains('test-project/locations/global:translateText'),
self::callback(static function (string $payload): bool {
$request = json_decode($payload, true);
return $request['contents'] === ['Hello', 'world']
&& $request['mimeType'] === 'text/html'
&& !str_contains($payload, '<style>')
&& !str_contains($payload, '<strong>');
})
);
$curl->method('getStatus')->willReturn(200);
$curl->method('getBody')->willReturn(json_encode([
'translations' => [
['translatedText' => 'Bonjour'],
['translatedText' => 'monde'],
],
], JSON_THROW_ON_ERROR));
$curlFactory = $this->createMock(CurlFactory::class);
$curlFactory->method('create')->willReturn($curl);
$provider = new Google(
$scopeConfig,
$credentials,
$accessToken,
$curlFactory,
new TranslatableTextExtractor()
);
$source = '<style>.hidden{display:none}</style><p>Hello <strong>world</strong></p>';
$result = $provider->translate([
'content' => ['value' => $source, 'is_html' => true],
], 'en', 'fr');
self::assertSame(
'<style>.hidden{display:none}</style><p>Bonjour <strong>monde</strong></p>',
$result['content']
);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Test\Unit\Model\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\CronConsumer;
use Esun\MultiLocaleTranslation\Model\Queue\QueueProcessor;
use Magento\Framework\App\Config\ScopeConfigInterface;
use PHPUnit\Framework\TestCase;
class CronConsumerTest extends TestCase
{
public function testUsesConfiguredQueueLimits(): void
{
$processor = $this->createMock(QueueProcessor::class);
$processor->expects(self::once())->method('process')->with(10, 50);
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static fn(string $path): string => str_ends_with($path, 'tasks_per_run') ? '10' : '50'
);
(new CronConsumer($processor, $scopeConfig))->execute();
}
public function testClampsQueueLimitsToAllowedRange(): void
{
$processor = $this->createMock(QueueProcessor::class);
$processor->expects(self::once())->method('process')->with(50, 10);
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('getValue')->willReturnCallback(
static fn(string $path): string => str_ends_with($path, 'tasks_per_run') ? '999' : '1'
);
(new CronConsumer($processor, $scopeConfig))->execute();
}
}

Some files were not shown because too many files have changed in this diff Show More