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,174 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\ScopeInterface;
class Accessories extends AbstractProduct implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/accessories/';
private const BACKGROUND_MEDIA_PATH = 'esun/homepage/accessories/';
/**
* @var Product[]|null
*/
private ?array $products = null;
public function __construct(
Context $context,
private readonly CollectionFactory $productCollectionFactory,
private readonly Visibility $productVisibility,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly HttpContext $httpContext,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return Product[]
*/
public function getProducts(): array
{
if ($this->products !== null) {
return $this->products;
}
$skus = $this->getConfiguredSkus();
if (!$skus) {
return $this->products = [];
}
$collection = $this->productCollectionFactory->create();
$collection->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($collection);
$collection->addStoreFilter();
$collection->addAttributeToFilter('sku', ['in' => $skus]);
$collection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$collection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$productsBySku = [];
foreach ($collection as $product) {
$productsBySku[strtolower((string) $product->getSku())] = $product;
}
$this->products = [];
foreach ($skus as $sku) {
$key = strtolower($sku);
if (isset($productsBySku[$key])) {
$this->products[] = $productsBySku[$key];
}
}
return $this->products;
}
public function getBackgroundImageUrl(): string
{
$image = ltrim(trim((string) $this->getConfig('background_image')), '/');
if ($image === '') {
return '';
}
return $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. self::BACKGROUND_MEDIA_PATH
. $image;
}
public function getExploreAllUrl(): string
{
return trim((string) $this->getConfig('explore_all_url'));
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_ACCESSORIES',
(int) $this->_storeManager->getStore()->getId(),
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
sha1(implode('|', $this->getConfiguredSkus())),
sha1($this->getBackgroundImageUrl()),
sha1($this->getExploreAllUrl()),
];
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getProducts() as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function getConfiguredSkus(): array
{
$value = (string) $this->getConfig('skus');
$skus = preg_split('/[\s,;]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
return array_values(array_unique(array_map('trim', $skus)));
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block\Adminhtml\System\Config\Form\Field;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
class CreateAnythingItems extends AbstractFieldArray
{
protected function _prepareToRender(): void
{
$this->addColumn('title', [
'label' => __('Title'),
'style' => 'width:160px',
]);
$this->addColumn('subtitle', [
'label' => __('Subtitle'),
'style' => 'width:180px',
]);
$this->addColumn('video_id', [
'label' => __('Video ID'),
'class' => 'validate-digits',
'style' => 'width:90px',
]);
$this->addColumn('product_sku', [
'label' => __('Product SKU'),
'style' => 'width:150px',
]);
$this->addColumn('sort_number', [
'label' => __('Sort Number'),
'class' => 'validate-number',
'style' => 'width:90px',
]);
$this->_addAfter = false;
$this->_addButtonLabel = __('Add Item');
}
public function getArrayRows(): array
{
$element = $this->getElement();
if (!$element->getValue()) {
$element->setValue([
'_initial' => [
'title' => '',
'subtitle' => '',
'video_id' => '',
'product_sku' => '',
'sort_number' => '',
],
]);
}
return parent::getArrayRows();
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ImageProvider;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
class Application extends Template implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/application/';
/**
* @var array<int, array<string, int|string>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly ImageProvider $imageProvider,
array $data = []
) {
parent::__construct($context, $data);
}
public function getSubtitle(): string
{
return trim((string) $this->getConfig('subtitle'));
}
public function getExploreAllUrl(): string
{
return trim((string) $this->getConfig('explore_all_url'));
}
/**
* @return array<int, array<string, int|string>>
*/
public function getItems(): array
{
if ($this->items === null) {
$this->items = $this->imageProvider->getImagesByCategoryId($this->getCategoryId());
}
return $this->items;
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_APPLICATION',
(int) $this->_storeManager->getStore()->getId(),
$this->getCategoryId(),
sha1($this->getSubtitle()),
sha1($this->getExploreAllUrl()),
];
}
public function getIdentities(): array
{
$identities = [];
$categoryId = $this->getCategoryId();
if ($categoryId > 0) {
$identities[] = Category::CACHE_TAG . '_' . $categoryId;
}
foreach ($this->getItems() as $item) {
$identities[] = Image::CACHE_TAG . '_' . (int) $item['id'];
}
return array_values(array_unique($identities));
}
private function getCategoryId(): int
{
return (int) $this->getConfig('category_id');
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ImageProvider;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
class AwardsReviews extends Template implements IdentityInterface
{
private const XML_PATH_CATEGORY_ID = 'esun_homepage/awards_reviews/category_id';
/**
* @var array<int, array<string, int|string>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly ImageProvider $imageProvider,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<int, array<string, int|string>>
*/
public function getItems(): array
{
if ($this->items === null) {
$this->items = array_values(array_filter(
$this->imageProvider->getImagesByCategoryId($this->getCategoryId()),
static fn (array $item): bool => trim((string) $item['thumbnail_url']) !== ''
));
}
return $this->items;
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_AWARDS_REVIEWS',
(int) $this->_storeManager->getStore()->getId(),
$this->getCategoryId(),
];
}
public function getIdentities(): array
{
$identities = [];
$categoryId = $this->getCategoryId();
if ($categoryId > 0) {
$identities[] = Category::CACHE_TAG . '_' . $categoryId;
}
foreach ($this->getItems() as $item) {
$identities[] = Image::CACHE_TAG . '_' . (int) $item['id'];
}
return array_values(array_unique($identities));
}
private function getCategoryId(): int
{
return (int) $this->_scopeConfig->getValue(
self::XML_PATH_CATEGORY_ID,
ScopeInterface::SCOPE_STORE
);
}
}
@@ -0,0 +1,392 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\CatalogRule\Model\Rule;
use Magento\CatalogRule\Model\RuleFactory;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Swatches\Helper\Data as SwatchHelper;
use Magento\Swatches\Helper\Media as SwatchMediaHelper;
use Magento\Swatches\Model\Swatch;
class CatalogRuleDeal extends AbstractProduct implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/catalog_rule_deal/';
private const MAX_PRODUCTS = 12;
private ?Rule $rule = null;
private ?Collection $products = null;
public function __construct(
Context $context,
private readonly RuleFactory $ruleFactory,
private readonly CollectionFactory $productCollectionFactory,
private readonly ResourceConnection $resourceConnection,
private readonly Visibility $productVisibility,
private readonly HttpContext $httpContext,
private readonly TimezoneInterface $timezone,
private readonly SwatchHelper $swatchHelper,
private readonly SwatchMediaHelper $swatchMediaHelper,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
public function isAvailable(): bool
{
return $this->isEnabled()
&& $this->getRule() !== null
&& $this->isRuleCurrent($this->getRule())
&& $this->getProducts()->getSize() > 0;
}
public function getRule(): ?Rule
{
if ($this->rule !== null) {
return $this->rule->getId() ? $this->rule : null;
}
$ruleId = (int) $this->getConfig('rule_id');
$this->rule = $this->ruleFactory->create();
if ($ruleId > 0) {
$this->rule->load($ruleId);
}
return $this->rule->getId() ? $this->rule : null;
}
public function getProducts(): Collection
{
if ($this->products !== null) {
return $this->products;
}
$collection = $this->productCollectionFactory->create();
$collection->setStoreId((int) $this->_storeManager->getStore()->getId());
$productIds = $this->getIndexedProductIds();
if (!$productIds) {
$collection->addFieldToFilter('entity_id', ['in' => [0]]);
$this->products = $collection;
return $this->products;
}
$this->_addProductAttributesAndPrices($collection);
$collection->addStoreFilter();
$collection->addFieldToFilter('entity_id', ['in' => $productIds]);
$collection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$collection->addAttributeToFilter('status', Product\Attribute\Source\Status::STATUS_ENABLED);
$collection->setOrder('entity_id', 'DESC');
$collection->setPageSize($this->getProductsLimit());
$collection->setCurPage(1);
$this->products = $collection;
return $this->products;
}
public function getHeading(): string
{
$heading = trim((string) $this->getConfig('title'));
$rule = $this->getRule();
return $heading !== '' ? $heading : (string) ($rule?->getName() ?: '');
}
public function getAccentHeading(): string
{
return trim((string) $this->getConfig('accent_title'));
}
public function getCountdownEnd(): string
{
$toDate = (string) ($this->getRule()?->getToDate() ?: '');
if ($toDate === '') {
return '';
}
$date = $this->timezone->date($toDate . ' 23:59:59');
return $date->format(\DateTimeInterface::ATOM);
}
public function getProductDiscount(Product $product): int
{
$regularPrice = $this->getRegularPriceValue($product);
$finalPrice = $this->getFinalPriceValue($product);
if ($regularPrice <= 0 || $finalPrice >= $regularPrice) {
return 0;
}
return (int) round((1 - ($finalPrice / $regularPrice)) * 100);
}
public function getMaximumDiscount(): int
{
$maximum = 0;
foreach ($this->getProducts() as $product) {
$maximum = max($maximum, $this->getProductDiscount($product));
}
return $maximum;
}
public function getColorSwatches(Product $product): array
{
if ($product->getTypeId() !== 'configurable') {
return [];
}
$children = [];
$optionIds = [];
$childIdsByGroup = $product->getTypeInstance()->getChildrenIds((int) $product->getId());
$childIds = array_values(array_unique(array_map(
'intval',
array_merge(...array_values($childIdsByGroup ?: [[]]))
)));
if (!$childIds) {
return [];
}
$childCollection = $this->productCollectionFactory->create();
$childCollection->setStoreId((int) $this->_storeManager->getStore()->getId());
$childCollection->addIdFilter($childIds);
$childCollection->addAttributeToSelect(['color', 'sku', 'image', 'small_image', 'thumbnail']);
$childCollection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$childCollection->setOrder('entity_id', 'ASC');
foreach ($childCollection as $childProduct) {
$optionId = (int) $childProduct->getData('color');
if ($optionId <= 0) {
continue;
}
$children[] = [
'option_id' => $optionId,
'sku' => (string) $childProduct->getSku(),
'product' => $childProduct,
];
$optionIds[$optionId] = $optionId;
}
if (!$children) {
return [];
}
$swatchData = $this->swatchHelper->getSwatchesByOptionsId(array_values($optionIds));
$colorAttribute = null;
foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $attribute) {
if ($attribute->getProductAttribute()->getAttributeCode() === 'color') {
$colorAttribute = $attribute->getProductAttribute();
$colorAttribute->setStoreId((int) $this->_storeManager->getStore()->getId());
break;
}
}
$result = [];
foreach ($children as $child) {
$optionId = $child['option_id'];
$swatch = $swatchData[$optionId] ?? [];
$type = (int) ($swatch['type'] ?? Swatch::SWATCH_TYPE_EMPTY);
$value = (string) ($swatch['value'] ?? '');
$result[] = [
'id' => $optionId,
'sku' => $child['sku'],
'label' => $colorAttribute
? (string) $colorAttribute->getSource()->getOptionText($optionId)
: $child['sku'],
'type' => $type,
'value' => $value,
'product_image' => $this->getProductImageUrl($child['product']),
'image' => $type === Swatch::SWATCH_TYPE_VISUAL_IMAGE && $value !== ''
? $this->swatchMediaHelper->getSwatchAttributeImage(
Swatch::SWATCH_IMAGE_NAME,
$value
)
: '',
];
}
return $result;
}
public function getProductImageUrl(Product $product, string $imageId = 'category_page_grid'): string
{
return (string) $this->getImage($product, $imageId)->getImageUrl();
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getProductPrice(Product $product): string
{
return $this->getProductPriceHtml(
$product,
FinalPrice::PRICE_CODE,
Render::ZONE_ITEM_LIST,
[
'include_container' => true,
'display_minimal_price' => true,
'list_category_page' => true,
]
);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_CATALOG_RULE_DEAL',
(int) $this->_storeManager->getStore()->getId(),
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
(int) ($this->getRule()?->getId() ?: 0),
];
}
public function getIdentities(): array
{
$identities = [];
$rule = $this->getRule();
if ($rule) {
$identities = array_merge($identities, $rule->getIdentities());
}
foreach ($this->getProducts() as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function isEnabled(): bool
{
return $this->_scopeConfig->isSetFlag(
self::XML_PATH . 'enabled',
ScopeInterface::SCOPE_STORE
);
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
private function getProductsLimit(): int
{
$limit = (int) $this->getConfig('products_limit');
return max(1, min(self::MAX_PRODUCTS, $limit ?: 4));
}
private function isRuleCurrent(Rule $rule): bool
{
if (!$rule->getIsActive()) {
return false;
}
$websiteId = (int) $this->_storeManager->getStore()->getWebsiteId();
if (!in_array($websiteId, array_map('intval', (array) $rule->getWebsiteIds()), true)) {
return false;
}
$today = $this->timezone->date()->format('Y-m-d');
$fromDate = (string) $rule->getFromDate();
$toDate = (string) $rule->getToDate();
return ($fromDate === '' || $fromDate <= $today)
&& ($toDate === '' || $toDate >= $today);
}
private function getIndexedProductIds(): array
{
$rule = $this->getRule();
if (!$rule) {
return [];
}
$connection = $this->resourceConnection->getConnection();
$table = $this->resourceConnection->getTableName('catalogrule_product');
$now = time();
$select = $connection->select()
->distinct()
->from($table, ['product_id'])
->where('rule_id = ?', (int) $rule->getId())
->where('website_id = ?', (int) $this->_storeManager->getStore()->getWebsiteId())
->where(
'customer_group_id = ?',
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP)
)
->where('(from_time = 0 OR from_time <= ?)', $now)
->where('(to_time = 0 OR to_time >= ?)', $now);
$productIds = array_map('intval', $connection->fetchCol($select));
if (!$productIds) {
return [];
}
$parentSelect = $connection->select()
->distinct()
->from(
$this->resourceConnection->getTableName('catalog_product_super_link'),
['parent_id']
)
->where('product_id IN (?)', $productIds);
$parentIds = array_map('intval', $connection->fetchCol($parentSelect));
return array_values(array_unique(array_merge($productIds, $parentIds)));
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
@@ -0,0 +1,210 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory as VideoCollectionFactory;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\ScopeInterface;
class CreateAnything extends AbstractProduct implements IdentityInterface
{
private const XML_PATH_ITEMS = 'esun_homepage/create_anything/items';
/**
* @var array<int, array<string, mixed>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly ProductCollectionFactory $productCollectionFactory,
private readonly VideoCollectionFactory $videoCollectionFactory,
private readonly Visibility $productVisibility,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly SerializerInterface $serializer,
private readonly HttpContext $httpContext,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<int, array<string, mixed>>
*/
public function getItems(): array
{
if ($this->items !== null) {
return $this->items;
}
$configuredItems = $this->getConfiguredItems();
if (!$configuredItems) {
return $this->items = [];
}
$videoIds = [];
$skus = [];
foreach ($configuredItems as $item) {
$videoId = (int) ($item['video_id'] ?? 0);
$sku = trim((string) ($item['product_sku'] ?? ''));
if ($videoId > 0) {
$videoIds[$videoId] = $videoId;
}
if ($sku !== '') {
$skus[strtolower($sku)] = $sku;
}
}
$videosById = [];
if ($videoIds) {
$videoCollection = $this->videoCollectionFactory->create();
$videoCollection->addFieldToFilter('video_id', ['in' => array_values($videoIds)]);
$videoCollection->addFieldToFilter('status', 1);
foreach ($videoCollection as $video) {
$videosById[(int) $video->getId()] = $video;
}
}
$productsBySku = [];
if ($skus) {
$productCollection = $this->productCollectionFactory->create();
$productCollection->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($productCollection);
$productCollection->addStoreFilter();
$productCollection->addAttributeToFilter('sku', ['in' => array_values($skus)]);
$productCollection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$productCollection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
foreach ($productCollection as $product) {
$productsBySku[strtolower((string) $product->getSku())] = $product;
}
}
$mediaBaseUrl = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
$this->items = [];
foreach ($configuredItems as $item) {
$videoId = (int) ($item['video_id'] ?? 0);
$skuKey = strtolower(trim((string) ($item['product_sku'] ?? '')));
$video = $videosById[$videoId] ?? null;
$product = $productsBySku[$skuKey] ?? null;
if (!$video || !$product) {
continue;
}
$this->items[] = [
'title' => trim((string) ($item['title'] ?? '')),
'subtitle' => trim((string) ($item['subtitle'] ?? '')),
'sort_number' => (int) ($item['sort_number'] ?? 0),
'video_url' => $mediaBaseUrl . ltrim((string) $video->getData('video_path'), '/'),
'cover_url' => $mediaBaseUrl . ltrim((string) $video->getData('cover_path'), '/'),
'product' => $product,
];
}
return $this->items;
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_CREATE_ANYTHING',
(int) $this->_storeManager->getStore()->getId(),
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
sha1((string) $this->_scopeConfig->getValue(
self::XML_PATH_ITEMS,
ScopeInterface::SCOPE_STORE
)),
];
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getItems() as $item) {
$product = $item['product'] ?? null;
if ($product instanceof Product) {
$identities = array_merge($identities, $product->getIdentities());
}
}
return array_values(array_unique($identities));
}
/**
* @return array<int, array<string, mixed>>
*/
private function getConfiguredItems(): array
{
$value = $this->_scopeConfig->getValue(
self::XML_PATH_ITEMS,
ScopeInterface::SCOPE_STORE
);
if (is_array($value)) {
return array_values($value);
}
if (!is_string($value) || trim($value) === '') {
return [];
}
try {
$items = $this->serializer->unserialize($value);
} catch (\InvalidArgumentException) {
return [];
}
return is_array($items) ? array_values($items) : [];
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
@@ -0,0 +1,272 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Swatches\Helper\Data as SwatchHelper;
use Magento\Swatches\Helper\Media as SwatchMediaHelper;
use Magento\Swatches\Model\Swatch;
class HotSaleFilament extends AbstractProduct implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/hot_sale_filament/';
/**
* @var Product[]|null
*/
private ?array $products = null;
/**
* @var array<int, array<int, array<string, int|string>>>
*/
private array $colorSwatches = [];
public function __construct(
Context $context,
private readonly CollectionFactory $productCollectionFactory,
private readonly Visibility $productVisibility,
private readonly SwatchHelper $swatchHelper,
private readonly SwatchMediaHelper $swatchMediaHelper,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly HttpContext $httpContext,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
public function getSubtitle(): string
{
return trim((string) $this->getConfig('subtitle'));
}
public function getExploreAllUrl(): string
{
return trim((string) $this->getConfig('explore_all_url'));
}
/**
* @return Product[]
*/
public function getProducts(): array
{
if ($this->products !== null) {
return $this->products;
}
$skus = $this->getConfiguredSkus();
if (!$skus) {
return $this->products = [];
}
$collection = $this->productCollectionFactory->create();
$collection->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($collection);
$collection->addAttributeToSelect(['short_description']);
$collection->addStoreFilter();
$collection->addAttributeToFilter('sku', ['in' => $skus]);
$collection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$collection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$productsBySku = [];
foreach ($collection as $product) {
$productsBySku[strtolower((string) $product->getSku())] = $product;
}
$this->products = [];
foreach ($skus as $sku) {
$key = strtolower($sku);
if (isset($productsBySku[$key])) {
$this->products[] = $productsBySku[$key];
}
}
return $this->products;
}
public function getShortDescription(Product $product): string
{
$description = html_entity_decode(
strip_tags((string) $product->getData('short_description')),
ENT_QUOTES | ENT_HTML5
);
return trim((string) preg_replace('/\s+/u', ' ', $description));
}
/**
* @return array<int, array<string, int|string>>
*/
public function getColorSwatches(Product $product): array
{
$productId = (int) $product->getId();
if (isset($this->colorSwatches[$productId])) {
return $this->colorSwatches[$productId];
}
if ($product->getTypeId() !== 'configurable') {
return $this->colorSwatches[$productId] = [];
}
$colorAttribute = null;
foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $attribute) {
if ($attribute->getProductAttribute()->getAttributeCode() === 'color') {
$colorAttribute = $attribute->getProductAttribute();
$colorAttribute->setStoreId((int) $this->_storeManager->getStore()->getId());
break;
}
}
if ($colorAttribute === null) {
return $this->colorSwatches[$productId] = [];
}
$childIdsByGroup = $product->getTypeInstance()->getChildrenIds($productId);
$childIds = array_values(array_unique(array_map(
'intval',
array_merge(...array_values($childIdsByGroup ?: [[]]))
)));
if (!$childIds) {
return $this->colorSwatches[$productId] = [];
}
$childCollection = $this->productCollectionFactory->create();
$childCollection->setStoreId((int) $this->_storeManager->getStore()->getId());
$childCollection->addIdFilter($childIds);
$childCollection->addAttributeToSelect(['color', 'sku', 'image', 'small_image', 'thumbnail']);
$childCollection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$childCollection->setOrder('entity_id', 'ASC');
$childrenByOption = [];
foreach ($childCollection as $childProduct) {
$optionId = (int) $childProduct->getData('color');
if ($optionId > 0 && !isset($childrenByOption[$optionId])) {
$childrenByOption[$optionId] = $childProduct;
}
}
if (!$childrenByOption) {
return $this->colorSwatches[$productId] = [];
}
$swatchData = $this->swatchHelper->getSwatchesByOptionsId(array_keys($childrenByOption));
$result = [];
foreach ($childrenByOption as $optionId => $childProduct) {
$swatch = $swatchData[$optionId] ?? [];
$type = (int) ($swatch['type'] ?? Swatch::SWATCH_TYPE_EMPTY);
$value = (string) ($swatch['value'] ?? '');
$result[] = [
'id' => $optionId,
'sku' => (string) $childProduct->getSku(),
'label' => (string) $colorAttribute->getSource()->getOptionText($optionId),
'type' => $type,
'value' => $value,
'product_image' => $this->getProductImageUrl($childProduct, 'category_page_grid'),
'product_image_large' => $this->getProductImageUrl($childProduct, 'product_page_image_large'),
'image' => $type === Swatch::SWATCH_TYPE_VISUAL_IMAGE && $value !== ''
? $this->swatchMediaHelper->getSwatchAttributeImage(
Swatch::SWATCH_IMAGE_NAME,
$value
)
: '',
];
}
return $this->colorSwatches[$productId] = $result;
}
public function getProductImageUrl(Product $product, string $imageId = 'category_page_grid'): string
{
return (string) $this->getImage($product, $imageId)->getImageUrl();
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_HOT_SALE_FILAMENT',
(int) $this->_storeManager->getStore()->getId(),
(string) $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_GROUP),
sha1(implode('|', $this->getConfiguredSkus())),
sha1($this->getSubtitle()),
sha1($this->getExploreAllUrl()),
];
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getProducts() as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function getConfiguredSkus(): array
{
$value = (string) $this->getConfig('skus');
$skus = preg_split('/[\s,;]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
return array_values(array_unique(array_map('trim', $skus)));
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ImageProvider;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
class InnovativeMaterials extends Template implements IdentityInterface
{
private const XML_PATH_CATEGORY_ID = 'esun_homepage/innovative_materials/category_id';
/**
* @var array<int, array<string, int|string>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly ImageProvider $imageProvider,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<int, array<string, int|string>>
*/
public function getItems(): array
{
if ($this->items === null) {
$this->items = array_values(array_filter(
$this->imageProvider->getImagesByCategoryId($this->getCategoryId()),
static fn (array $item): bool => trim((string) $item['thumbnail_url']) !== ''
));
}
return $this->items;
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_INNOVATIVE_MATERIALS',
(int) $this->_storeManager->getStore()->getId(),
$this->getCategoryId(),
];
}
public function getIdentities(): array
{
$identities = [];
$categoryId = $this->getCategoryId();
if ($categoryId > 0) {
$identities[] = Category::CACHE_TAG . '_' . $categoryId;
}
foreach ($this->getItems() as $item) {
$identities[] = Image::CACHE_TAG . '_' . (int) $item['id'];
}
return array_values(array_unique($identities));
}
private function getCategoryId(): int
{
return (int) $this->_scopeConfig->getValue(
self::XML_PATH_CATEGORY_ID,
ScopeInterface::SCOPE_STORE
);
}
}
@@ -0,0 +1,154 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Esun\Video\Model\ResourceModel\Video\CollectionFactory as VideoCollectionFactory;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\ScopeInterface;
class LandscapeVideo extends AbstractProduct implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/landscape_video/';
/**
* @var array<string, mixed>|null
*/
private ?array $item = null;
public function __construct(
Context $context,
private readonly ProductCollectionFactory $productCollectionFactory,
private readonly VideoCollectionFactory $videoCollectionFactory,
private readonly Visibility $productVisibility,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly HttpContext $httpContext,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<string, mixed>
*/
public function getItem(): array
{
if ($this->item !== null) {
return $this->item;
}
$videoId = (int) $this->getConfig('video_id');
$sku = trim((string) $this->getConfig('product_sku'));
if ($videoId <= 0 || $sku === '') {
return $this->item = [];
}
$videos = $this->videoCollectionFactory->create();
$videos->addFieldToFilter('video_id', $videoId);
$videos->addFieldToFilter('status', 1);
$videos->setPageSize(1);
$video = $videos->getFirstItem();
if (!$video->getId() || trim((string) $video->getData('cover_path')) === '') {
return $this->item = [];
}
$products = $this->productCollectionFactory->create();
$products->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($products);
$products->addStoreFilter();
$products->addAttributeToFilter('sku', $sku);
$products->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$products->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$products->setPageSize(1);
$product = $products->getFirstItem();
if (!$product->getId()) {
return $this->item = [];
}
$mediaBaseUrl = $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
return $this->item = [
'video_url' => $mediaBaseUrl . ltrim((string) $video->getData('video_path'), '/'),
'cover_url' => $mediaBaseUrl . ltrim((string) $video->getData('cover_path'), '/'),
'product' => $product,
];
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_LANDSCAPE_VIDEO',
(int) $this->_storeManager->getStore()->getId(),
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
(int) $this->getConfig('video_id'),
sha1(trim((string) $this->getConfig('product_sku'))),
];
}
public function getIdentities(): array
{
$product = $this->getItem()['product'] ?? null;
return $product instanceof Product ? $product->getIdentities() : [];
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Store\Model\ScopeInterface;
class NewProduct extends AbstractProduct implements IdentityInterface
{
private const XML_PATH_SKUS = 'esun_homepage/new_product/skus';
private const FEATURE_ATTRIBUTE = 'homepage_feature_content';
private const GALLERY_ATTRIBUTE = 'homepage_gallery_content';
/**
* @var Product[]|null
*/
private ?array $products = null;
public function __construct(
Context $context,
private readonly CollectionFactory $productCollectionFactory,
private readonly Visibility $productVisibility,
private readonly FilterProvider $filterProvider,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return Product[]
*/
public function getProducts(): array
{
if ($this->products !== null) {
return $this->products;
}
$skus = $this->getConfiguredSkus();
if (!$skus) {
return $this->products = [];
}
$collection = $this->productCollectionFactory->create();
$collection->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($collection);
$collection->addAttributeToSelect([self::FEATURE_ATTRIBUTE, self::GALLERY_ATTRIBUTE]);
$collection->addStoreFilter();
$collection->addAttributeToFilter('sku', ['in' => $skus]);
$collection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$collection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$productsBySku = [];
foreach ($collection as $product) {
$productsBySku[strtolower((string) $product->getSku())] = $product;
}
$this->products = [];
foreach ($skus as $sku) {
$key = strtolower($sku);
if (isset($productsBySku[$key])) {
$this->products[] = $productsBySku[$key];
}
}
return $this->products;
}
public function getFeatureContent(Product $product): string
{
return $this->filterContent((string) $product->getData(self::FEATURE_ATTRIBUTE));
}
public function getGalleryContent(Product $product): string
{
return $this->filterContent((string) $product->getData(self::GALLERY_ATTRIBUTE));
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getProducts() as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function getConfiguredSkus(): array
{
$value = (string) $this->_scopeConfig->getValue(
self::XML_PATH_SKUS,
ScopeInterface::SCOPE_STORE
);
$skus = preg_split('/[\s,;]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
return array_values(array_unique(array_map('trim', $skus)));
}
private function filterContent(string $content): string
{
if (trim($content) === '') {
return '';
}
return $this->filterProvider->getPageFilter()->filter($content);
}
}
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Mageplaza\Blog\Block\Post\View;
use Mageplaza\Blog\Model\Post;
/**
* Provides chronological navigation for the current news post.
*/
class NewsPostNavigation extends View
{
/** @var bool */
private bool $navigationLoaded = false;
/** @var Post|null */
private ?Post $previousPost = null;
/** @var Post|null */
private ?Post $nextPost = null;
/**
* Get the news post immediately before the current post.
*
* @return Post|null
*/
public function getPreviousPost(): ?Post
{
$this->loadNavigation();
return $this->previousPost;
}
/**
* Get the news post immediately after the current post.
*
* @return Post|null
*/
public function getNextPost(): ?Post
{
$this->loadNavigation();
return $this->nextPost;
}
/**
* Get the active storefront ID.
*
* @return int
*/
public function getCurrentStoreId(): int
{
return (int) $this->store->getStore()->getId();
}
/**
* Resolve both navigation directions once per request.
*
* @return void
*/
private function loadNavigation(): void
{
if ($this->navigationLoaded) {
return;
}
$this->navigationLoaded = true;
$currentPost = $this->getPost();
$currentPostId = (int) $currentPost->getId();
$publishDate = (string) $currentPost->getData('publish_date');
if ($currentPostId <= 0 || $publishDate === '') {
return;
}
$this->previousPost = $this->findPost([
'publish_date' => ['eq' => $publishDate],
'post_id' => ['lt' => $currentPostId],
], 'DESC');
if ($this->previousPost === null) {
$this->previousPost = $this->findPost([
'publish_date' => ['lt' => $publishDate],
], 'DESC');
}
$this->nextPost = $this->findPost([
'publish_date' => ['eq' => $publishDate],
'post_id' => ['gt' => $currentPostId],
], 'ASC');
if ($this->nextPost === null) {
$this->nextPost = $this->findPost([
'publish_date' => ['gt' => $publishDate],
], 'ASC');
}
}
/**
* Get the closest published post matching the supplied filters.
*
* @param array $filters
* @param string $direction
* @return Post|null
*/
private function findPost(array $filters, string $direction): ?Post
{
$collection = $this->helperData->getPostList($this->getCurrentStoreId());
foreach ($filters as $field => $condition) {
$collection->addFieldToFilter($field, $condition);
}
$collection->setOrder('publish_date', $direction)
->setOrder('post_id', $direction)
->setPageSize(1)
->setCurPage(1);
$post = $collection->getFirstItem();
return $post instanceof Post && $post->getId() ? $post : null;
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
use Mageplaza\Blog\Helper\Data as BlogHelper;
use Mageplaza\Blog\Helper\Image as BlogImageHelper;
use Mageplaza\Blog\Model\Post;
use Mageplaza\Blog\Model\ResourceModel\Post\CollectionFactory as PostCollectionFactory;
class NewsRoom extends Template implements IdentityInterface
{
private const XML_PATH_IDS = 'esun_homepage/news_room/ids';
/**
* @var array<int, array<string, mixed>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly PostCollectionFactory $postCollectionFactory,
private readonly BlogHelper $blogHelper,
private readonly TimezoneInterface $timezone,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<int, array<string, mixed>>
*/
public function getItems(): array
{
if ($this->items === null) {
$ids = $this->getConfiguredIds();
$this->items = [];
if (!$ids) {
return $this->items;
}
$collection = $this->postCollectionFactory->create();
$collection->addFieldToFilter('post_id', ['in' => $ids])
->addFieldToFilter('enabled', 1)
->addFieldToFilter('publish_date', ['to' => $this->timezone->date()->format('Y-m-d H:i:s')])
->setOrder('publish_date', 'desc');
foreach ($collection as $post) {
$this->items[] = $this->preparePostItem($post);
}
}
return $this->items;
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_NEWS_ROOM',
(int) $this->_storeManager->getStore()->getId(),
implode('_', $this->getConfiguredIds()),
];
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getItems() as $item) {
$identities[] = Post::CACHE_TAG . '_' . (int) $item['id'];
}
return array_values(array_unique($identities));
}
/**
* @return array<int, int>
*/
private function getConfiguredIds(): array
{
$value = (string) $this->_scopeConfig->getValue(
self::XML_PATH_IDS,
ScopeInterface::SCOPE_STORE
);
if (trim($value) === '') {
return [];
}
$ids = preg_split('/[\s,;]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
$ids = array_map('intval', $ids);
$ids = array_filter($ids, static fn (int $id): bool => $id > 0);
return array_values(array_unique($ids));
}
/**
* @return array<string, mixed>
*/
private function preparePostItem(Post $post): array
{
$imageUrl = $this->getPostImageUrl((string) $post->getImage());
return [
'id' => (int) $post->getId(),
'title' => (string) $post->getName(),
'image_url' => $imageUrl,
'publish_date' => $this->formatPublishDate((string) $post->getData('publish_date')),
'publish_date_iso' => $this->formatPublishDateIso((string) $post->getData('publish_date')),
'tag_name' => $this->getFirstTagName($post) ?: $this->getFirstCategoryName($post),
'url' => (string) $post->getUrl((int) $this->_storeManager->getStore()->getId()),
];
}
private function getPostImageUrl(string $image): string
{
if ($image === '') {
return $this->getViewFileUrl('Mageplaza_Blog::media/images/mageplaza-logo-default.png');
}
return (string) $this->blogHelper->getImageHelper()->resizeImage(
$image,
'640x',
BlogImageHelper::TEMPLATE_MEDIA_TYPE_POST
);
}
private function formatPublishDate(string $date): string
{
if ($date === '') {
return '';
}
return $this->timezone->date(new \DateTime($date))->format('y.m.d');
}
private function formatPublishDateIso(string $date): string
{
if ($date === '') {
return '';
}
return $this->timezone->date(new \DateTime($date))->format('Y-m-d');
}
private function getFirstTagName(Post $post): string
{
foreach ($post->getSelectedTagsCollection() as $tag) {
return (string) $tag->getName();
}
return '';
}
private function getFirstCategoryName(Post $post): string
{
foreach ($post->getSelectedCategoriesCollection() as $category) {
return (string) $category->getName();
}
return '';
}
}
+280
View File
@@ -0,0 +1,280 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\Catalog\Model\Product\CardPriceResolver;
use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Swatches\Helper\Data as SwatchHelper;
use Magento\Swatches\Helper\Media as SwatchMediaHelper;
use Magento\Swatches\Model\Swatch;
class Resin extends AbstractProduct implements IdentityInterface
{
private const XML_PATH = 'esun_homepage/resin/';
private const BACKGROUND_MEDIA_PATH = 'esun/homepage/resin/';
/**
* @var Product[]|null
*/
private ?array $products = null;
/**
* @var array<int, array<int, array<string, int|string>>>
*/
private array $colorSwatches = [];
public function __construct(
Context $context,
private readonly CollectionFactory $productCollectionFactory,
private readonly Visibility $productVisibility,
private readonly PriceCurrencyInterface $priceCurrency,
private readonly HttpContext $httpContext,
private readonly SwatchHelper $swatchHelper,
private readonly SwatchMediaHelper $swatchMediaHelper,
private readonly CardPriceResolver $cardPriceResolver,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return Product[]
*/
public function getProducts(): array
{
if ($this->products !== null) {
return $this->products;
}
$skus = $this->getConfiguredSkus();
if (!$skus) {
return $this->products = [];
}
$collection = $this->productCollectionFactory->create();
$collection->setStoreId((int) $this->_storeManager->getStore()->getId());
$this->_addProductAttributesAndPrices($collection);
$collection->addAttributeToSelect('short_description');
$collection->addStoreFilter();
$collection->addAttributeToFilter('sku', ['in' => $skus]);
$collection->addAttributeToFilter(
'visibility',
['in' => $this->productVisibility->getVisibleInSiteIds()]
);
$collection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$productsBySku = [];
foreach ($collection as $product) {
$productsBySku[strtolower((string) $product->getSku())] = $product;
}
$this->products = [];
foreach ($skus as $sku) {
$key = strtolower($sku);
if (isset($productsBySku[$key])) {
$this->products[] = $productsBySku[$key];
}
}
return $this->products;
}
public function getBackgroundImageUrl(): string
{
$image = ltrim(trim((string) $this->getConfig('background_image')), '/');
if ($image === '') {
return '';
}
return $this->_storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA)
. self::BACKGROUND_MEDIA_PATH
. $image;
}
public function getExploreAllUrl(): string
{
return trim((string) $this->getConfig('explore_all_url'));
}
public function getShortDescription(Product $product): string
{
return trim((string) preg_replace(
'/\s+/u',
' ',
strip_tags((string) $product->getData('short_description'))
));
}
/**
* @return array<int, array<string, int|string>>
*/
public function getColorSwatches(Product $product): array
{
$productId = (int) $product->getId();
if (isset($this->colorSwatches[$productId])) {
return $this->colorSwatches[$productId];
}
if ($product->getTypeId() !== 'configurable') {
return $this->colorSwatches[$productId] = [];
}
$colorAttribute = null;
foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $attribute) {
if ($attribute->getProductAttribute()->getAttributeCode() === 'color') {
$colorAttribute = $attribute->getProductAttribute();
$colorAttribute->setStoreId((int) $this->_storeManager->getStore()->getId());
break;
}
}
if ($colorAttribute === null) {
return $this->colorSwatches[$productId] = [];
}
$childIdsByGroup = $product->getTypeInstance()->getChildrenIds($productId);
$childIds = array_values(array_unique(array_map(
'intval',
array_merge(...array_values($childIdsByGroup ?: [[]]))
)));
if (!$childIds) {
return $this->colorSwatches[$productId] = [];
}
$childCollection = $this->productCollectionFactory->create();
$childCollection->setStoreId((int) $this->_storeManager->getStore()->getId());
$childCollection->addIdFilter($childIds);
$childCollection->addAttributeToSelect(['color', 'sku', 'image', 'small_image', 'thumbnail']);
$childCollection->addAttributeToFilter(
'status',
Product\Attribute\Source\Status::STATUS_ENABLED
);
$childCollection->setOrder('entity_id', 'ASC');
$childrenByOption = [];
foreach ($childCollection as $childProduct) {
$optionId = (int) $childProduct->getData('color');
if ($optionId > 0 && !isset($childrenByOption[$optionId])) {
$childrenByOption[$optionId] = $childProduct;
}
}
if (!$childrenByOption) {
return $this->colorSwatches[$productId] = [];
}
$swatchData = $this->swatchHelper->getSwatchesByOptionsId(array_keys($childrenByOption));
$result = [];
foreach ($childrenByOption as $optionId => $childProduct) {
$swatch = $swatchData[$optionId] ?? [];
$type = (int) ($swatch['type'] ?? Swatch::SWATCH_TYPE_EMPTY);
$value = (string) ($swatch['value'] ?? '');
$result[] = [
'id' => $optionId,
'sku' => (string) $childProduct->getSku(),
'label' => (string) $colorAttribute->getSource()->getOptionText($optionId),
'type' => $type,
'value' => $value,
'product_image' => $this->getProductImageUrl($childProduct),
'image' => $type === Swatch::SWATCH_TYPE_VISUAL_IMAGE && $value !== ''
? $this->swatchMediaHelper->getSwatchAttributeImage(
Swatch::SWATCH_IMAGE_NAME,
$value
)
: '',
];
}
return $this->colorSwatches[$productId] = $result;
}
public function getProductImageUrl(Product $product, string $imageId = 'category_page_grid'): string
{
return (string) $this->getImage($product, $imageId)->getImageUrl();
}
public function getFormattedFinalPrice(Product $product): string
{
return $this->formatPrice($this->getFinalPriceValue($product));
}
public function getFormattedRegularPrice(Product $product): string
{
return $this->formatPrice($this->getRegularPriceValue($product));
}
public function hasRegularPrice(Product $product): bool
{
return $this->getRegularPriceValue($product) > $this->getFinalPriceValue($product);
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_RESIN',
(int) $this->_storeManager->getStore()->getId(),
(int) $this->httpContext->getValue(CustomerContext::CONTEXT_GROUP),
sha1(implode('|', $this->getConfiguredSkus())),
sha1($this->getBackgroundImageUrl()),
sha1($this->getExploreAllUrl()),
];
}
public function getIdentities(): array
{
$identities = [];
foreach ($this->getProducts() as $product) {
$identities = array_merge($identities, $product->getIdentities());
}
return array_values(array_unique($identities));
}
private function getConfiguredSkus(): array
{
$value = (string) $this->getConfig('skus');
$skus = preg_split('/[\s,;]+/', $value, -1, PREG_SPLIT_NO_EMPTY) ?: [];
return array_values(array_unique(array_map('trim', $skus)));
}
private function getConfig(string $field): mixed
{
return $this->_scopeConfig->getValue(
self::XML_PATH . $field,
ScopeInterface::SCOPE_STORE
);
}
private function getFinalPriceValue(Product $product): float
{
return $this->cardPriceResolver->getFinalPrice($product);
}
private function getRegularPriceValue(Product $product): float
{
return $this->cardPriceResolver->getRegularPrice($product);
}
private function formatPrice(float $price): string
{
return $this->priceCurrency->format(
$price,
false,
PriceCurrencyInterface::DEFAULT_PRECISION,
$this->_storeManager->getStore()
);
}
}
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Esun\Homepage\Block;
use Esun\ImageManager\Model\Category;
use Esun\ImageManager\Model\Image;
use Esun\ImageManager\Model\ImageProvider;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\ScopeInterface;
class ResourcesDownloads extends Template implements IdentityInterface
{
private const XML_PATH_CATEGORY_ID = 'esun_homepage/resources_downloads/category_id';
/**
* @var array<int, array<string, int|string>>|null
*/
private ?array $items = null;
public function __construct(
Context $context,
private readonly ImageProvider $imageProvider,
array $data = []
) {
parent::__construct($context, $data);
}
/**
* @return array<int, array<string, int|string>>
*/
public function getItems(): array
{
if ($this->items === null) {
$this->items = array_values(array_filter(
$this->imageProvider->getImagesByCategoryId($this->getCategoryId()),
static fn (array $item): bool => trim((string) $item['thumbnail_url']) !== ''
));
}
return $this->items;
}
public function getCacheKeyInfo(): array
{
return [
'ESUN_HOMEPAGE_RESOURCES_DOWNLOADS',
(int) $this->_storeManager->getStore()->getId(),
$this->getCategoryId(),
];
}
public function getIdentities(): array
{
$identities = [];
$categoryId = $this->getCategoryId();
if ($categoryId > 0) {
$identities[] = Category::CACHE_TAG . '_' . $categoryId;
}
foreach ($this->getItems() as $item) {
$identities[] = Image::CACHE_TAG . '_' . (int) $item['id'];
}
return array_values(array_unique($identities));
}
private function getCategoryId(): int
{
return (int) $this->_scopeConfig->getValue(
self::XML_PATH_CATEGORY_ID,
ScopeInterface::SCOPE_STORE
);
}
}