<?php
declare(strict_types=1);
namespace Zeobv\VisibleDiscounts\Storefront\Subscriber;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Zeobv\VisibleDiscounts\Service\ConfigService;
use Zeobv\VisibleDiscounts\Service\PromotionService;
/**
* Class SalesChannelSubscriber
*
* @package Zeobv\VisibleDiscounts\Storefront\Subscriber
*/
class SalesChannelSubscriber implements EventSubscriberInterface
{
protected PromotionService $promotionService;
protected ConfigService $configService;
/**
* SalesChannelSubscriber constructor.
*/
public function __construct(
PromotionService $promotionService,
ConfigService $configService
)
{
$this->promotionService = $promotionService;
$this->configService = $configService;
}
/**
* @return array<string>
*/
public static function getSubscribedEvents(): array
{
return ['sales_channel.product.loaded' => 'loaded'];
}
/**
* @throws \Exception
*/
public function loaded(SalesChannelEntityLoadedEvent $event): void
{
$salesChannelContext = $event->getSalesChannelContext();
$activateVisibleDiscounts = $this->configService->getActivateVisibleDiscounts($salesChannelContext->getSalesChannel());
if ($activateVisibleDiscounts== false) {
return;
}
# Event can get fired multiple times, return to avoid applying discounts multiple times
if ($salesChannelContext->hasExtension('zeobvDiscountsApplied')) {
return;
}
$salesChannelContext->addExtension('zeobvDiscountsApplied', new ArrayEntity(['applied' => true]));
$this->promotionService->overrideCalculatedListPrices($event->getEntities(), $salesChannelContext);
# Clean up
$salesChannelContext->removeExtension('zeobvDiscountsApplied');
}
}