<?php declare(strict_types=1);
namespace Ies\ProductNote\Subscriber;
use Ies\ProductNote\Services\MediaUpdater;
use Ies\ProductNote\Services\OrderUpdater;
use Ies\ProductNote\Services\ProductNoteService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Content\Media\MediaEntity;
use Shopware\Core\Framework\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\LineItem\LineItemCollection;
/**
* @author Lei Wang <lei.wang@isento-ecommcerce.de>
* @copyright 2022 isento eCommerce solutions GmbH
*/
class CheckoutConfirm implements EventSubscriberInterface
{
private ProductNoteService $productNoteService;
private OrderUpdater $orderUpdater;
private MediaUpdater $mediaUpdater;
public function __construct(
ProductNoteService $productNoteService,
OrderUpdater $orderUpdater,
MediaUpdater $mediaUpdater
) {
$this->productNoteService = $productNoteService;
$this->orderUpdater = $orderUpdater;
$this->mediaUpdater = $mediaUpdater;
}
public static function getSubscribedEvents()
{
return [
CartConvertedEvent::class => 'onCartConverted',
CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
];
}
public function onCartConverted(CartConvertedEvent $event)
{
$convertedCart = $event->getConvertedCart();
$salesChannelContext = $event->getSalesChannelContext();
$convertedCart = $this->addProductNoteToConvertedCart(
$convertedCart,
$event->getCart()->getLineItems(),
$salesChannelContext->getContext()
);
$event->setConvertedCart($convertedCart);
}
public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
$context = $event->getContext();
$order = $this->orderUpdater->updateCustomField($event->getOrderId(), $context);
$this->mediaUpdater->updateCustomField($order, $context);
$this->productNoteService->removeAll();
}
private function addProductNoteToConvertedCart(
array $convertedCart,
LineItemCollection $cartLineItems,
Context $context
): array {
foreach ($convertedCart['lineItems'] as $index => $convertedLineItem) {
$cartLineItem = $cartLineItems->get($convertedLineItem['identifier']);
if ($productNote = $this->productNoteService->getProductNote($cartLineItem->getId(), $context)) {
$convertedCart['lineItems'][$index]['customFields']['ies_product_note'] = $productNote;
}
}
return $convertedCart;
}
}