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