96 lines
3.1 KiB
PHP
96 lines
3.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
|
|
|
|
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
|
|
use Magento\Cms\Controller\Adminhtml\Block\Save;
|
|
use Magento\Framework\App\Cache\Manager as CacheManager;
|
|
use Magento\Framework\App\Request\Http;
|
|
use Magento\Framework\Controller\Result\Redirect;
|
|
use Magento\Framework\Controller\Result\RedirectFactory;
|
|
use Magento\Framework\Message\ManagerInterface;
|
|
|
|
class CmsBlockSave
|
|
{
|
|
private const FIELDS = [
|
|
'title',
|
|
'content',
|
|
];
|
|
|
|
public function __construct(
|
|
private readonly Http $request,
|
|
private readonly CmsTranslationRepository $translationRepository,
|
|
private readonly RedirectFactory $redirectFactory,
|
|
private readonly ManagerInterface $messageManager,
|
|
private readonly CacheManager $cacheManager
|
|
) {
|
|
}
|
|
|
|
public function aroundExecute(Save $subject, callable $proceed): mixed
|
|
{
|
|
$data = $this->request->getPostValue();
|
|
$storeId = (int)($data['translation_store_id'] ?? 0);
|
|
if ($storeId <= 0) {
|
|
return $proceed();
|
|
}
|
|
|
|
$blockId = (int)($data['block_id'] ?? $this->request->getParam('block_id'));
|
|
if ($blockId <= 0) {
|
|
$this->messageManager->addErrorMessage(__('The CMS block no longer exists.'));
|
|
return $this->redirectToIndex();
|
|
}
|
|
|
|
try {
|
|
$useDefault = is_array($data['use_default'] ?? null) ? $data['use_default'] : [];
|
|
$defaultFields = [];
|
|
$translations = [];
|
|
|
|
foreach (self::FIELDS as $field) {
|
|
if (!empty($useDefault[$field])) {
|
|
$defaultFields[] = $field;
|
|
continue;
|
|
}
|
|
if (array_key_exists($field, $data)) {
|
|
$translations[$field] = (string)$data[$field];
|
|
}
|
|
}
|
|
|
|
$this->translationRepository->deleteTranslations(
|
|
$blockId,
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_BLOCK,
|
|
$defaultFields
|
|
);
|
|
$this->translationRepository->saveTranslations(
|
|
$blockId,
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_BLOCK,
|
|
$translations
|
|
);
|
|
$this->cacheManager->clean(['full_page', 'block_html']);
|
|
$this->messageManager->addSuccessMessage(__('You saved the block translation.'));
|
|
} catch (\Throwable $exception) {
|
|
$this->messageManager->addErrorMessage(
|
|
__('Something went wrong while saving the block translation: %1', $exception->getMessage())
|
|
);
|
|
}
|
|
|
|
return $this->redirectToEdit($blockId, $storeId);
|
|
}
|
|
|
|
private function redirectToEdit(int $blockId, int $storeId): Redirect
|
|
{
|
|
return $this->redirectFactory->create()->setPath(
|
|
'cms/block/edit',
|
|
['block_id' => $blockId, 'store' => $storeId]
|
|
);
|
|
}
|
|
|
|
private function redirectToIndex(): Redirect
|
|
{
|
|
return $this->redirectFactory->create()->setPath('cms/block/index');
|
|
}
|
|
}
|