This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Registry;
use Mageplaza\Blog\Block\Adminhtml\Post\Edit;
class BlogPostEditButton
{
public function __construct(
private readonly Registry $registry,
private readonly AuthorizationInterface $authorization
) {
}
public function beforeToHtml(Edit $subject): array
{
$post = $this->registry->registry('mageplaza_blog_post');
if (!$post || !$post->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')
) {
return [];
}
$config = [
'entityType' => 'blog_post',
'entityId' => (int)$post->getId(),
'sourceStoreId' => max(0, (int)$subject->getRequest()->getParam('store')),
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$configJson = (string)json_encode(
$config,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
);
$subject->addButton('localetranslate_translate', [
'label' => __('Translate'),
'class' => 'action-secondary',
'onclick' => sprintf(
"require(['Esun_MultiLocaleTranslation/js/translate-modal'], function (openModal) { openModal(%s); });",
$configJson
),
'sort_order' => 30,
], 0, 30);
return [];
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use Esun\MultiLocaleTranslation\Model\Entity\BlogPostEntity;
use Magento\Framework\App\Cache\Manager as CacheManager;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\AuthorizationInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Message\ManagerInterface;
use Mageplaza\Blog\Controller\Adminhtml\Post\Save;
class BlogPostSave
{
public function __construct(
private readonly RequestInterface $request,
private readonly BlogPostEntity $blogPostEntity,
private readonly RedirectFactory $redirectFactory,
private readonly ManagerInterface $messageManager,
private readonly CacheManager $cacheManager,
private readonly AuthorizationInterface $authorization
) {
}
public function aroundExecute(Save $subject, callable $proceed): mixed
{
$postData = $this->request->getParam('post', []);
$postData = is_array($postData) ? $postData : [];
$storeId = max(0, (int)($postData['translation_store_id'] ?? 0));
if ($storeId <= 0) {
return $proceed();
}
$postId = (int)$this->request->getParam('id');
if ($postId <= 0) {
$this->messageManager->addErrorMessage(__('The blog post no longer exists.'));
return $this->redirectFactory->create()->setPath('mageplaza_blog/post/index');
}
if (!$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_blog')) {
$this->messageManager->addErrorMessage(__('You are not allowed to save blog translations.'));
return $this->redirectToEdit($postId, $storeId);
}
try {
$fields = array_intersect_key($postData, array_flip(BlogPostFields::codes()));
$useDefault = is_array($postData['use_default'] ?? null) ? $postData['use_default'] : [];
$this->blogPostEntity->apply($postId, $storeId, $fields, $useDefault);
$this->cacheManager->clean(['full_page', 'block_html']);
$this->messageManager->addSuccessMessage(__('You saved the blog post translation.'));
} catch (\Throwable $exception) {
$this->messageManager->addErrorMessage(
__('Something went wrong while saving the blog post translation: %1', $exception->getMessage())
);
}
return $this->redirectToEdit($postId, $storeId);
}
private function redirectToEdit(int $postId, int $storeId): Redirect
{
return $this->redirectFactory->create()->setPath(
'mageplaza_blog/post/edit',
['id' => $postId, 'store' => $storeId]
);
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Block\DataProvider;
use Magento\Framework\App\RequestInterface;
class CmsBlockDataProvider
{
private const FIELDS = [
'title' => 'general',
'content' => 'general',
];
public function __construct(
private readonly RequestInterface $request,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterGetData(DataProvider $subject, array $result): array
{
$blockId = (int)$this->request->getParam('block_id');
$storeId = (int)$this->request->getParam('store');
if ($blockId <= 0 || !isset($result[$blockId])) {
return $result;
}
$result[$blockId]['translation_store_id'] = $storeId;
if ($storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($blockId, $storeId);
foreach (array_keys(self::FIELDS) as $field) {
if (array_key_exists($field, $translations)) {
$result[$blockId][$field] = $translations[$field];
}
}
return $result;
}
public function afterGetMeta(DataProvider $subject, array $result): array
{
$blockId = (int)$this->request->getParam('block_id');
$storeId = (int)$this->request->getParam('store');
if ($blockId <= 0 || $storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($blockId, $storeId);
foreach (self::FIELDS as $field => $fieldset) {
$config = &$result[$fieldset]['children'][$field]['arguments']['data']['config'];
$config['service'] = ['template' => 'ui/form/element/helper/service'];
$config['disabled'] = !array_key_exists($field, $translations);
unset($config);
}
return $result;
}
private function getTranslations(int $blockId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$blockId,
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
array_keys(self::FIELDS)
);
}
}
@@ -0,0 +1,95 @@
<?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');
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Page\DataProvider;
use Magento\Framework\App\RequestInterface;
class CmsPageDataProvider
{
private const FIELDSETS = [
'title' => 'general',
'content_heading' => 'content',
'content' => 'content',
'meta_title' => 'search_engine_optimisation',
'meta_keywords' => 'search_engine_optimisation',
'meta_description' => 'search_engine_optimisation',
];
public function __construct(
private readonly RequestInterface $request,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterGetData(DataProvider $subject, array $result): array
{
$pageId = (int)$this->request->getParam('page_id');
$storeId = (int)$this->request->getParam('store');
if ($pageId <= 0 || !isset($result[$pageId])) {
return $result;
}
$result[$pageId]['translation_store_id'] = $storeId;
if ($storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($pageId, $storeId);
foreach (array_keys(self::FIELDSETS) as $field) {
if (array_key_exists($field, $translations)) {
$result[$pageId][$field] = $translations[$field];
}
}
return $result;
}
public function afterGetMeta(DataProvider $subject, array $result): array
{
$pageId = (int)$this->request->getParam('page_id');
$storeId = (int)$this->request->getParam('store');
if ($pageId <= 0 || $storeId <= 0) {
return $result;
}
$translations = $this->getTranslations($pageId, $storeId);
foreach (self::FIELDSETS as $field => $fieldset) {
$config = &$result[$fieldset]['children'][$field]['arguments']['data']['config'];
$config['service'] = ['template' => 'ui/form/element/helper/service'];
$config['disabled'] = !array_key_exists($field, $translations);
unset($config);
}
return $result;
}
private function getTranslations(int $pageId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$pageId,
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
array_keys(self::FIELDSETS)
);
}
}
@@ -0,0 +1,99 @@
<?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');
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\Wiki\Block\Adminhtml\Category\EditBlock;
use Magento\Framework\AuthorizationInterface;
class WikiCategoryTranslateButton
{
public function __construct(private readonly AuthorizationInterface $authorization)
{
}
public function afterToHtml(EditBlock $subject, string $html): string
{
$category = $subject->getCategory();
if (!$category->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
return $html;
}
return $this->addButton($subject, $html, 'wiki_category', (int)$category->getId());
}
private function addButton(EditBlock $subject, string $html, string $entityType, int $entityId): string
{
$config = [
'entityType' => $entityType,
'entityId' => $entityId,
'sourceStoreId' => 0,
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$button = sprintf(
'<button class="action-secondary" type="button" onclick="require([&quot;Esun_MultiLocaleTranslation/js/translate-modal&quot;],function(openModal){openModal(%s);});"><span>%s</span></button>',
htmlspecialchars((string)json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES),
__('Translate')
);
return preg_replace('/(<div class="page-actions">)/', '$1' . $button, $html, 1) ?? $html;
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Adminhtml;
use Esun\Wiki\Block\Adminhtml\Homepage\EditBlock;
use Magento\Framework\AuthorizationInterface;
class WikiHomepageTranslateButton
{
public function __construct(private readonly AuthorizationInterface $authorization)
{
}
public function afterToHtml(EditBlock $subject, string $html): string
{
$homepage = $subject->getHomepage();
if (!$homepage->getId()
|| !$this->authorization->isAllowed('Esun_MultiLocaleTranslation::translate_wiki')
) {
return $html;
}
$config = [
'entityType' => 'wiki_homepage',
'entityId' => (int)$homepage->getId(),
'sourceStoreId' => 0,
'storesUrl' => $subject->getUrl('localetranslate/translation/stores'),
'fieldsUrl' => $subject->getUrl('localetranslate/translation/fields'),
'applyUrl' => $subject->getUrl('localetranslate/translation/apply'),
'autoTranslateUrl' => $subject->getUrl('localetranslate/translation/autotranslate'),
];
$button = sprintf(
'<button class="action-secondary" type="button" onclick="require([&quot;Esun_MultiLocaleTranslation/js/translate-modal&quot;],function(openModal){openModal(%s);});"><span>%s</span></button>',
htmlspecialchars((string)json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES),
__('Translate')
);
return preg_replace('/(<div class="page-actions">)/', '$1' . $button, $html, 1) ?? $html;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Blog;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Mageplaza\Blog\Model\Post;
class ApplyStoreTranslationToPost
{
public function __construct(
private readonly BlogPostTranslationApplier $translationApplier,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterLoad(Post $subject, Post $result): Post
{
$this->translationApplier->apply($result);
return $result;
}
public function afterDelete(Post $subject, Post $result): Post
{
$this->translationRepository->clearEntityTranslations(
(int)$subject->getId(),
CmsTranslationRepository::ENTITY_BLOG_POST
);
return $result;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Blog;
use Esun\MultiLocaleTranslation\Model\BlogPostTranslationApplier;
use Mageplaza\Blog\Model\ResourceModel\Post\Collection;
class ApplyStoreTranslationToPostCollection
{
private bool $applying = false;
public function __construct(
private readonly BlogPostTranslationApplier $translationApplier
) {
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems());
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Cms;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Block;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class ApplyStoreTranslationToBlock
{
private const FIELDS = [
'title',
'content'
];
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function afterLoad(Block $subject, Block $result): Block
{
if (!$this->isFrontendArea()) {
return $result;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0 || !$subject->getId()) {
return $result;
}
$translations = $this->translationRepository->getTranslations(
(int)$subject->getId(),
$storeId,
CmsTranslationRepository::ENTITY_BLOCK,
self::FIELDS
);
foreach (self::FIELDS as $field) {
if (!array_key_exists($field, $translations)) {
continue;
}
$subject->setData($field, $translations[$field]);
}
return $result;
}
private function isFrontendArea(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Cms;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Magento\Cms\Model\Page;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class ApplyStoreTranslationToPage
{
private const FIELDS = [
'title',
'content_heading',
'content',
'meta_title',
'meta_keywords',
'meta_description',
'layout_update_xml',
'custom_layout_update_xml',
'page_layout',
'custom_theme',
'custom_root_template',
'sort_order',
];
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function afterLoad(Page $subject, Page $result): Page
{
if (!$this->isFrontendArea()) {
return $result;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0 || !$subject->getId()) {
return $result;
}
$translations = $this->translationRepository->getTranslations(
(int)$subject->getId(),
$storeId,
CmsTranslationRepository::ENTITY_PAGE,
self::FIELDS
);
foreach (self::FIELDS as $field) {
if (!array_key_exists($field, $translations)) {
continue;
}
$subject->setData($field, $translations[$field]);
}
return $result;
}
private function isFrontendArea(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\ResourceModel\Category\Collection;
class ApplyWikiCategoryCollectionTranslation
{
private bool $applying = false;
public function __construct(private readonly WikiTranslationApplier $translationApplier)
{
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems());
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\ResourceModel\Homepage\Collection;
class ApplyWikiHomepageCollectionTranslation
{
private bool $applying = false;
public function __construct(private readonly WikiTranslationApplier $translationApplier)
{
}
public function afterLoad(Collection $subject, Collection $result): Collection
{
if ($this->applying) {
return $result;
}
$this->applying = true;
try {
$this->translationApplier->applyMany($result->getItems(), true);
} finally {
$this->applying = false;
}
return $result;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\WikiTranslationApplier;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\Homepage;
class ApplyWikiTranslation
{
public function __construct(
private readonly WikiTranslationApplier $translationApplier,
private readonly CmsTranslationRepository $translationRepository
) {
}
public function afterLoad(Category $subject, Category $result): Category
{
$this->translationApplier->apply($result);
return $result;
}
public function afterDelete(Category $subject, Category $result): Category
{
$this->translationRepository->clearEntityTranslations(
(int)$subject->getId(),
$subject instanceof Homepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY
);
return $result;
}
}
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Plugin\Wiki;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\Wiki\Block\Wiki\View;
use Esun\Wiki\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Store\Model\StoreManagerInterface;
class SearchTranslatedCategories
{
/** @var array<int, array> */
private array $results = [];
public function __construct(
private readonly CollectionFactory $collectionFactory,
private readonly ResourceConnection $resourceConnection,
private readonly StoreManagerInterface $storeManager
) {
}
public function aroundGetSearchResults(View $subject, callable $proceed): array
{
$query = $subject->getSearchQuery();
$storeId = (int)$this->storeManager->getStore()->getId();
if ($query === '' || $storeId <= 0) {
return $proceed();
}
$cacheKey = spl_object_id($subject);
if (isset($this->results[$cacheKey])) {
return $this->results[$cacheKey];
}
$connection = $this->resourceConnection->getConnection();
$pattern = '%' . $query . '%';
$translatedIds = array_map('intval', $connection->fetchCol(
$connection->select()
->distinct(true)
->from($this->resourceConnection->getTableName('esun_localetranslation_cms'), ['entity_id'])
->where('entity_type = ?', CmsTranslationRepository::ENTITY_WIKI_CATEGORY)
->where('store_id = ?', $storeId)
->where('field_name IN (?)', ['title', 'summary', 'content'])
->where('translated_value LIKE ?', $pattern)
));
if ($translatedIds === []) {
return $this->results[$cacheKey] = $proceed();
}
$collection = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($storeId)
->addTreeOrder();
$adapter = $collection->getConnection();
$collection->getSelect()->where(implode(' OR ', [
$adapter->quoteInto('main_table.title LIKE ?', $pattern),
$adapter->quoteInto('main_table.slug LIKE ?', $pattern),
$adapter->quoteInto('main_table.summary LIKE ?', $pattern),
$adapter->quoteInto('main_table.content LIKE ?', $pattern),
$adapter->quoteInto('main_table.category_id IN (?)', $translatedIds),
]));
$results = [];
foreach ($collection as $category) {
if (!$subject->isCategoryClickable($category)) {
continue;
}
$results[] = $category;
if (count($results) >= 20) {
break;
}
}
return $this->results[$cacheKey] = $results;
}
}