init
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Ai;
|
||||
|
||||
use Esun\Translation\Api\TranslatorInterface;
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Framework\HTTP\Client\Curl;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class OpenAiCompatibleTranslator implements TranslatorInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly Curl $curl,
|
||||
private readonly Json $json,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function translate(array $texts, string $sourceLocale, string $targetLocale): array
|
||||
{
|
||||
$texts = array_filter($texts, static fn (string $value): bool => trim($value) !== '');
|
||||
if ($texts === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$apiKey = $this->config->getApiKey();
|
||||
$baseUrl = $this->config->getApiBaseUrl();
|
||||
$model = $this->config->getModel();
|
||||
|
||||
if ($apiKey === '' || $baseUrl === '' || $model === '') {
|
||||
throw new \RuntimeException('AI provider is not configured.');
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'model' => $model,
|
||||
'temperature' => $this->config->getTemperature(),
|
||||
'response_format' => $this->buildResponseFormat(array_keys($texts)),
|
||||
'messages' => [
|
||||
[
|
||||
'role' => 'system',
|
||||
'content' => 'You translate Magento ecommerce content. Return only JSON that conforms to the supplied schema. The translations object must contain every input key exactly once. Do not rename keys. Preserve placeholders like __ESUN_TRANSLATION_PRESERVE_0__ exactly.',
|
||||
],
|
||||
[
|
||||
'role' => 'user',
|
||||
'content' => $this->json->serialize([
|
||||
'source_locale' => $sourceLocale,
|
||||
'target_locale' => $targetLocale,
|
||||
'required_keys' => array_keys($texts),
|
||||
'texts' => $texts,
|
||||
]),
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$this->curl->setTimeout($this->config->getTimeout());
|
||||
$this->curl->addHeader('Content-Type', 'application/json');
|
||||
$this->curl->addHeader('Authorization', 'Bearer ' . $apiKey);
|
||||
$this->curl->post($baseUrl . '/chat/completions', $this->json->serialize($payload));
|
||||
$status = $this->curl->getStatus();
|
||||
$body = $this->curl->getBody();
|
||||
|
||||
if ($status < 200 || $status >= 300) {
|
||||
if ($this->shouldRetryWithoutJsonSchema($status, $body)) {
|
||||
$payload['response_format'] = ['type' => 'json_object'];
|
||||
$payload['messages'][0]['content'] = 'You translate Magento ecommerce content. Return only JSON in this exact shape: {"translations":{"field_key":"translated text"}}. The translations object must contain every input key exactly once. Do not rename keys. Do not add commentary. Preserve placeholders like __ESUN_TRANSLATION_PRESERVE_0__ exactly.';
|
||||
$this->curl->post($baseUrl . '/chat/completions', $this->json->serialize($payload));
|
||||
$status = $this->curl->getStatus();
|
||||
$body = $this->curl->getBody();
|
||||
}
|
||||
|
||||
if ($status < 200 || $status >= 300) {
|
||||
throw new \RuntimeException(sprintf('AI provider returned HTTP %d.', $status));
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->json->unserialize($body);
|
||||
$content = $response['choices'][0]['message']['content'] ?? null;
|
||||
if (!is_string($content) || trim($content) === '') {
|
||||
throw new \RuntimeException('AI provider response did not contain translated content.');
|
||||
}
|
||||
|
||||
$translated = $this->json->unserialize($content);
|
||||
if (!is_array($translated)) {
|
||||
throw new \RuntimeException('AI provider response content is not a JSON object.');
|
||||
}
|
||||
|
||||
return $this->normalizeTranslations($texts, $translated);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->error('Esun Translation AI request failed.', ['exception' => $exception]);
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $sourceTexts
|
||||
* @param array<mixed> $translated
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function normalizeTranslations(array $sourceTexts, array $translated): array
|
||||
{
|
||||
if (!isset($translated['translations']) || !is_array($translated['translations'])) {
|
||||
throw new \RuntimeException('AI response must be a JSON object with a "translations" object.');
|
||||
}
|
||||
|
||||
$translations = $translated['translations'];
|
||||
$result = [];
|
||||
foreach ($sourceTexts as $key => $sourceText) {
|
||||
if (!array_key_exists($key, $translations) || !is_scalar($translations[$key])) {
|
||||
throw new \RuntimeException(sprintf('AI response is missing translation key "%s".', $key));
|
||||
}
|
||||
$result[$key] = (string)$translations[$key];
|
||||
}
|
||||
|
||||
$unexpectedKeys = array_diff(array_keys($translations), array_keys($sourceTexts));
|
||||
if ($unexpectedKeys !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'AI response contains unexpected translation key "%s".',
|
||||
(string)reset($unexpectedKeys)
|
||||
));
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $keys
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function buildResponseFormat(array $keys): array
|
||||
{
|
||||
$properties = [];
|
||||
foreach ($keys as $key) {
|
||||
$properties[$key] = [
|
||||
'type' => 'string',
|
||||
'description' => 'Translated text for input key ' . $key,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'type' => 'json_schema',
|
||||
'json_schema' => [
|
||||
'name' => 'product_translation_response',
|
||||
'strict' => true,
|
||||
'schema' => [
|
||||
'type' => 'object',
|
||||
'additionalProperties' => false,
|
||||
'required' => ['translations'],
|
||||
'properties' => [
|
||||
'translations' => [
|
||||
'type' => 'object',
|
||||
'additionalProperties' => false,
|
||||
'required' => $keys,
|
||||
'properties' => $properties,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private function shouldRetryWithoutJsonSchema(int $status, string $body): bool
|
||||
{
|
||||
if ($status !== 400 && $status !== 422) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lowerBody = strtolower($body);
|
||||
|
||||
return str_contains($lowerBody, 'json_schema')
|
||||
|| str_contains($lowerBody, 'response_format')
|
||||
|| str_contains($lowerBody, 'unsupported');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Ai;
|
||||
|
||||
class ProtectedTextProcessor
|
||||
{
|
||||
/**
|
||||
* @return array{0: string, 1: array<string, string>}
|
||||
*/
|
||||
public function protect(string $text): array
|
||||
{
|
||||
$placeholders = [];
|
||||
$index = 0;
|
||||
$protected = preg_replace_callback(
|
||||
'/\{\{.*?\}\}|https?:\/\/[^\s<>"\']+|%[0-9]*\$?[a-zA-Z]|\{[A-Za-z0-9_.-]+\}/',
|
||||
function (array $matches) use (&$placeholders, &$index): string {
|
||||
$token = '__ESUN_TRANSLATION_PRESERVE_' . $index++ . '__';
|
||||
$placeholders[$token] = $matches[0];
|
||||
|
||||
return $token;
|
||||
},
|
||||
$text
|
||||
);
|
||||
|
||||
return [$protected ?? $text, $placeholders];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $placeholders
|
||||
*/
|
||||
public function restore(string $text, array $placeholders): string
|
||||
{
|
||||
foreach ($placeholders as $token => $original) {
|
||||
if (!str_contains($text, $token)) {
|
||||
throw new \RuntimeException(sprintf('Protected token "%s" was not preserved by AI response.', $token));
|
||||
}
|
||||
}
|
||||
|
||||
return strtr($text, $placeholders);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Encryption\EncryptorInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
private const XML_PATH_ENABLED = 'esun_translation/general/enabled';
|
||||
private const XML_PATH_SOURCE_LOCALE = 'esun_translation/general/source_locale';
|
||||
private const XML_PATH_SOURCE_STORE_ID = 'esun_translation/general/source_store_id';
|
||||
private const XML_PATH_ATTRIBUTES = 'esun_translation/general/translatable_attributes';
|
||||
private const XML_PATH_LANGUAGE_GROUPS = 'esun_translation/general/language_groups';
|
||||
private const XML_PATH_API_BASE_URL = 'esun_translation/ai/api_base_url';
|
||||
private const XML_PATH_API_KEY = 'esun_translation/ai/api_key';
|
||||
private const XML_PATH_MODEL = 'esun_translation/ai/model';
|
||||
private const XML_PATH_TEMPERATURE = 'esun_translation/ai/temperature';
|
||||
private const XML_PATH_TIMEOUT = 'esun_translation/ai/timeout';
|
||||
|
||||
public function __construct(
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly EncryptorInterface $encryptor
|
||||
) {
|
||||
}
|
||||
|
||||
public function isEnabled(): bool
|
||||
{
|
||||
return $this->scopeConfig->isSetFlag(self::XML_PATH_ENABLED, ScopeInterface::SCOPE_STORE);
|
||||
}
|
||||
|
||||
public function getSourceLocale(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_SOURCE_LOCALE)) ?: 'en';
|
||||
}
|
||||
|
||||
public function getSourceStoreId(): int
|
||||
{
|
||||
return max(0, (int)$this->scopeConfig->getValue(self::XML_PATH_SOURCE_STORE_ID));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getTranslatableAttributeCodes(): array
|
||||
{
|
||||
$raw = (string)$this->scopeConfig->getValue(self::XML_PATH_ATTRIBUTES);
|
||||
$codes = preg_split('/[\s,]+/', $raw) ?: [];
|
||||
|
||||
return array_values(array_unique(array_filter(array_map('trim', $codes))));
|
||||
}
|
||||
|
||||
public function getLanguageGroupsConfig(): string
|
||||
{
|
||||
return (string)$this->scopeConfig->getValue(self::XML_PATH_LANGUAGE_GROUPS);
|
||||
}
|
||||
|
||||
public function getApiBaseUrl(): string
|
||||
{
|
||||
return rtrim((string)$this->scopeConfig->getValue(self::XML_PATH_API_BASE_URL), '/');
|
||||
}
|
||||
|
||||
public function getApiKey(): string
|
||||
{
|
||||
$value = (string)$this->scopeConfig->getValue(self::XML_PATH_API_KEY);
|
||||
|
||||
return $value !== '' ? $this->encryptor->decrypt($value) : '';
|
||||
}
|
||||
|
||||
public function getModel(): string
|
||||
{
|
||||
return trim((string)$this->scopeConfig->getValue(self::XML_PATH_MODEL));
|
||||
}
|
||||
|
||||
public function getTemperature(): float
|
||||
{
|
||||
return (float)$this->scopeConfig->getValue(self::XML_PATH_TEMPERATURE);
|
||||
}
|
||||
|
||||
public function getTimeout(): int
|
||||
{
|
||||
return max(1, (int)$this->scopeConfig->getValue(self::XML_PATH_TIMEOUT));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class Provider implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'openai_compatible', 'label' => __('OpenAI Compatible')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Cms\Api\BlockRepositoryInterface;
|
||||
use Magento\Cms\Model\Block;
|
||||
use Magento\Cms\Model\BlockFactory;
|
||||
use Magento\Cms\Model\ResourceModel\Block\CollectionFactory;
|
||||
|
||||
class CmsBlockEntity implements TranslatableEntityInterface
|
||||
{
|
||||
private const FIELDS = [
|
||||
'title' => ['label' => 'Block Title', 'is_html' => false],
|
||||
'content' => ['label' => 'Content', 'is_html' => true],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly BlockRepositoryInterface $blockRepository,
|
||||
private readonly BlockFactory $blockFactory,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'cms_block';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'CMS Block';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->getBlock($entityId)->getTitle();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'cms/block/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'block_id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
$source = $this->getBlock($entityId);
|
||||
$target = $this->findTargetBlock($source, $targetStoreIds);
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $code => $metadata) {
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => $metadata['label'],
|
||||
'source_value' => (string)($source->getData($code) ?? ''),
|
||||
'target_value' => $target ? (string)($target->getData($code) ?? '') : '',
|
||||
'is_html' => (bool)$metadata['is_html'],
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$source = $this->getBlock($entityId);
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable CMS block fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
$created = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$block = $this->findByIdentifierAndStore((string)$source->getIdentifier(), $storeId);
|
||||
if ($block) {
|
||||
$this->applyFields($block, $fields);
|
||||
$block->setStores([$storeId]);
|
||||
$this->blockRepository->save($block);
|
||||
$updated++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array(0, array_map('intval', (array)$source->getStores()), true)) {
|
||||
throw new \RuntimeException(
|
||||
'This CMS block is assigned to All Store Views. Create store-specific blocks first or remove All Store Views before creating localized copies.'
|
||||
);
|
||||
}
|
||||
|
||||
$copy = $this->cloneForStore($source, $storeId);
|
||||
$this->applyFields($copy, $fields);
|
||||
$this->blockRepository->save($copy);
|
||||
$created++;
|
||||
}
|
||||
|
||||
if ($updated + $created === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'created' => $created,
|
||||
'message' => __('CMS block translations applied. Updated: %1, Created: %2.', $updated, $created)->render(),
|
||||
];
|
||||
}
|
||||
|
||||
private function getBlock(int $blockId): Block
|
||||
{
|
||||
$block = $this->blockRepository->getById($blockId);
|
||||
if (!$block instanceof Block) {
|
||||
throw new \RuntimeException('CMS block model type is not supported.');
|
||||
}
|
||||
|
||||
return $block;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
*/
|
||||
private function findTargetBlock(Block $source, array $targetStoreIds): ?Block
|
||||
{
|
||||
foreach ($targetStoreIds as $storeId) {
|
||||
$block = $this->findByIdentifierAndStore((string)$source->getIdentifier(), (int)$storeId);
|
||||
if ($block && (int)$block->getId() !== (int)$source->getId()) {
|
||||
return $block;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function findByIdentifierAndStore(string $identifier, int $storeId): ?Block
|
||||
{
|
||||
if ($storeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$collection = $this->collectionFactory->create();
|
||||
$collection->addFieldToFilter('identifier', $identifier);
|
||||
$collection->addStoreFilter($storeId, false);
|
||||
$collection->setPageSize(1);
|
||||
$block = $collection->getFirstItem();
|
||||
|
||||
return $block && $block->getId() ? $block : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!isset(self::FIELDS[$code])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ((bool)self::FIELDS[$code]['is_html']) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
private function applyFields(Block $block, array $fields): void
|
||||
{
|
||||
foreach ($fields as $code => $value) {
|
||||
$block->setData($code, $value);
|
||||
}
|
||||
}
|
||||
|
||||
private function cloneForStore(Block $source, int $storeId): Block
|
||||
{
|
||||
$data = $source->getData();
|
||||
unset($data['block_id'], $data['store_id']);
|
||||
|
||||
$copy = $this->blockFactory->create();
|
||||
$copy->setData($data);
|
||||
$copy->setStores([$storeId]);
|
||||
$copy->setData('store_id', [$storeId]);
|
||||
|
||||
return $copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Cms\Api\PageRepositoryInterface;
|
||||
use Magento\Cms\Model\Page;
|
||||
use Magento\Cms\Model\PageFactory;
|
||||
use Magento\Cms\Model\ResourceModel\Page\CollectionFactory;
|
||||
|
||||
class CmsPageEntity implements TranslatableEntityInterface
|
||||
{
|
||||
private const FIELDS = [
|
||||
'title' => ['label' => 'Page Title', 'is_html' => false],
|
||||
'content_heading' => ['label' => 'Content Heading', 'is_html' => false],
|
||||
'content' => ['label' => 'Content', 'is_html' => true],
|
||||
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
|
||||
'meta_keywords' => ['label' => 'Meta Keywords', 'is_html' => false],
|
||||
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly PageRepositoryInterface $pageRepository,
|
||||
private readonly PageFactory $pageFactory,
|
||||
private readonly CollectionFactory $collectionFactory,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'cms_page';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'CMS Page';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->getPage($entityId)->getTitle();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'cms/page/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'page_id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
$source = $this->getPage($entityId);
|
||||
$target = $this->findTargetPage($source, $targetStoreIds);
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $code => $metadata) {
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => $metadata['label'],
|
||||
'source_value' => (string)($source->getData($code) ?? ''),
|
||||
'target_value' => $target ? (string)($target->getData($code) ?? '') : '',
|
||||
'is_html' => (bool)$metadata['is_html'],
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$source = $this->getPage($entityId);
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable CMS page fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
$created = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$page = $this->findByIdentifierAndStore((string)$source->getIdentifier(), $storeId);
|
||||
if ($page) {
|
||||
$this->applyFields($page, $fields);
|
||||
$page->setStores([$storeId]);
|
||||
$this->pageRepository->save($page);
|
||||
$updated++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array(0, array_map('intval', (array)$source->getStores()), true)) {
|
||||
throw new \RuntimeException(
|
||||
'This CMS page is assigned to All Store Views. Create store-specific pages first or remove All Store Views before creating localized copies.'
|
||||
);
|
||||
}
|
||||
|
||||
$copy = $this->cloneForStore($source, $storeId);
|
||||
$this->applyFields($copy, $fields);
|
||||
$this->pageRepository->save($copy);
|
||||
$created++;
|
||||
}
|
||||
|
||||
if ($updated + $created === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'created' => $created,
|
||||
'message' => __('CMS page translations applied. Updated: %1, Created: %2.', $updated, $created)->render(),
|
||||
];
|
||||
}
|
||||
|
||||
private function getPage(int $pageId): Page
|
||||
{
|
||||
$page = $this->pageRepository->getById($pageId);
|
||||
if (!$page instanceof Page) {
|
||||
throw new \RuntimeException('CMS page model type is not supported.');
|
||||
}
|
||||
|
||||
return $page;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
*/
|
||||
private function findTargetPage(Page $source, array $targetStoreIds): ?Page
|
||||
{
|
||||
foreach ($targetStoreIds as $storeId) {
|
||||
$page = $this->findByIdentifierAndStore((string)$source->getIdentifier(), (int)$storeId);
|
||||
if ($page && (int)$page->getId() !== (int)$source->getId()) {
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function findByIdentifierAndStore(string $identifier, int $storeId): ?Page
|
||||
{
|
||||
if ($storeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$collection = $this->collectionFactory->create();
|
||||
$collection->addFieldToFilter('identifier', $identifier);
|
||||
$collection->addStoreFilter($storeId, false);
|
||||
$collection->setPageSize(1);
|
||||
$page = $collection->getFirstItem();
|
||||
|
||||
return $page && $page->getId() ? $page : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!isset(self::FIELDS[$code])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ((bool)self::FIELDS[$code]['is_html']) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
private function applyFields(Page $page, array $fields): void
|
||||
{
|
||||
foreach ($fields as $code => $value) {
|
||||
$page->setData($code, $value);
|
||||
}
|
||||
}
|
||||
|
||||
private function cloneForStore(Page $source, int $storeId): Page
|
||||
{
|
||||
$data = $source->getData();
|
||||
unset($data['page_id'], $data['store_id']);
|
||||
|
||||
$copy = $this->pageFactory->create();
|
||||
$copy->setData($data);
|
||||
$copy->setStores([$storeId]);
|
||||
$copy->setData('store_id', [$storeId]);
|
||||
|
||||
return $copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
|
||||
class EntityPool
|
||||
{
|
||||
/**
|
||||
* @param array<string, TranslatableEntityInterface> $entities
|
||||
*/
|
||||
public function __construct(private readonly array $entities = [])
|
||||
{
|
||||
}
|
||||
|
||||
public function get(string $type): TranslatableEntityInterface
|
||||
{
|
||||
if (!isset($this->entities[$type])) {
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported translation entity type "%s".', $type));
|
||||
}
|
||||
|
||||
return $this->entities[$type];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getTypes(): array
|
||||
{
|
||||
return array_keys($this->entities);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Entity;
|
||||
|
||||
use Esun\Translation\Api\TranslatableEntityInterface;
|
||||
use Esun\Translation\Model\Product\TranslatableFieldProvider;
|
||||
use Esun\Translation\Model\Product\TranslationApplier;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
|
||||
class ProductEntity implements TranslatableEntityInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly TranslatableFieldProvider $fieldProvider,
|
||||
private readonly TranslationApplier $translationApplier
|
||||
) {
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return 'product';
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return 'Product';
|
||||
}
|
||||
|
||||
public function getTitle(int $entityId): string
|
||||
{
|
||||
return (string)$this->productRepository->getById($entityId)->getName();
|
||||
}
|
||||
|
||||
public function getEditUrlPath(): string
|
||||
{
|
||||
return 'catalog/product/edit';
|
||||
}
|
||||
|
||||
public function getEditIdParam(): string
|
||||
{
|
||||
return 'id';
|
||||
}
|
||||
|
||||
public function getFields(int $entityId, array $targetStoreIds = []): array
|
||||
{
|
||||
return $this->fieldProvider->getFields($entityId, $targetStoreIds);
|
||||
}
|
||||
|
||||
public function apply(int $entityId, array $storeIds, array $fields): array
|
||||
{
|
||||
$updated = $this->translationApplier->apply($entityId, $storeIds, $fields);
|
||||
|
||||
return [
|
||||
'updated' => $updated,
|
||||
'message' => __('Translations applied to %1 store view(s).', $updated)->render(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMText;
|
||||
|
||||
class HtmlFragment
|
||||
{
|
||||
/**
|
||||
* @param array<string, DOMText> $textNodes
|
||||
* @param array<string, string> $texts
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly DOMDocument $document,
|
||||
private readonly DOMElement $root,
|
||||
private readonly array $textNodes,
|
||||
private readonly array $texts,
|
||||
private readonly array $directivePlaceholders = []
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function getTexts(): array
|
||||
{
|
||||
return $this->texts;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $translations
|
||||
*/
|
||||
public function applyTranslations(array $translations): string
|
||||
{
|
||||
foreach ($this->textNodes as $id => $node) {
|
||||
if (array_key_exists($id, $translations)) {
|
||||
$node->nodeValue = $translations[$id];
|
||||
}
|
||||
}
|
||||
|
||||
$html = '';
|
||||
foreach ($this->root->childNodes as $childNode) {
|
||||
$html .= $this->document->saveHTML($childNode);
|
||||
}
|
||||
|
||||
$restored = $this->directivePlaceholders === [] ? $html : strtr($html, $this->directivePlaceholders);
|
||||
|
||||
return $this->normalizeMagentoDirectiveQuotes($restored);
|
||||
}
|
||||
|
||||
private function normalizeMagentoDirectiveQuotes(string $html): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
static function (array $matches): string {
|
||||
return str_ireplace(
|
||||
['"', '"', '"', ''', ''', '''],
|
||||
['"', '"', '"', "'", "'", "'"],
|
||||
$matches[0]
|
||||
);
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMNode;
|
||||
use DOMText;
|
||||
use DOMXPath;
|
||||
|
||||
class HtmlTextExtractor
|
||||
{
|
||||
private const ROOT_ID = 'esun-translation-root';
|
||||
private const DIRECTIVE_TOKEN_PREFIX = '__ESUN_HTML_DIRECTIVE_';
|
||||
|
||||
public function extract(string $html): HtmlFragment
|
||||
{
|
||||
[$protectedHtml, $directivePlaceholders] = $this->protectMagentoDirectives($html);
|
||||
$document = $this->createDocument($protectedHtml);
|
||||
$xpath = new DOMXPath($document);
|
||||
$query = sprintf(
|
||||
'//*[@id="%s"]//text()[normalize-space(.) != "" and not(ancestor::script) and not(ancestor::style) and not(ancestor::code) and not(ancestor::pre)]',
|
||||
self::ROOT_ID
|
||||
);
|
||||
$nodes = $xpath->query($query);
|
||||
$textNodes = [];
|
||||
$texts = [];
|
||||
$index = 0;
|
||||
|
||||
if ($nodes !== false) {
|
||||
foreach ($nodes as $node) {
|
||||
if (!$node instanceof DOMText) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = $this->restoreMagentoDirectives($node->nodeValue ?? '', $directivePlaceholders);
|
||||
if (trim($text) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = 'html_' . $index++;
|
||||
$textNodes[$id] = $node;
|
||||
$texts[$id] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
$root = $document->getElementById(self::ROOT_ID);
|
||||
if (!$root) {
|
||||
throw new \RuntimeException('Unable to parse HTML fragment.');
|
||||
}
|
||||
|
||||
return new HtmlFragment($document, $root, $textNodes, $texts, $directivePlaceholders);
|
||||
}
|
||||
|
||||
private function createDocument(string $html): DOMDocument
|
||||
{
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$wrappedHtml = sprintf(
|
||||
'<?xml encoding="UTF-8"><div id="%s">%s</div>',
|
||||
self::ROOT_ID,
|
||||
$html
|
||||
);
|
||||
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
$loaded = $document->loadHTML($wrappedHtml, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
|
||||
if (!$loaded) {
|
||||
throw new \RuntimeException('Unable to parse HTML fragment.');
|
||||
}
|
||||
|
||||
return $document;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: string, 1: array<string, string>}
|
||||
*/
|
||||
private function protectMagentoDirectives(string $html): array
|
||||
{
|
||||
$placeholders = [];
|
||||
$index = 0;
|
||||
$protected = preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
function (array $matches) use (&$placeholders, &$index): string {
|
||||
$token = self::DIRECTIVE_TOKEN_PREFIX . $index++ . '__';
|
||||
$placeholders[$token] = $this->normalizeMagentoDirectiveQuotes($matches[0]);
|
||||
|
||||
return $token;
|
||||
},
|
||||
$html
|
||||
);
|
||||
|
||||
return [$protected ?? $html, $placeholders];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $placeholders
|
||||
*/
|
||||
private function restoreMagentoDirectives(string $html, array $placeholders): string
|
||||
{
|
||||
$restored = $placeholders === [] ? $html : strtr($html, $placeholders);
|
||||
|
||||
return $this->normalizeMagentoDirectiveQuotes($restored);
|
||||
}
|
||||
|
||||
private function normalizeMagentoDirectiveQuotes(string $html): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/\{\{.*?\}\}/s',
|
||||
static function (array $matches): string {
|
||||
return str_ireplace(
|
||||
['"', '"', '"', ''', ''', '''],
|
||||
['"', '"', '"', "'", "'", "'"],
|
||||
$matches[0]
|
||||
);
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Html;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
|
||||
class HtmlTranslationValidator
|
||||
{
|
||||
/**
|
||||
* DOMDocument::loadHTML uses an HTML4 parser and reports safe HTML5/Page Builder tags as invalid.
|
||||
*/
|
||||
private const HTML5_ALLOWED_INVALID_TAGS = [
|
||||
'article',
|
||||
'aside',
|
||||
'audio',
|
||||
'canvas',
|
||||
'figcaption',
|
||||
'figure',
|
||||
'footer',
|
||||
'header',
|
||||
'main',
|
||||
'nav',
|
||||
'picture',
|
||||
'section',
|
||||
'source',
|
||||
'summary',
|
||||
'template',
|
||||
'time',
|
||||
'video',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function validate(string $html): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
if (substr_count($html, '{{') !== substr_count($html, '}}')) {
|
||||
$errors[] = 'Magento directive braces are unbalanced.';
|
||||
}
|
||||
|
||||
$document = new DOMDocument('1.0', 'UTF-8');
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
$loaded = $document->loadHTML(
|
||||
'<?xml encoding="UTF-8"><div>' . $html . '</div>',
|
||||
LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED
|
||||
);
|
||||
$libxmlErrors = libxml_get_errors();
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
|
||||
if (!$loaded) {
|
||||
return ['HTML cannot be parsed.'];
|
||||
}
|
||||
|
||||
foreach ($libxmlErrors as $error) {
|
||||
if ($error->level >= LIBXML_ERR_ERROR) {
|
||||
if ($this->isAllowedHtml5InvalidTagMessage(trim($error->message))) {
|
||||
continue;
|
||||
}
|
||||
$errors[] = trim($error->message);
|
||||
}
|
||||
}
|
||||
|
||||
$xpath = new DOMXPath($document);
|
||||
foreach (['script', 'iframe', 'object', 'embed'] as $tag) {
|
||||
$nodes = $xpath->query('//' . $tag);
|
||||
if ($nodes !== false && $nodes->length > 0) {
|
||||
$errors[] = sprintf('Disallowed <%s> tag found.', $tag);
|
||||
}
|
||||
}
|
||||
|
||||
$allNodes = $xpath->query('//*');
|
||||
if ($allNodes !== false) {
|
||||
foreach ($allNodes as $node) {
|
||||
if (!$node instanceof DOMElement || !$node->hasAttributes()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($node->attributes as $attribute) {
|
||||
$name = strtolower($attribute->nodeName);
|
||||
$value = strtolower(trim($attribute->nodeValue ?? ''));
|
||||
if (str_starts_with($name, 'on')) {
|
||||
$errors[] = sprintf('Disallowed event attribute "%s" found.', $name);
|
||||
}
|
||||
if (in_array($name, ['href', 'src'], true) && str_starts_with($value, 'javascript:')) {
|
||||
$errors[] = sprintf('Disallowed javascript URL in "%s" found.', $name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique(array_filter($errors)));
|
||||
}
|
||||
|
||||
private function isAllowedHtml5InvalidTagMessage(string $message): bool
|
||||
{
|
||||
if (!preg_match('/^Tag ([a-z0-9:-]+) invalid$/i', $message, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return in_array(strtolower($matches[1]), self::HTML5_ALLOWED_INVALID_TAGS, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Product;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
|
||||
|
||||
class TranslatableFieldProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly ProductAttributeRepositoryInterface $attributeRepository
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $targetStoreIds
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function getFields(int $productId, array $targetStoreIds = []): array
|
||||
{
|
||||
$sourceProduct = $this->productRepository->getById($productId, false, $this->config->getSourceStoreId());
|
||||
$targetProduct = $targetStoreIds !== []
|
||||
? $this->productRepository->getById($productId, false, (int)reset($targetStoreIds))
|
||||
: null;
|
||||
$fields = [];
|
||||
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
$code = (string)$attribute->getAttributeCode();
|
||||
$sourceValue = (string)($sourceProduct->getData($code) ?? '');
|
||||
$targetValue = $targetProduct ? (string)($targetProduct->getData($code) ?? '') : '';
|
||||
|
||||
$fields[] = [
|
||||
'code' => $code,
|
||||
'label' => (string)$attribute->getDefaultFrontendLabel() ?: $code,
|
||||
'source_value' => $sourceValue,
|
||||
'target_value' => $targetValue,
|
||||
'is_html' => $this->isHtmlAttribute($attribute),
|
||||
];
|
||||
}
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Attribute[]
|
||||
*/
|
||||
public function getAttributes(): array
|
||||
{
|
||||
$attributes = [];
|
||||
foreach ($this->config->getTranslatableAttributeCodes() as $code) {
|
||||
try {
|
||||
$attribute = $this->attributeRepository->get($code);
|
||||
} catch (\Throwable) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$attribute instanceof Attribute) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_array((string)$attribute->getFrontendInput(), ['text', 'textarea'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($attribute->isScopeGlobal()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes[$code] = $attribute;
|
||||
}
|
||||
|
||||
return array_values($attributes);
|
||||
}
|
||||
|
||||
public function isAttributeAllowed(string $code): bool
|
||||
{
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
if ((string)$attribute->getAttributeCode() === $code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isHtmlAttributeCode(string $code): bool
|
||||
{
|
||||
foreach ($this->getAttributes() as $attribute) {
|
||||
if ((string)$attribute->getAttributeCode() === $code) {
|
||||
return $this->isHtmlAttribute($attribute);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function isHtmlAttribute(Attribute $attribute): bool
|
||||
{
|
||||
return (bool)$attribute->getIsWysiwygEnabled()
|
||||
|| in_array((string)$attribute->getAttributeCode(), ['description', 'short_description'], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Product;
|
||||
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Magento\Catalog\Api\ProductRepositoryInterface;
|
||||
|
||||
class TranslationApplier
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductRepositoryInterface $productRepository,
|
||||
private readonly TranslatableFieldProvider $fieldProvider,
|
||||
private readonly HtmlTranslationValidator $htmlValidator
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int[] $storeIds
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
public function apply(int $productId, array $storeIds, array $fields): int
|
||||
{
|
||||
$fields = $this->filterAndValidateFields($fields);
|
||||
if ($fields === []) {
|
||||
throw new \RuntimeException('No translatable fields were provided.');
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
foreach (array_unique(array_map('intval', $storeIds)) as $storeId) {
|
||||
if ($storeId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$product = $this->productRepository->getById($productId, false, $storeId);
|
||||
$product->setStoreId($storeId);
|
||||
foreach ($fields as $code => $value) {
|
||||
$product->setData($code, $value);
|
||||
}
|
||||
$this->productRepository->save($product);
|
||||
$updated++;
|
||||
}
|
||||
|
||||
if ($updated === 0) {
|
||||
throw new \RuntimeException('No valid target store views were provided.');
|
||||
}
|
||||
|
||||
return $updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function filterAndValidateFields(array $fields): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($fields as $code => $value) {
|
||||
$code = (string)$code;
|
||||
if (!$this->fieldProvider->isAttributeAllowed($code)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = (string)$value;
|
||||
if ($this->fieldProvider->isHtmlAttributeCode($code)) {
|
||||
$errors = $this->htmlValidator->validate($value);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
$result[$code] = $value;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\StoreView;
|
||||
|
||||
class LanguageGroup
|
||||
{
|
||||
/**
|
||||
* @param int[] $storeIds
|
||||
* @param string[] $storeCodes
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly string $label,
|
||||
private readonly string $targetLocale,
|
||||
private readonly array $storeIds,
|
||||
private readonly array $storeCodes
|
||||
) {
|
||||
}
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return $this->label;
|
||||
}
|
||||
|
||||
public function getTargetLocale(): string
|
||||
{
|
||||
return $this->targetLocale;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
public function getStoreIds(): array
|
||||
{
|
||||
return $this->storeIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function getStoreCodes(): array
|
||||
{
|
||||
return $this->storeCodes;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'label' => $this->label,
|
||||
'target_locale' => $this->targetLocale,
|
||||
'store_ids' => $this->storeIds,
|
||||
'store_codes' => $this->storeCodes,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\StoreView;
|
||||
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class LanguageGroupProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StoreManagerInterface $storeManager
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return LanguageGroup[]
|
||||
*/
|
||||
public function getGroups(): array
|
||||
{
|
||||
$groups = [];
|
||||
foreach ($this->storeManager->getStores(false) as $store) {
|
||||
if (!$store->isActive()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$languageCode = $this->getLanguageCode((string)$store->getCode());
|
||||
if ($languageCode === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$groups[$languageCode]['label'] = $this->getLanguageLabel($languageCode);
|
||||
$groups[$languageCode]['store_ids'][] = (int)$store->getId();
|
||||
$groups[$languageCode]['store_codes'][] = (string)$store->getCode();
|
||||
}
|
||||
|
||||
ksort($groups);
|
||||
|
||||
return array_map(
|
||||
static fn (array $group): LanguageGroup => new LanguageGroup(
|
||||
$group['label'],
|
||||
$group['target_locale'],
|
||||
$group['store_ids'],
|
||||
$group['store_codes']
|
||||
),
|
||||
array_map(
|
||||
static fn (array $group, string $languageCode): array => $group + ['target_locale' => $languageCode],
|
||||
$groups,
|
||||
array_keys($groups)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function getGroup(string $label): ?LanguageGroup
|
||||
{
|
||||
foreach ($this->getGroups() as $group) {
|
||||
if ($group->getLabel() === $label || $group->getTargetLocale() === $label) {
|
||||
return $group;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function getLanguageCode(string $storeCode): string
|
||||
{
|
||||
if (!preg_match('/^([a-z]{2,3})(?:[_-]|$)/i', $storeCode, $matches)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return strtolower($matches[1]);
|
||||
}
|
||||
|
||||
private function getLanguageLabel(string $languageCode): string
|
||||
{
|
||||
if (class_exists(\Locale::class)) {
|
||||
$label = \Locale::getDisplayLanguage($languageCode, 'en');
|
||||
if (is_string($label) && $label !== '') {
|
||||
return ucfirst($label);
|
||||
}
|
||||
}
|
||||
|
||||
return strtoupper($languageCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Translation;
|
||||
|
||||
use Esun\Translation\Model\Config;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
|
||||
class ApplyService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $fields
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function apply(string $type, int $entityId, string $languageLabel, array $fields): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
throw new \RuntimeException('Esun Translation is disabled.');
|
||||
}
|
||||
|
||||
$group = $this->languageGroupProvider->getGroup($languageLabel);
|
||||
if (!$group) {
|
||||
throw new \RuntimeException('Language group was not found.');
|
||||
}
|
||||
|
||||
return $this->entityPool->get($type)->apply($entityId, $group->getStoreIds(), $fields);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Translation\Model\Translation;
|
||||
|
||||
use Esun\Translation\Api\TranslatorInterface;
|
||||
use Esun\Translation\Model\Ai\ProtectedTextProcessor;
|
||||
use Esun\Translation\Model\Config;
|
||||
use Esun\Translation\Model\Entity\EntityPool;
|
||||
use Esun\Translation\Model\Html\HtmlTextExtractor;
|
||||
use Esun\Translation\Model\Html\HtmlTranslationValidator;
|
||||
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
|
||||
|
||||
class TranslationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly EntityPool $entityPool,
|
||||
private readonly LanguageGroupProvider $languageGroupProvider,
|
||||
private readonly HtmlTextExtractor $htmlTextExtractor,
|
||||
private readonly HtmlTranslationValidator $htmlValidator,
|
||||
private readonly ProtectedTextProcessor $protectedTextProcessor,
|
||||
private readonly TranslatorInterface $translator
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $sourceOverrides
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function translate(string $type, int $entityId, string $languageLabel, array $sourceOverrides = []): array
|
||||
{
|
||||
if (!$this->config->isEnabled()) {
|
||||
throw new \RuntimeException('Esun Translation is disabled.');
|
||||
}
|
||||
|
||||
$entity = $this->entityPool->get($type);
|
||||
$group = $this->languageGroupProvider->getGroup($languageLabel);
|
||||
if (!$group) {
|
||||
throw new \RuntimeException('Language group was not found.');
|
||||
}
|
||||
|
||||
$fields = $entity->getFields($entityId, $group->getStoreIds());
|
||||
$plainUnits = [];
|
||||
$restoreMaps = [];
|
||||
$htmlFragments = [];
|
||||
$fieldUnits = [];
|
||||
|
||||
foreach ($fields as $field) {
|
||||
$code = (string)$field['code'];
|
||||
$sourceValue = array_key_exists($code, $sourceOverrides)
|
||||
? (string)$sourceOverrides[$code]
|
||||
: (string)$field['source_value'];
|
||||
if (trim($sourceValue) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((bool)$field['is_html']) {
|
||||
$fragment = $this->htmlTextExtractor->extract($sourceValue);
|
||||
$htmlFragments[$code] = $fragment;
|
||||
foreach ($fragment->getTexts() as $nodeId => $text) {
|
||||
[$protectedText, $placeholders] = $this->protectedTextProcessor->protect($text);
|
||||
$unitId = $code . '::' . $nodeId;
|
||||
$plainUnits[$unitId] = $protectedText;
|
||||
$restoreMaps[$unitId] = $placeholders;
|
||||
$fieldUnits[$code][] = $unitId;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
[$protectedText, $placeholders] = $this->protectedTextProcessor->protect($sourceValue);
|
||||
$plainUnits[$code] = $protectedText;
|
||||
$restoreMaps[$code] = $placeholders;
|
||||
}
|
||||
|
||||
$translatedUnits = $this->translator->translate(
|
||||
$plainUnits,
|
||||
$this->config->getSourceLocale(),
|
||||
$group->getTargetLocale()
|
||||
);
|
||||
foreach ($translatedUnits as $unitId => $text) {
|
||||
$translatedUnits[$unitId] = $this->protectedTextProcessor->restore($text, $restoreMaps[$unitId] ?? []);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($fields as $field) {
|
||||
$code = (string)$field['code'];
|
||||
if (!isset($htmlFragments[$code])) {
|
||||
if (isset($translatedUnits[$code])) {
|
||||
$result[$code] = $translatedUnits[$code];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$nodeTranslations = [];
|
||||
foreach ($fieldUnits[$code] ?? [] as $unitId) {
|
||||
[, $nodeId] = explode('::', $unitId, 2);
|
||||
$nodeTranslations[$nodeId] = $translatedUnits[$unitId] ?? '';
|
||||
}
|
||||
|
||||
$translatedHtml = $htmlFragments[$code]->applyTranslations($nodeTranslations);
|
||||
$errors = $this->htmlValidator->validate($translatedHtml);
|
||||
if ($errors !== []) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
'Translated HTML for "%s" is invalid: %s',
|
||||
$code,
|
||||
implode('; ', $errors)
|
||||
));
|
||||
}
|
||||
$result[$code] = $translatedHtml;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user