custom/plugins/WbfkMultipleDeliveries/src/Subscriber/OrderDeliverySubscriber.php line 29

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Wbfk\MultipleDeliveries\Subscriber;
  4. use Shopware\Core\Framework\Context;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class OrderDeliverySubscriber implements EventSubscriberInterface
  12. {
  13. public function __construct(private readonly EntityRepository $wbfkOrderDeliveryExtensionRepository)
  14. {
  15. }
  16. public static function getSubscribedEvents(): array
  17. {
  18. return [
  19. 'order_delivery.written' => 'onOrderDeliveryWritten',
  20. ];
  21. }
  22. public function onOrderDeliveryWritten(EntityWrittenEvent $event): void
  23. {
  24. foreach ($event->getWriteResults() as $entityWriteResult) {
  25. if ($this->isNewDelivery($entityWriteResult)) {
  26. $this->createOrderDeliveryExtensionIfNotExists($entityWriteResult, $event->getContext());
  27. }
  28. }
  29. }
  30. public function isNewDelivery(EntityWriteResult $entityWriteResult): bool
  31. {
  32. return $entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT;
  33. }
  34. private function createOrderDeliveryExtensionIfNotExists(EntityWriteResult $entityWriteResult, Context $context): void
  35. {
  36. $criteria = new Criteria();
  37. $criteria->addFilter(
  38. new EqualsFilter('orderDeliveryId', $entityWriteResult->getPrimaryKey())
  39. )->addFilter(
  40. new EqualsFilter('orderDeliveryVersionId', $context->getVersionId())
  41. );
  42. $existing = $this->wbfkOrderDeliveryExtensionRepository->search($criteria, $context)->first();
  43. if ($existing) {
  44. return;
  45. }
  46. $this->wbfkOrderDeliveryExtensionRepository->create([
  47. [
  48. 'orderDeliveryId' => $entityWriteResult->getPrimaryKey(),
  49. 'orderDeliveryVersionId' => $context->getVersionId(),
  50. ],
  51. ], $context);
  52. }
  53. }