<?php
declare(strict_types=1);
namespace Wbfk\MultipleDeliveries\Subscriber;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderDeliverySubscriber implements EventSubscriberInterface
{
public function __construct(private readonly EntityRepository $wbfkOrderDeliveryExtensionRepository)
{
}
public static function getSubscribedEvents(): array
{
return [
'order_delivery.written' => 'onOrderDeliveryWritten',
];
}
public function onOrderDeliveryWritten(EntityWrittenEvent $event): void
{
foreach ($event->getWriteResults() as $entityWriteResult) {
if ($this->isNewDelivery($entityWriteResult)) {
$this->createOrderDeliveryExtensionIfNotExists($entityWriteResult, $event->getContext());
}
}
}
public function isNewDelivery(EntityWriteResult $entityWriteResult): bool
{
return $entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT;
}
private function createOrderDeliveryExtensionIfNotExists(EntityWriteResult $entityWriteResult, Context $context): void
{
$criteria = new Criteria();
$criteria->addFilter(
new EqualsFilter('orderDeliveryId', $entityWriteResult->getPrimaryKey())
)->addFilter(
new EqualsFilter('orderDeliveryVersionId', $context->getVersionId())
);
$existing = $this->wbfkOrderDeliveryExtensionRepository->search($criteria, $context)->first();
if ($existing) {
return;
}
$this->wbfkOrderDeliveryExtensionRepository->create([
[
'orderDeliveryId' => $entityWriteResult->getPrimaryKey(),
'orderDeliveryVersionId' => $context->getVersionId(),
],
], $context);
}
}