<?php declare(strict_types=1);
namespace DkcPentagastOrderExport\Subscriber;
use DkcPentagastOrderExport\Service\PentagastOrderExportService;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\SalesChannelEntity;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderCreatedSubscriber implements EventSubscriberInterface
{
private PentagastOrderExportService $exportService;
private EntityRepository $orderRepository;
/** @var mixed */
private $salesChannelRepository;
private SystemConfigService $systemConfigService;
public function __construct(
PentagastOrderExportService $exportService,
EntityRepository $orderRepository,
$salesChannelRepository,
SystemConfigService $systemConfigService
) {
$this->exportService = $exportService;
$this->orderRepository = $orderRepository;
$this->salesChannelRepository = $salesChannelRepository;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'onOrderWritten',
];
}
public function onOrderWritten(EntityWrittenEvent $event): void
{
$context = $event->getContext();
$ids = $event->getIds();
if (empty($ids)) {
return;
}
$criteria = (new Criteria($ids))
->addAssociation('salesChannel')
->addAssociation('lineItems')
->addAssociation('deliveries')
->addAssociation('deliveries.shippingOrderAddress.country')
->addAssociation('transactions.paymentMethod')
->addAssociation('billingAddress.country')
->addAssociation('orderCustomer');
$orders = $this->orderRepository->search($criteria, $context);
/** @var OrderEntity $order */
foreach ($orders as $order) {
/** @var SalesChannelEntity|null $salesChannel */
$salesChannel = $order->getSalesChannel();
if (!$salesChannel) {
$salesChannelId = $order->getSalesChannelId();
$criteria = new Criteria([$salesChannelId]);
$salesChannel = $this->salesChannelRepository->search($criteria, $context)->first();
if (!$salesChannel) {
continue;
}
}
$salesChannelId = $salesChannel->getId();
$triggerState = (string) ($this->systemConfigService->get(
'DkcPentagastOrderExport.config.triggerState',
$salesChannelId
) ?? 'transaction_paid');
if ($triggerState !== 'all_orders') {
continue;
}
$this->exportService->exportOrder($order, $salesChannel);
}
}
}