<?php
declare(strict_types=1);
namespace MadBodymedBundle\Subscriber;
use MadBodymedBundle\Core\Content\Product\ProductExtension;
use MadBodymedBundle\Service\BundleChecker;
use MadBodymedBundle\Service\BundleConfigurationLoader;
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTax;
use Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
private BundleChecker $bundleChecker;
private BundleConfigurationLoader $bundleConfigurationLoader;
public function __construct(BundleChecker $bundleChecker, BundleConfigurationLoader $bundleConfigurationLoader)
{
$this->bundleChecker = $bundleChecker;
$this->bundleConfigurationLoader = $bundleConfigurationLoader;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
ProductPageLoadedEvent::class => 'onProductPageLoaded',
'product.loaded' => 'onProductLoaded',
#ProductPageCriteriaEvent::class => 'onProductPageCriteria',
];
}
public function onProductLoaded(EntityLoadedEvent $event)
{
/* @var $product ProductEntity */
foreach ($event->getEntities() as $product) {
if ($this->isProductBundle($product)) {
// @todo Alternative suchen
#$product->setGrouped(true);
}
}
}
public function onProductPageCriteria(ProductPageCriteriaEvent $event)
{
#$event->getCriteria()->addAssociation('bundle');
#$event->getCriteria()->addAssociation('bundle_product.bundle_id');
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$mainProduct = $event->getPage()->getProduct();
$salesChannelContext = $event->getSalesChannelContext();
if ($this->isProductBundle($mainProduct)) {
$bundle = $this->bundleConfigurationLoader->loadBundleConfigForMainProduct(
$mainProduct,
$salesChannelContext
);
if ($bundle) {
$mainProduct->addExtension(ProductExtension::PRODUCT_EXTENSION_BUNDLE, $bundle);
#$mainProduct->setGrouped(true);
}
}
}
private function isProductBundle(ProductEntity $productEntity): bool
{
return $this->bundleChecker->isProductBundle($productEntity);
}
}