Files
esun3d/app/code/Esun/MultiLocaleTranslation/Controller/Adminhtml/Translation/Apply.php
T
2026-09-15 10:35:56 +08:00

76 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Controller\Adminhtml\Translation;
use Esun\MultiLocaleTranslation\Model\EntityPool;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
class Apply extends Action
{
public const ADMIN_RESOURCE = 'Esun_MultiLocaleTranslation::translation';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly EntityPool $entityPool
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
try {
$entityType = (string)$this->getRequest()->getParam('entity_type', '');
$entityId = (int)$this->getRequest()->getParam('entity_id');
$targetStoreId = (int)$this->getRequest()->getParam('target_store_id');
$sourceStoreId = (int)$this->getRequest()->getParam('source_store_id');
$fields = $this->getRequest()->getParam('fields', []);
$useDefault = $this->getRequest()->getParam('use_default', []);
if ($entityType === '' || $entityId <= 0 || $targetStoreId <= 0
|| !is_array($fields) || !is_array($useDefault)
) {
throw new \InvalidArgumentException(__('Invalid request.'));
}
if ($sourceStoreId > 0 && $sourceStoreId === $targetStoreId) {
throw new \InvalidArgumentException(__('Target store view cannot be same as source store view.'));
}
$this->assertBlogPermission($entityType);
$entity = $this->entityPool->get($entityType);
$entity->apply($entityId, $targetStoreId, $fields, $useDefault);
return $result->setData([
'success' => true,
'message' => __('Translation saved.')
]);
} catch (\Throwable $exception) {
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
private function assertBlogPermission(string $entityType): void
{
if ($entityType === 'blog_post'
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate blog posts.'));
}
if (in_array($entityType, ['wiki_category', 'wiki_homepage'], true)
&& !$this->_authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
throw new \InvalidArgumentException((string)__('You are not allowed to translate Wiki content.'));
}
}
}