<?php
declare(strict_types=1);
namespace Zeobv\BundleProducts\Storefront\Subscriber;
use Shopware\Core\Content\Product\SalesChannel\Price\AbstractProductPriceCalculator;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Zeobv\BundleProducts\Struct\BundleProduct\ProductBundle;
class SalesChannelBundleProductSubscriber implements EventSubscriberInterface
{
private AbstractProductPriceCalculator $calculator;
public function __construct(
AbstractProductPriceCalculator $calculator
) {
$this->calculator = $calculator;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'salesChannelLoaded',
'sales_channel.product.loaded' => 'salesChannelLoaded',
];
}
/**
* @param ProductPageLoadedEvent|SalesChannelEntityLoadedEvent $event
*/
public function salesChannelLoaded($event): void
{
if ($event instanceof ProductPageLoadedEvent) {
if (!$event->getPage()->getProduct()->hasExtension(ProductBundle::EXTENSION_NAME)) {
return;
}
$product = $event->getPage()->getProduct();
} elseif ($event instanceof SalesChannelEntityLoadedEvent) {
if (
count($event->getIds()) !== 1
|| !current($event->getEntities())->hasExtension(ProductBundle::EXTENSION_NAME)
) {
return;
}
$product = current($event->getEntities());
} else {
return;
}
$this->calculator->calculate(
$product->getExtension(ProductBundle::EXTENSION_NAME)->getSalesChannelProducts(),
$event->getSalesChannelContext()
);
}
}