<?php
namespace Wbfk\Bundles\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class BundleSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly EntityRepository $bundleRepository)
{
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents(): array
{
return [
'wbfk_bundle_product.written' => 'onBundleProductWritten',
];
}
/**
* @throws \Exception
*/
public function onBundleProductWritten(EntityWrittenEvent $event): void
{
$isBundleUsedAsChild = false;
foreach ($event->getPayloads() as $payload) {
if (!isset($payload['productId']) || !isset($payload['childProductId'])) {
continue;
}
if ($payload['productId'] === $payload['childProductId']) {
$isBundleUsedAsChild = true;
$this->bundleRepository->delete([['id'=>$payload['id']]], $event->getContext());
}
}
if ($isBundleUsedAsChild) {
throw new \Exception('A bundle cannot be used as its own child product.');
}
}
}