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

70 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Translation\Controller\Adminhtml\Translate;
use Esun\Translation\Model\Entity\EntityPool;
use Esun\Translation\Model\StoreView\LanguageGroupProvider;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
class Fields extends Action
{
public const ADMIN_RESOURCE = 'Magento_Backend::admin';
public function __construct(
Context $context,
private readonly JsonFactory $jsonFactory,
private readonly EntityPool $entityPool,
private readonly LanguageGroupProvider $languageGroupProvider
) {
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');
if ($entityId <= 0) {
throw new \InvalidArgumentException('A valid content ID is required.');
}
$group = $this->languageGroupProvider->getGroup($language);
if (!$group) {
throw new \InvalidArgumentException('Language group was not found.');
}
return $result->setData([
'success' => true,
'fields' => $this->entityPool->get($type)->getFields($entityId, $group->getStoreIds()),
]);
} catch (\Throwable $exception) {
return $result->setData([
'success' => false,
'message' => $exception->getMessage(),
]);
}
}
protected function _isAllowed(): bool
{
return $this->_authorization->isAllowed($this->getTranslateResource());
}
private function getTranslateResource(): string
{
return match ((string)$this->getRequest()->getParam('entity_type', 'product')) {
'cms_page' => 'Esun_Translation::translate_cms_page',
'cms_block' => 'Esun_Translation::translate_cms_block',
default => 'Esun_Translation::translate_product',
};
}
}