<?php declare(strict_types=1);
namespace Acris\ProductBadges\Storefront\Subscriber;
use Acris\ProductBadges\Components\ProductBadges\ProductBadgesService;
use Acris\ProductBadges\Components\ProductBadges\Struct\BadgeLoadingAllowedStruct;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
use Shopware\Core\System\SalesChannel\Event\SalesChannelProcessCriteriaEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductBadgeSubscriber implements EventSubscriberInterface
{
public const ACRIS_STREAM_IDS_EXTENSION = 'acrisStreamIds';
public const CRITERIA_TITLE_BLACKLIST = [
'cart::products'
];
private ProductBadgesService $productBadgeService;
public function __construct(ProductBadgesService $productBadgeService)
{
$this->productBadgeService = $productBadgeService;
}
public static function getSubscribedEvents(): array
{
return [
'sales_channel.product.process.criteria' => 'onProductCriteriaLoaded',
'sales_channel.product.loaded' => ['onProductLoaded', -60]
];
}
public function onProductCriteriaLoaded(SalesChannelProcessCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
if(!empty($criteria->getTitle()) && in_array($criteria->getTitle(), self::CRITERIA_TITLE_BLACKLIST)) {
$event->getContext()->addExtension(BadgeLoadingAllowedStruct::EXTENSION_KEY, new BadgeLoadingAllowedStruct(false));
return;
} else {
$event->getContext()->addExtension(BadgeLoadingAllowedStruct::EXTENSION_KEY, new BadgeLoadingAllowedStruct(true));
}
if($criteria->hasAssociation('streams') === false) {
$criteria->addAssociation('streams');
}
}
public function onProductLoaded(SalesChannelEntityLoadedEvent $event): void
{
if($event->getContext()->hasExtension(BadgeLoadingAllowedStruct::EXTENSION_KEY) && $event->getContext()->getExtension(BadgeLoadingAllowedStruct::EXTENSION_KEY)->isAllowed() !== true) {
return;
}
$productCollection = new EntityCollection();
foreach ($event->getEntities() as $product) {
if ($product instanceof SalesChannelProductEntity) {
$productCollection->add($product);
}
}
$this->productBadgeService->addBadgesToProducts($productCollection, $event->getSalesChannelContext());
}
}