Files
2026-09-15 10:35:56 +08:00

77 lines
3.0 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Queue;
use Esun\MultiLocaleTranslation\Model\Queue\QueueManager;
use Esun\MultiLocaleTranslation\Model\Queue\SelectionRegistry;
use Magento\Backend\App\Action;
use Magento\Framework\Controller\Result\Redirect;
class Add extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::queue_add';
public function __construct(
Action\Context $context,
private readonly QueueManager $queueManager,
private readonly SelectionRegistry $selectionRegistry
) {
parent::__construct($context);
}
public function execute(): Redirect
{
$token = (string)$this->getRequest()->getParam('token');
try {
$selection = $this->selectionRegistry->get($token);
$entityType = $selection['entity_type'] ?? (string)$this->getRequest()->getParam('entity_type');
$this->assertBlogPermission((string)$entityType);
$entityIds = $selection['entity_ids'] ?? $this->parseIds(
(string)$this->getRequest()->getParam('entity_ids')
);
$result = $this->queueManager->enqueue(
$entityType,
$entityIds,
(int)$this->getRequest()->getParam('source_store_id'),
(array)$this->getRequest()->getParam('target_store_ids', []),
(string)$this->getRequest()->getParam('provider')
);
$this->selectionRegistry->clear($token);
$this->messageManager->addSuccessMessage(
__('%1 task(s) added to the translation queue. %2 duplicate active task(s) skipped.',
$result['created'],
$result['skipped'])
);
return $this->resultRedirectFactory->create()->setPath('*/*/index', [
'batch_id' => $result['batch_id'],
]);
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage($exception->getMessage());
return $this->resultRedirectFactory->create()->setPath('*/*/new', ['token' => $token]);
}
}
/** @return int[] */
private function parseIds(string $value): array
{
$parts = preg_split('/[^0-9]+/', $value, -1, PREG_SPLIT_NO_EMPTY);
return array_values(array_unique(array_map('intval', $parts ?: [])));
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}