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

66 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Translation\Controller\Adminhtml\Translate;
use Esun\Translation\Model\Translation\ApplyService;
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 = 'Magento_Backend::admin';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly ApplyService $applyService
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
try {
$type = (string)$this->getRequest()->getParam('entity_type', 'product');
$entityId = (int)$this->getRequest()->getParam('entity_id', $this->getRequest()->getParam('product_id'));
$language = (string)$this->getRequest()->getParam('language');
$fields = $this->getRequest()->getParam('fields', []);
if ($entityId <= 0) {
throw new \InvalidArgumentException('A valid content ID is required.');
}
if (!is_array($fields)) {
throw new \InvalidArgumentException('Fields payload is invalid.');
}
$response = $this->applyService->apply($type, $entityId, $language, $fields);
return $result->setData(array_merge(['success' => true], $response));
} catch (\Throwable $exception) {
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
protected function _isAllowed(): bool
{
return $this->_authorization->isAllowed($this->getApplyResource());
}
private function getApplyResource(): string
{
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
'cms_page' => 'Esun_Translation::apply_cms_page_translation',
'cms_block' => 'Esun_Translation::apply_cms_block_translation',
default => 'Esun_Translation::apply_product_translation',
};
}
}