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,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;
}
}
}