custom/plugins/ZeobvBundleProducts/src/Storefront/Subscriber/SalesChannelBundleProductSubscriber.php line 37

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Zeobv\BundleProducts\Storefront\Subscriber;
  4. use Shopware\Core\Content\Product\SalesChannel\Price\AbstractProductPriceCalculator;
  5. use Shopware\Core\System\SalesChannel\Entity\SalesChannelEntityLoadedEvent;
  6. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Zeobv\BundleProducts\Struct\BundleProduct\ProductBundle;
  9. class SalesChannelBundleProductSubscriber implements EventSubscriberInterface
  10. {
  11.     private AbstractProductPriceCalculator $calculator;
  12.     public function __construct(
  13.         AbstractProductPriceCalculator $calculator
  14.     ) {
  15.         $this->calculator $calculator;
  16.     }
  17.     /**
  18.      * @return string[]
  19.      */
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             ProductPageLoadedEvent::class => 'salesChannelLoaded',
  24.             'sales_channel.product.loaded' => 'salesChannelLoaded',
  25.         ];
  26.     }
  27.     /**
  28.      * @param ProductPageLoadedEvent|SalesChannelEntityLoadedEvent $event
  29.      */
  30.     public function salesChannelLoaded($event): void
  31.     {
  32.         if ($event instanceof ProductPageLoadedEvent) {
  33.             if (!$event->getPage()->getProduct()->hasExtension(ProductBundle::EXTENSION_NAME)) {
  34.                 return;
  35.             }
  36.             $product $event->getPage()->getProduct();
  37.         } elseif ($event instanceof SalesChannelEntityLoadedEvent) {
  38.             if (
  39.                 count($event->getIds()) !== 1
  40.                 || !current($event->getEntities())->hasExtension(ProductBundle::EXTENSION_NAME)
  41.             ) {
  42.                 return;
  43.             }
  44.             $product current($event->getEntities());
  45.         } else {
  46.             return;
  47.         }
  48.         $this->calculator->calculate(
  49.             $product->getExtension(ProductBundle::EXTENSION_NAME)->getSalesChannelProducts(),
  50.             $event->getSalesChannelContext()
  51.         );
  52.     }
  53. }