<?php
namespace B2bOffer\Subscriber;
use Doctrine\DBAL\Connection;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\Event\BeforeDeleteEvent;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductDeletionSubscriber implements EventSubscriberInterface
{
private Connection $connection;
private SystemConfigService $configService;
public function __construct(
Connection $connection,
SystemConfigService $configService
)
{
$this->connection = $connection;
$this->configService = $configService;
}
public static function getSubscribedEvents()
{
return [
BeforeDeleteEvent::class => 'convertOfferProductItemsBeforeDeletion'
];
}
public function convertOfferProductItemsBeforeDeletion(BeforeDeleteEvent $event)
{
$offerStatusId = $this->configService->get('B2bOffer.config.defaultInvalidOfferStatusId');
if(empty($offerStatusId) || !Uuid::isValid($offerStatusId)) {
return;
}
foreach ($event->getCommands() as $command) {
if($command->getEntityName() !== ProductDefinition::ENTITY_NAME) {
continue;
}
$primaryKeys = $command->getPrimaryKey();
if(isset($primaryKeys['version_id']) && Uuid::fromBytesToHex($primaryKeys['version_id']) !== Defaults::LIVE_VERSION) {
continue;
}
if(!isset($primaryKeys['id'])) {
continue;
}
$this->connection->executeStatement("
UPDATE `b2b_offer_item`
LEFT JOIN `b2b_offer` ON `b2b_offer_item`.`offer_id` = `b2b_offer`.`id`
SET `b2b_offer_item`.`type` = 'custom',
`b2b_offer_item`.`label` = CONCAT(`b2b_offer_item`.`label`, ' (deleted)'),
`b2b_offer_item`.`product_id` = NULL,
`b2b_offer`.`status_id` = :statusId
WHERE `b2b_offer_item`.`type` = 'product' AND `b2b_offer_item`.`product_id` = :productId
", ['productId' => $primaryKeys['id'], 'statusId' => Uuid::fromHexToBytes($offerStatusId)]);
}
}
}