custom/plugins/WbfkBundles/src/Subscriber/BundleSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace Wbfk\Bundles\Subscriber;
  3. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  4. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. class BundleSubscriber implements EventSubscriberInterface
  7. {
  8.     public function __construct(private readonly EntityRepository $bundleRepository)
  9.     {
  10.     }
  11.     /**
  12.      * @inheritDoc
  13.      */
  14.     public static function getSubscribedEvents(): array
  15.     {
  16.         return [
  17.             'wbfk_bundle_product.written' => 'onBundleProductWritten',
  18.         ];
  19.     }
  20.     /**
  21.      * @throws \Exception
  22.      */
  23.     public function onBundleProductWritten(EntityWrittenEvent $event): void
  24.     {
  25.         $isBundleUsedAsChild false;
  26.         foreach ($event->getPayloads() as $payload) {
  27.             if (!isset($payload['productId']) || !isset($payload['childProductId'])) {
  28.                 continue;
  29.             }
  30.             if ($payload['productId'] === $payload['childProductId']) {
  31.                 $isBundleUsedAsChild true;
  32.                 $this->bundleRepository->delete([['id'=>$payload['id']]], $event->getContext());
  33.             }
  34.         }
  35.         if ($isBundleUsedAsChild) {
  36.             throw new \Exception('A bundle cannot be used as its own child product.');
  37.         }
  38.     }
  39. }