100 lines
3.2 KiB
PHP
100 lines
3.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
|
|
|
|
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
|
|
use Magento\Cms\Controller\Adminhtml\Page\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 CmsPageSave
|
|
{
|
|
private const FIELDS = [
|
|
'title',
|
|
'content_heading',
|
|
'content',
|
|
'meta_title',
|
|
'meta_keywords',
|
|
'meta_description',
|
|
];
|
|
|
|
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();
|
|
}
|
|
|
|
$pageId = (int)($data['page_id'] ?? $this->request->getParam('page_id'));
|
|
if ($pageId <= 0) {
|
|
$this->messageManager->addErrorMessage(__('The CMS page 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(
|
|
$pageId,
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_PAGE,
|
|
$defaultFields
|
|
);
|
|
$this->translationRepository->saveTranslations(
|
|
$pageId,
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_PAGE,
|
|
$translations
|
|
);
|
|
$this->cacheManager->clean(['full_page', 'block_html']);
|
|
$this->messageManager->addSuccessMessage(__('You saved the page translation.'));
|
|
} catch (\Throwable $exception) {
|
|
$this->messageManager->addErrorMessage(
|
|
__('Something went wrong while saving the page translation: %1', $exception->getMessage())
|
|
);
|
|
}
|
|
|
|
return $this->redirectToEdit($pageId, $storeId);
|
|
}
|
|
|
|
private function redirectToEdit(int $pageId, int $storeId): Redirect
|
|
{
|
|
return $this->redirectFactory->create()->setPath(
|
|
'cms/page/edit',
|
|
['page_id' => $pageId, 'store' => $storeId]
|
|
);
|
|
}
|
|
|
|
private function redirectToIndex(): Redirect
|
|
{
|
|
return $this->redirectFactory->create()->setPath('cms/page/index');
|
|
}
|
|
}
|