<?php declare(strict_types=1);
namespace Kilb\KilbShopwareProductDesigner\Subscriber;
use Kilb\KilbShopwareProductDesigner\Constants;
use Kilb\KilbShopwareProductDesigner\Services\DesignGroupServiceInterface;
use Kilb\KilbShopwareProductDesigner\Services\ProductServiceInterface;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderSubscriber implements EventSubscriberInterface
{
/**
* @var DesignGroupServiceInterface
*/
private $designGroupService;
/**
* @var ProductServiceInterface
*/
private $productService;
/**
* @param DesignGroupServiceInterface $designGroupService
* @param ProductServiceInterface $productService
*/
public function __construct(
DesignGroupServiceInterface $designGroupService,
ProductServiceInterface $productService
) {
$this->designGroupService = $designGroupService;
$this->productService = $productService;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return[
CheckoutOrderPlacedEvent::class => 'onOrderPlaced',
];
}
/**
* @param CheckoutOrderPlacedEvent $event
* @throws \Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException
*/
public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
$order = $event->getOrder();
$context = $event->getContext();
foreach ($order->getLineItems() ?: [] as $lineItem) {
$payload = $lineItem->getPayload();
if (true === empty($payload[Constants::LINE_ITEM_PAYLOAD_KEY_PRODUCT_NUMBER])) {
continue;
}
$product = $this->productService->getProductByProductNumber(
$payload[Constants::LINE_ITEM_PAYLOAD_KEY_PRODUCT_NUMBER],
$context
);
if (null === $product) {
continue;
}
if (!empty($lineItem->getPayload()[Constants::LINE_ITEM_PAYLOAD_KEY_GROUP_SECRET])) {
$secret = $lineItem->getPayload()[Constants::LINE_ITEM_PAYLOAD_KEY_GROUP_SECRET];
$data = [
'orderId' => $order->getId(),
'productId' => $product->getId(),
'orderLineItemId' => $lineItem->getId(),
'orderedAt' => date('Y-m-d H:i:s'),
];
$this->designGroupService->updateDesignGroupBySecret(
$secret,
$data,
$context
);
}
}
}
}