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,230 @@
<?php
declare(strict_types=1);
namespace Esun\Wiki\Block\Adminhtml\Category;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\CategoryFactory;
use Esun\Wiki\Model\ResourceModel\Category\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Cms\Model\Wysiwyg\Config as WysiwygConfig;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\System\Store as SystemStore;
class EditBlock extends Template
{
private ?Category $category = null;
public function __construct(
Context $context,
private readonly CategoryFactory $categoryFactory,
private readonly CollectionFactory $collectionFactory,
private readonly FormFactory $formFactory,
private readonly WysiwygConfig $wysiwygConfig,
private readonly SystemStore $systemStore,
array $data = []
) {
parent::__construct($context, $data);
}
public function getCategory(): Category
{
if ($this->category === null) {
$this->category = $this->categoryFactory->create();
$id = (int) $this->getRequest()->getParam('id');
if ($id > 0) {
$this->category->load($id);
}
}
return $this->category;
}
public function getSaveUrl(): string
{
return $this->getUrl('esun_wiki/category/save');
}
public function getBackUrl(): string
{
return $this->getUrl('esun_wiki/category/index');
}
public function getPreviewUrl(): string
{
$id = (int) $this->getCategory()->getId();
$customPath = trim((string) $this->getCategory()->getData('custom_url_path'), '/');
$baseUrl = rtrim($this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_LINK), '/');
if ($id > 0 && $customPath !== '' && $this->getCategory()->isClickable()) {
return $baseUrl . '/' . $customPath;
}
return $id > 0 && $this->getCategory()->isClickable()
? $baseUrl . '/wiki/index/view/slug/'
. rawurlencode((string) $this->getCategory()->getData('slug')) . '/'
: '';
}
public function getContentEditorHtml(): string
{
$form = $this->formFactory->create();
$editor = $form->addField('content', 'editor', [
'name' => 'content',
'label' => __('Wiki Content'),
'title' => __('Wiki Content'),
'style' => 'width:100%;height:36em',
'required' => false,
'value' => (string) $this->getCategory()->getData('content'),
'config' => $this->wysiwygConfig->getConfig([
'add_variables' => false,
'add_widgets' => true,
'add_images' => true,
'is_pagebuilder_enabled' => true,
'pagebuilder_button' => true,
]),
]);
return $editor->getElementHtml();
}
public function getLogoUrl(): string
{
$path = trim((string) $this->getCategory()->getData('logo_path'));
if ($path === '') {
return '';
}
return rtrim($this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA), '/')
. '/' . ltrim($path, '/');
}
/**
* @return int[]
*/
public function getSelectedStoreIds(): array
{
if (!$this->getCategory()->getId()) {
return [0];
}
$storeIds = array_map('intval', (array) $this->getCategory()->getData('store_ids'));
return $storeIds ?: [0];
}
/**
* @return array<int, array{value:int|string,label:string,disabled:bool}>
*/
public function getStoreOptions(): array
{
$options = [];
foreach ($this->systemStore->getStoreValuesForForm(false, true) as $option) {
$children = $option['value'] ?? null;
if (!is_array($children)) {
$options[] = [
'value' => (int) $children,
'label' => (string) $option['label'],
'disabled' => false,
];
continue;
}
$options[] = [
'value' => '',
'label' => (string) $option['label'],
'disabled' => true,
];
foreach ($children as $child) {
$options[] = [
'value' => (int) $child['value'],
'label' => (string) $child['label'],
'disabled' => false,
];
}
}
return $options;
}
/**
* @return array<int, array{value:int,label:string}>
*/
public function getParentOptions(): array
{
$currentId = (int) $this->getCategory()->getId();
$excludedIds = $currentId > 0 ? $this->getExcludedParentIds($currentId) : [];
$nodes = [];
foreach ($this->collectionFactory->create()->addTreeOrder() as $category) {
$id = (int) $category->getId();
if (isset($excludedIds[$id])) {
continue;
}
$nodes[$id] = [
'id' => $id,
'parent_id' => (int) $category->getData('parent_id'),
'title' => (string) $category->getData('title'),
'children' => [],
];
}
foreach ($nodes as $id => $node) {
$parentId = (int) $node['parent_id'];
if ($parentId > 0 && isset($nodes[$parentId])) {
$nodes[$parentId]['children'][$id] = &$nodes[$id];
}
}
$options = [['value' => 0, 'label' => (string) __('Root Category')]];
foreach ($nodes as $id => $node) {
if ((int) $node['parent_id'] === 0 || !isset($nodes[(int) $node['parent_id']])) {
$this->appendOption($options, $node, 0);
}
}
return $options;
}
/**
* @return array<int, bool>
*/
private function getExcludedParentIds(int $currentId): array
{
$childrenByParent = [];
foreach ($this->collectionFactory->create() as $category) {
$childrenByParent[(int) $category->getData('parent_id')][] = (int) $category->getId();
}
$excluded = [$currentId => true];
$queue = $childrenByParent[$currentId] ?? [];
while ($queue) {
$id = (int) array_shift($queue);
$excluded[$id] = true;
foreach ($childrenByParent[$id] ?? [] as $childId) {
$queue[] = (int) $childId;
}
}
return $excluded;
}
/**
* @param array<int, array{value:int,label:string}> $options
* @param mixed[] $node
*/
private function appendOption(array &$options, array $node, int $depth): void
{
$options[] = [
'value' => (int) $node['id'],
'label' => str_repeat('-- ', $depth) . (string) $node['title'],
];
foreach ($node['children'] as $childNode) {
$this->appendOption($options, $childNode, $depth + 1);
}
}
}
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Esun\Wiki\Block\Adminhtml\Homepage;
use Esun\Wiki\Model\Homepage;
use Esun\Wiki\Model\HomepageFactory;
use Esun\Wiki\Model\ResourceModel\Homepage\CollectionFactory;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Cms\Model\Wysiwyg\Config as WysiwygConfig;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\UrlInterface;
class EditBlock extends Template
{
private ?Homepage $homepage = null;
public function __construct(
Context $context,
private readonly HomepageFactory $homepageFactory,
private readonly CollectionFactory $collectionFactory,
private readonly FormFactory $formFactory,
private readonly WysiwygConfig $wysiwygConfig,
array $data = []
) {
parent::__construct($context, $data);
}
public function getHomepage(): Homepage
{
if ($this->homepage === null) {
$homepage = $this->collectionFactory->create()
->setPageSize(1)
->getFirstItem();
$this->homepage = $homepage->getId() ? $homepage : $this->homepageFactory->create();
if (!$this->homepage->getData('title')) {
$this->homepage->setData('title', 'eSUN Wiki');
}
}
return $this->homepage;
}
public function getSaveUrl(): string
{
return $this->getUrl('esun_wiki/homepage/save');
}
public function getCategoriesUrl(): string
{
return $this->getUrl('esun_wiki/category/index');
}
public function getPreviewUrl(): string
{
return rtrim($this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_LINK), '/') . '/wiki';
}
public function getContentEditorHtml(): string
{
$form = $this->formFactory->create();
$editor = $form->addField('content', 'editor', [
'name' => 'content',
'label' => __('Homepage Content'),
'title' => __('Homepage Content'),
'style' => 'height:36em',
'required' => false,
'value' => (string) $this->getHomepage()->getData('content'),
'config' => $this->wysiwygConfig->getConfig([
'add_variables' => false,
'add_widgets' => true,
'add_images' => true,
'is_pagebuilder_enabled' => true,
'pagebuilder_button' => true,
]),
]);
return $editor->getElementHtml();
}
}
@@ -0,0 +1,211 @@
<?php
declare(strict_types=1);
namespace Esun\Wiki\Block\Wiki;
use Esun\Catalog\Model\ResourceModel\SpecificationBrand\CollectionFactory as BrandCollectionFactory;
use Esun\Catalog\Model\ResourceModel\SpecificationFile\CollectionFactory as FileCollectionFactory;
use Esun\Catalog\Model\ResourceModel\SpecificationImport\CollectionFactory as ImportCollectionFactory;
use Esun\Catalog\Model\SpecificationMedia;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;
class DownloadCenter extends Template
{
private ?array $items = null;
private ?array $archives = null;
private ?array $activeBrands = null;
public function __construct(
Template\Context $context,
private readonly FileCollectionFactory $fileCollectionFactory,
private readonly BrandCollectionFactory $brandCollectionFactory,
private readonly ImportCollectionFactory $importCollectionFactory,
private readonly SpecificationMedia $media,
private readonly StoreManagerInterface $storeManager,
private readonly Json $json,
array $data = []
) {
parent::__construct($context, $data);
}
public function isTargetPage(): bool
{
$parent = $this->getParentBlock();
if (!($parent instanceof View)) {
return false;
}
$category = $parent->getCurrentCategory();
return $category !== null
&& (int) $category->getData('show_download_center') === 1;
}
public function hasSpecifications(): bool
{
return $this->isTargetPage() && (bool) ($this->getItems() || $this->getArchives());
}
public function getConfigJson(): string
{
$items = $this->getItems();
$archives = $this->getArchives();
$brands = [];
$modelsByBrand = [];
foreach ($archives as $archive) {
$brandId = (string) $archive['brand_id'];
$brands[$brandId] = [
'id' => $brandId,
'name' => $archive['brand_name'],
];
}
foreach ($items as $item) {
$brandId = (string) $item['brand_id'];
$brands[$brandId] = [
'id' => $brandId,
'name' => $item['brand_name'],
];
$modelsByBrand[$brandId][$item['model_name']] = $item['model_name'];
}
foreach ($modelsByBrand as $brandId => $models) {
$modelsByBrand[$brandId] = array_values($models);
sort($modelsByBrand[$brandId], SORT_NATURAL | SORT_FLAG_CASE);
}
return $this->json->serialize([
'items' => $items,
'archives' => $archives,
'brands' => array_values($brands),
'modelsByBrand' => $modelsByBrand,
]);
}
private function getItems(): array
{
if ($this->items !== null) {
return $this->items;
}
$activeBrands = $this->getActiveBrands();
if (!$activeBrands) {
return $this->items = [];
}
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
$items = [];
$collection = $this->fileCollectionFactory->create()
->addFieldToFilter('brand_id', ['in' => array_keys($activeBrands)])
->setOrder('brand_name', 'ASC')
->setOrder('model_name', 'ASC')
->setOrder('file_name', 'ASC');
foreach ($collection as $file) {
$filePath = (string) $file->getData('file_path');
$brandId = (int) $file->getData('brand_id');
$logoPath = (string) $activeBrands[$brandId]['logo'];
$items[] = [
'id' => (int) $file->getId(),
'type' => 'file',
'brand_id' => $brandId,
'brand_name' => (string) $activeBrands[$brandId]['name'],
'brand_logo_url' => $logoPath !== '' ? $mediaBaseUrl . ltrim($logoPath, '/') : '',
'model_name' => (string) $file->getData('model_name'),
'file_name' => strtoupper((string) $file->getData('file_name')),
'file_url' => $mediaBaseUrl . ltrim($filePath, '/'),
'file_size_label' => $this->formatFileSize((int) $file->getData('file_size')),
'file_date' => $file->getData('file_mtime')
? date('Y-m-d', strtotime((string) $file->getData('file_mtime')))
: '',
];
}
return $this->items = $items;
}
private function getArchives(): array
{
if ($this->archives !== null) {
return $this->archives;
}
$activeBrands = $this->getActiveBrands();
if (!$activeBrands) {
return $this->archives = [];
}
$mediaBaseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
$archives = [];
$seenBrandIds = [];
$collection = $this->importCollectionFactory->create()
->addFieldToFilter('status', 1)
->addFieldToFilter('brand_id', ['in' => array_keys($activeBrands)])
->setOrder('updated_at', 'DESC');
foreach ($collection as $import) {
$brandId = (int) $import->getData('brand_id');
$archivePath = (string) $import->getData('archive_file');
if (isset($seenBrandIds[$brandId]) || $archivePath === '' || !$this->media->exists($archivePath)) {
continue;
}
$brand = $activeBrands[$brandId];
$logoPath = (string) $brand['logo'];
$archives[] = [
'id' => 'archive-' . (int) $import->getId(),
'type' => 'archive',
'brand_id' => $brandId,
'brand_name' => (string) $brand['name'],
'brand_logo_url' => $logoPath !== '' ? $mediaBaseUrl . ltrim($logoPath, '/') : '',
'model_name' => '',
'file_name' => basename($archivePath),
'file_url' => $mediaBaseUrl . ltrim($archivePath, '/'),
'file_size_label' => $this->formatFileSize($this->media->getFileSize($archivePath)),
'file_date' => $import->getData('updated_at')
? date('Y-m-d', strtotime((string) $import->getData('updated_at')))
: '',
];
$seenBrandIds[$brandId] = true;
}
usort($archives, static fn (array $a, array $b): int => strcasecmp($a['brand_name'], $b['brand_name']));
return $this->archives = $archives;
}
private function getActiveBrands(): array
{
if ($this->activeBrands !== null) {
return $this->activeBrands;
}
$brands = [];
$collection = $this->brandCollectionFactory->create()
->addFieldToFilter('status', 1)
->setOrder('sort_order', 'ASC')
->setOrder('brand_name', 'ASC');
foreach ($collection as $brand) {
$brands[(int) $brand->getId()] = [
'name' => (string) $brand->getData('brand_name'),
'logo' => (string) $brand->getData('brand_logo'),
];
}
return $this->activeBrands = $brands;
}
private function formatFileSize(int $bytes): string
{
if ($bytes >= 1048576) {
return round($bytes / 1048576, 1) . ' MB';
}
return round($bytes / 1024, 1) . ' KB';
}
}
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace Esun\Wiki\Block\Wiki;
use Esun\Catalog\Model\PrintingParameter;
use Esun\Wiki\Model\PrintingParameterClassifier;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\View\Element\Template;
class ParameterComparison extends Template
{
private ?array $config = null;
public function __construct(
Template\Context $context,
private readonly PrintingParameter $printingParameter,
private readonly PrintingParameterClassifier $classifier,
private readonly Json $json,
array $data = []
) {
parent::__construct($context, $data);
}
public function isTargetPage(): bool
{
$parent = $this->getParentBlock();
if (!($parent instanceof View)) {
return false;
}
$category = $parent->getCurrentCategory();
return $category !== null
&& (int) $category->getData('show_parameter_comparison') === 1;
}
public function hasComparisonData(): bool
{
return $this->isTargetPage() && (bool) $this->getConfig()['products'];
}
public function getConfigJson(): string
{
return $this->json->serialize($this->getConfig());
}
public function getBaseOptions(): array
{
return $this->getConfig()['baseOptions'];
}
public function getApplicationOptions(): array
{
return $this->getConfig()['applicationOptions'];
}
public function getParameterGroups(): array
{
return $this->getConfig()['parameterGroups'];
}
private function getConfig(): array
{
if ($this->config !== null) {
return $this->config;
}
$products = [];
$parameterGroups = [];
$baseCounts = [];
$applicationCounts = [];
foreach ($this->printingParameter->getAll() as $rawName => $groups) {
$classification = $this->classifier->classify($rawName);
$cleanName = $this->classifier->cleanName($rawName);
$productGroups = [];
foreach ($groups as $groupName => $group) {
$items = is_array($group['items'] ?? null) ? $group['items'] : [];
if (!$items) {
continue;
}
$productGroups[$groupName] = $items;
foreach (array_keys($items) as $parameterName) {
$parameterGroups[$groupName][(string) $parameterName] = (string) $parameterName;
}
}
$products[] = [
'id' => $rawName,
'name' => $cleanName,
'base' => $classification['base'],
'applications' => $classification['applications'],
'groups' => $productGroups,
];
$baseCounts[$classification['base']] = ($baseCounts[$classification['base']] ?? 0) + 1;
foreach ($classification['applications'] as $application) {
$applicationCounts[$application] = ($applicationCounts[$application] ?? 0) + 1;
}
}
usort($products, static fn (array $a, array $b): int => strnatcasecmp($a['name'], $b['name']));
$baseOptions = $this->buildOptions($this->classifier->getBaseOptions(), $baseCounts);
$applicationOptions = $this->buildOptions($this->classifier->getApplicationOptions(), $applicationCounts);
foreach ($parameterGroups as $groupName => $items) {
$parameterGroups[$groupName] = array_values($items);
}
return $this->config = [
'products' => $products,
'baseOptions' => $baseOptions,
'applicationOptions' => $applicationOptions,
'parameterGroups' => $parameterGroups,
'messages' => [
'selectMaterials' => (string) __('Select 1 to 6 materials to view or compare.'),
'maximumMaterials' => (string) __('You can compare up to 6 materials.'),
'noMaterials' => (string) __('No materials match the selected filters.'),
'missingValue' => '—',
],
];
}
private function buildOptions(array $labels, array $counts): array
{
$options = [];
foreach ($labels as $value => $label) {
if (($counts[$value] ?? 0) > 0) {
$options[] = ['value' => $value, 'label' => $label, 'count' => $counts[$value]];
}
}
return $options;
}
}
+878
View File
@@ -0,0 +1,878 @@
<?php
declare(strict_types=1);
namespace Esun\Wiki\Block\Wiki;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\CategoryFactory;
use Esun\Wiki\Model\Homepage;
use Esun\Wiki\Model\HomepageFactory;
use Esun\Wiki\Model\ResourceModel\Category\Collection;
use Esun\Wiki\Model\ResourceModel\Category\CollectionFactory;
use Esun\Wiki\Model\ResourceModel\Homepage\CollectionFactory as HomepageCollectionFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\ImageBuilder;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Catalog\Pricing\Price\RegularPrice;
use Magento\Checkout\Helper\Cart as CartHelper;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\App\ActionInterface;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\UrlInterface;
use Magento\Framework\Url\Helper\Data as UrlHelper;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
class View extends Template implements IdentityInterface
{
private const XML_PATH_BANNER_IMAGE = 'esun_wiki/appearance/banner_image';
private const BANNER_MEDIA_PATH = 'esun/wiki/banner/';
private ?Collection $categories = null;
private ?Category $currentCategory = null;
/**
* @var array<int, Category>|null
*/
private ?array $categoryMap = null;
/**
* @var mixed[]|null
*/
private ?array $categoryTree = null;
private ?string $processedContent = null;
/**
* @var mixed[]
*/
private array $tooltips = [];
private int $tooltipCounter = 0;
/**
* @var Product[]
*/
private array $tooltipProducts = [];
/**
* @var mixed[]|null
*/
private ?array $anchors = null;
/**
* @var Category[]|null
*/
private ?array $searchResults = null;
/**
* @var Category[]|null
*/
private ?array $navigationCategories = null;
public function __construct(
Context $context,
private readonly CollectionFactory $collectionFactory,
private readonly CategoryFactory $categoryFactory,
private readonly FilterProvider $filterProvider,
private readonly ProductRepositoryInterface $productRepository,
private readonly ImageBuilder $imageBuilder,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly CartHelper $cartHelper,
private readonly UrlHelper $urlHelper,
private readonly HomepageFactory $homepageFactory,
private readonly HomepageCollectionFactory $homepageCollectionFactory,
array $data = []
) {
parent::__construct($context, $data);
}
protected function _prepareLayout(): self
{
parent::_prepareLayout();
if ($this->hasSearchQuery()) {
$this->pageConfig->getTitle()->set((string) __('Esun Wiki'));
return $this;
}
$category = $this->getCurrentCategory();
if (!$category) {
$this->pageConfig->getTitle()->set((string) __('Esun Wiki'));
return $this;
}
$categoryTitle = (string) $category->getData('title');
$metaTitle = trim((string) $category->getData('meta_title'));
$this->pageConfig->getTitle()->set($categoryTitle);
$this->pageConfig->setMetaTitle($metaTitle !== '' ? $metaTitle : $categoryTitle);
$metaDescription = trim((string) $category->getData('meta_description'));
if ($metaDescription !== '') {
$this->pageConfig->setDescription($metaDescription);
}
$metaKeywords = trim((string) $category->getData('meta_keywords'));
if ($metaKeywords !== '') {
$this->pageConfig->setKeywords($metaKeywords);
}
return $this;
}
public function getWikiHomeUrl(): string
{
return $this->getUrl('wiki/index/index');
}
public function getSearchUrl(): string
{
return $this->getUrl('wiki/index/index');
}
public function getCategoryUrl(Category $category): string
{
$customPath = trim((string) $category->getData('custom_url_path'), '/');
if ($customPath !== '') {
return rtrim($this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_LINK), '/')
. '/' . $customPath;
}
return $this->getUrl('wiki/index/view', ['slug' => (string) $category->getData('slug')]);
}
public function getHeroBackgroundUrl(): string
{
$image = ltrim(trim((string) $this->_scopeConfig->getValue(
self::XML_PATH_BANNER_IMAGE,
ScopeInterface::SCOPE_STORE
)), '/');
if ($image !== '') {
return $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. self::BANNER_MEDIA_PATH
. $image;
}
return $this->getViewFileUrl('Magento_Theme::images/wiki_top_banner.png');
}
public function getSearchQuery(): string
{
return trim((string) $this->getRequest()->getParam('q'));
}
public function hasSearchQuery(): bool
{
return $this->getSearchQuery() !== '';
}
/**
* @return Category[]
*/
public function getSearchResults(): array
{
if ($this->searchResults !== null) {
return $this->searchResults;
}
$query = $this->getSearchQuery();
if ($query === '') {
$this->searchResults = [];
return $this->searchResults;
}
$collection = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($this->getCurrentStoreId())
->addFieldToFilter(
['title', 'slug', 'summary', 'content'],
[
['like' => '%' . $query . '%'],
['like' => '%' . $query . '%'],
['like' => '%' . $query . '%'],
['like' => '%' . $query . '%'],
]
)
->addTreeOrder();
$this->searchResults = [];
foreach ($collection as $category) {
if (!$this->isCategoryClickable($category)) {
continue;
}
$this->searchResults[] = $category;
if (count($this->searchResults) >= 20) {
break;
}
}
return $this->searchResults;
}
public function getSearchSnippet(Category $category): string
{
$text = trim(strip_tags((string) $category->getData('summary')));
if ($text === '') {
$text = trim(strip_tags((string) $category->getData('content')));
}
if ($text === '') {
return (string) __('Open this wiki category to view details.');
}
return $this->truncate($text, 180);
}
public function getCurrentCategory(): ?Category
{
if ($this->currentCategory !== null) {
return $this->currentCategory->getId() ? $this->currentCategory : null;
}
if ($this->isHomepageRequest()) {
$homepage = $this->homepageCollectionFactory->create()
->setPageSize(1)
->getFirstItem();
$this->currentCategory = $homepage->getId()
? $homepage
: $this->homepageFactory->create();
return $this->currentCategory->getId() ? $this->currentCategory : null;
}
$category = null;
$id = (int) $this->getRequest()->getParam('id');
$slug = trim((string) $this->getRequest()->getParam('slug'));
if ($id > 0) {
$candidate = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($this->getCurrentStoreId())
->addFieldToFilter('category_id', $id)
->setPageSize(1)
->getFirstItem();
if ($candidate->getId() && $this->isCategoryClickable($candidate)) {
$category = $candidate;
}
}
if ($category === null && $slug !== '') {
$collection = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($this->getCurrentStoreId())
->addFieldToFilter('slug', $slug)
->setPageSize(1);
$category = $collection->getFirstItem();
if (!$category->getId() || !$this->isCategoryClickable($category)) {
$category = null;
}
}
if ($category === null) {
$firstClickableCategory = null;
foreach ($this->getCategories() as $candidate) {
if (!$this->isCategoryClickable($candidate)) {
continue;
}
$firstClickableCategory ??= $candidate;
if (trim((string) $candidate->getData('content')) !== '') {
$category = $candidate;
break;
}
}
$category ??= $firstClickableCategory;
}
$this->currentCategory = $category ?: $this->categoryFactory->create();
return $this->currentCategory->getId() ? $this->currentCategory : null;
}
public function isHomepage(): bool
{
return $this->getCurrentCategory() instanceof Homepage;
}
/**
* @return mixed[]
*/
public function getCategoryTree(): array
{
if ($this->categoryTree !== null) {
return $this->categoryTree;
}
$activeIds = [];
foreach ($this->getCategories() as $category) {
$activeIds[(int) $category->getId()] = true;
}
$childrenByParent = [];
foreach ($this->getCategories() as $category) {
$parentId = (int) $category->getData('parent_id');
if ($parentId > 0 && !isset($activeIds[$parentId])) {
$parentId = 0;
}
$childrenByParent[$parentId][] = $category;
}
$this->categoryTree = $this->buildTree($childrenByParent, 0);
return $this->categoryTree;
}
public function isCurrent(Category $category): bool
{
$current = $this->getCurrentCategory();
return $current instanceof Category
&& !($current instanceof Homepage)
&& (int) $current->getId() === (int) $category->getId();
}
public function isInCurrentPath(Category $category): bool
{
$current = $this->getCurrentCategory();
if (!$current) {
return false;
}
return isset($this->getCurrentPathIds()[(int) $category->getId()]);
}
public function isCategoryOpenByDefault(Category $category): bool
{
return $category->isOpenByDefault();
}
public function isCategoryClickable(Category $category): bool
{
return $category->isClickable();
}
public function getCategoryLogoUrl(Category $category): string
{
$path = trim((string) $category->getData('logo_path'));
if ($path === '') {
return '';
}
return rtrim($this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA), '/')
. '/' . ltrim($path, '/');
}
/**
* @return Category[]
*/
public function getBreadcrumbItems(): array
{
$current = $this->getCurrentCategory();
if (!$current || $current instanceof Homepage) {
return [];
}
$items = [$current];
$map = $this->getCategoryMap();
$parentId = (int) $current->getData('parent_id');
while ($parentId > 0 && isset($map[$parentId]) && count($items) < 20) {
array_unshift($items, $map[$parentId]);
$parentId = (int) $map[$parentId]->getData('parent_id');
}
return $items;
}
public function getPreviousCategory(): ?Category
{
return $this->getSiblingNavigationCategory(-1);
}
public function getNextCategory(): ?Category
{
return $this->getSiblingNavigationCategory(1);
}
public function getProcessedContent(): string
{
$this->prepareContent();
return $this->processedContent ?? '';
}
/**
* @return array<int, array{id:string,label:string,level:int}>
*/
public function getAnchors(): array
{
$this->prepareContent();
return $this->anchors ?? [];
}
/**
* @return mixed[]
*/
public function getTooltips(): array
{
$this->prepareContent();
return $this->tooltips;
}
/**
* @return string[]
*/
public function getIdentities(): array
{
$this->prepareContent();
$identities = [];
$current = $this->getCurrentCategory();
if ($current instanceof IdentityInterface) {
$identities = array_merge($identities, $current->getIdentities());
}
foreach ($this->tooltipProducts as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function getSiblingNavigationCategory(int $offset): ?Category
{
$current = $this->getCurrentCategory();
if (!$current || $current instanceof Homepage) {
return null;
}
foreach ($this->getNavigationCategories() as $index => $category) {
if ((int) $category->getId() !== (int) $current->getId()) {
continue;
}
return $this->getNavigationCategories()[$index + $offset] ?? null;
}
return null;
}
/**
* @return Category[]
*/
private function getNavigationCategories(): array
{
if ($this->navigationCategories !== null) {
return $this->navigationCategories;
}
$this->navigationCategories = [];
$this->appendNavigationCategories($this->getCategoryTree(), $this->navigationCategories);
return $this->navigationCategories;
}
private function getCategories(): Collection
{
if ($this->categories === null) {
$this->categories = $this->collectionFactory->create()
->addActiveFilter()
->addStoreFilter($this->getCurrentStoreId())
->addTreeOrder();
}
return $this->categories;
}
private function getCurrentStoreId(): int
{
return (int) $this->_storeManager->getStore()->getId();
}
private function isHomepageRequest(): bool
{
return $this->getRequest()->getFullActionName() === 'wiki_index_index'
&& !$this->hasSearchQuery();
}
/**
* @param array<int, Category[]> $childrenByParent
* @return mixed[]
*/
private function buildTree(array $childrenByParent, int $parentId): array
{
$tree = [];
foreach ($childrenByParent[$parentId] ?? [] as $category) {
$tree[] = [
'category' => $category,
'children' => $this->buildTree($childrenByParent, (int) $category->getId()),
];
}
return $tree;
}
/**
* @param mixed[] $nodes
* @param Category[] $categories
*/
private function appendNavigationCategories(array $nodes, array &$categories): void
{
foreach ($nodes as $node) {
if ($this->isCategoryClickable($node['category'])) {
$categories[] = $node['category'];
}
$this->appendNavigationCategories($node['children'], $categories);
}
}
/**
* @return array<int, Category>
*/
private function getCategoryMap(): array
{
if ($this->categoryMap === null) {
$this->categoryMap = [];
foreach ($this->getCategories() as $category) {
$this->categoryMap[(int) $category->getId()] = $category;
}
}
return $this->categoryMap;
}
/**
* @return array<int, bool>
*/
private function getCurrentPathIds(): array
{
$ids = [];
foreach ($this->getBreadcrumbItems() as $category) {
$ids[(int) $category->getId()] = true;
}
return $ids;
}
private function prepareContent(): void
{
if ($this->processedContent !== null && $this->anchors !== null) {
return;
}
$current = $this->getCurrentCategory();
$rawContent = $current ? (string) $current->getData('content') : '';
$preparedContent = trim($this->replaceTooltipDirectives($rawContent));
$html = $preparedContent;
if ($html !== '') {
try {
$html = $this->filterProvider->getPageFilter()->filter($html);
} catch (\Throwable) {
$html = $preparedContent;
}
}
if (trim($html) === '') {
$message = $current instanceof Homepage
? __('This wiki homepage does not have content yet. Add content from the Magento admin.')
: __('This wiki category does not have content yet. Add content from the Magento admin.');
$html = '<p>' . $this->escapeHtml($message) . '</p>';
}
$anchors = [];
$usedIds = [];
$index = 0;
$html = (string) preg_replace_callback(
'/<h([1-2])([^>]*)>(.*?)<\/h\1>/is',
function (array $matches) use (&$anchors, &$usedIds, &$index): string {
$level = (int) $matches[1];
$attributes = (string) $matches[2];
$innerHtml = (string) $matches[3];
$label = trim(html_entity_decode(strip_tags($innerHtml), ENT_QUOTES, 'UTF-8'));
if ($label === '') {
return $matches[0];
}
if (preg_match('/\sid=(["\'])(.*?)\1/i', $attributes, $idMatches)) {
$id = $this->uniqueAnchorId((string) $idMatches[2], $usedIds);
$attributes = str_replace((string) $idMatches[0], ' id="' . $id . '"', $attributes);
} else {
$id = $this->uniqueAnchorId($this->createAnchorId($label, ++$index), $usedIds);
$attributes = rtrim($attributes) . ' id="' . $id . '"';
}
$anchors[] = [
'id' => $id,
'label' => $label,
'level' => $level,
];
return '<h' . $level . $attributes . '>' . $innerHtml . '</h' . $level . '>';
},
$html
);
$this->processedContent = $html;
$this->anchors = $anchors;
}
private function replaceTooltipDirectives(string $content): string
{
return (string) preg_replace_callback(
'/\{\{wiki_(product|term)\s+([^{}]*)\}\}/i',
function (array $matches): string {
$type = strtolower((string) $matches[1]);
$attributes = $this->parseDirectiveAttributes((string) $matches[2]);
return $type === 'product'
? $this->createProductTooltip($attributes)
: $this->createTermTooltip($attributes);
},
$content
);
}
/**
* @return array<string, string>
*/
private function parseDirectiveAttributes(string $source): array
{
$attributes = [];
preg_match_all(
'/([a-z_][a-z0-9_-]*)\s*=\s*(["\'])(.*?)\2/is',
$source,
$matches,
PREG_SET_ORDER
);
foreach ($matches as $match) {
$attributes[strtolower((string) $match[1])] = html_entity_decode(
(string) $match[3],
ENT_QUOTES | ENT_HTML5,
'UTF-8'
);
}
return $attributes;
}
/**
* @param array<string, string> $attributes
*/
private function createProductTooltip(array $attributes): string
{
$sku = trim($attributes['sku'] ?? '');
$fallbackLabel = trim($attributes['label'] ?? $sku);
if ($sku === '') {
return $this->escapeHtml($fallbackLabel);
}
try {
$storeId = (int) $this->_storeManager->getStore()->getId();
$product = $this->productRepository->get($sku, false, $storeId);
if (!$product->getId() || (int) $product->getStatus() !== Status::STATUS_ENABLED) {
return $this->escapeHtml($fallbackLabel);
}
} catch (\Throwable) {
return $this->escapeHtml($fallbackLabel);
}
$id = $this->nextTooltipId();
$label = $fallbackLabel !== '' ? $fallbackLabel : (string) $product->getName();
$finalPrice = $this->getPriceValue($product, FinalPrice::PRICE_CODE);
$regularPrice = $this->getPriceValue($product, RegularPrice::PRICE_CODE);
$isSaleable = (bool) $product->isSaleable();
$canAddToCart = $isSaleable
&& (bool) $product->getTypeInstance()->isPossibleBuyFromList($product);
$this->tooltips[] = [
'id' => $id,
'type' => 'product',
'sku' => (string) $product->getSku(),
'name' => (string) $product->getName(),
'product_url' => (string) $product->getProductUrl(),
'image_url' => $this->getProductImageUrl($product),
'final_price' => $this->formatPrice($finalPrice),
'regular_price' => $regularPrice > $finalPrice ? $this->formatPrice($regularPrice) : '',
'is_saleable' => $isSaleable,
'can_add_to_cart' => $canAddToCart,
'add_to_cart' => $canAddToCart ? $this->getAddToCartData($product) : [],
];
$this->tooltipProducts[(int) $product->getId()] = $product;
return $this->renderTooltipTrigger($id, $label, 'product');
}
/**
* @param array<string, string> $attributes
*/
private function createTermTooltip(array $attributes): string
{
$label = trim($attributes['label'] ?? '');
$title = trim($attributes['title'] ?? $label);
$description = trim($attributes['description'] ?? '');
$imageUrl = $this->resolveTermImageUrl(trim($attributes['image'] ?? ''));
if ($label === '' || ($title === '' && $description === '')) {
return $this->escapeHtml($label);
}
$id = $this->nextTooltipId();
$this->tooltips[] = [
'id' => $id,
'type' => 'term',
'title' => $title,
'description' => $description,
'image_url' => $imageUrl,
'image_alt' => trim($attributes['image_alt'] ?? $title),
'link_label' => trim($attributes['link_label'] ?? ''),
'link_url' => trim($attributes['link_url'] ?? ''),
];
return $this->renderTooltipTrigger($id, $label, 'term');
}
private function resolveTermImageUrl(string $image): string
{
if ($image === '') {
return '';
}
if (preg_match('#^(?:https?:)?//#i', $image) || str_starts_with($image, '/')) {
return $image;
}
$image = ltrim($image, '/');
if (str_starts_with($image, 'media/')) {
$image = substr($image, strlen('media/'));
}
return rtrim(
$this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA),
'/'
) . '/' . $image;
}
private function nextTooltipId(): string
{
$this->tooltipCounter++;
return 'esun-wiki-tooltip-' . $this->tooltipCounter;
}
private function renderTooltipTrigger(string $id, string $label, string $type): string
{
return sprintf(
'<button type="button" class="esun-wiki-tip-trigger is-%1$s" data-wiki-tip="%2$s" aria-controls="%2$s" aria-expanded="false">%3$s</button>',
$this->escapeHtmlAttr($type),
$this->escapeHtmlAttr($id),
$this->escapeHtml($label)
);
}
private function getProductImageUrl(Product $product): string
{
try {
return (string) $this->imageBuilder
->create($product, 'category_page_grid')
->getImageUrl();
} catch (\Throwable) {
return '';
}
}
private function getPriceValue(Product $product, string $priceCode): float
{
try {
return (float) $product->getPriceInfo()
->getPrice($priceCode)
->getAmount()
->getValue();
} catch (\Throwable) {
return (float) $product->getFinalPrice();
}
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
/**
* @return array{action:string,product:int,uenc:string}
*/
private function getAddToCartData(Product $product): array
{
$action = $this->cartHelper->getAddUrl($product, ['_escape' => false]);
return [
'action' => $action,
'product' => (int) $product->getId(),
ActionInterface::PARAM_NAME_URL_ENCODED => $this->urlHelper->getEncodedUrl($action),
];
}
/**
* @param array<string, bool> $usedIds
*/
private function uniqueAnchorId(string $id, array &$usedIds): string
{
$base = $id !== '' ? $id : 'section';
$candidate = $base;
$counter = 2;
while (isset($usedIds[$candidate])) {
$candidate = $base . '-' . $counter;
$counter++;
}
$usedIds[$candidate] = true;
return $candidate;
}
private function createAnchorId(string $label, int $index): string
{
$id = strtolower(trim($label));
$id = (string) preg_replace('/[^a-z0-9]+/', '-', $id);
$id = trim($id, '-');
return $id !== '' ? $id : 'section-' . $index;
}
private function truncate(string $text, int $limit): string
{
$text = preg_replace('/\s+/', ' ', trim($text)) ?: '';
if (function_exists('mb_strlen') && function_exists('mb_substr')) {
if (mb_strlen($text) <= $limit) {
return $text;
}
return rtrim(mb_substr($text, 0, $limit - 1)) . '...';
}
if (strlen($text) <= $limit) {
return $text;
}
return rtrim(substr($text, 0, $limit - 1)) . '...';
}
}