<?php declare(strict_types=1);
namespace Ew\GrecoBundle\Subscriber;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepository
*/
private $customerDnaProductRepository;
public function __construct(
EntityRepository $customerDnaProductRepository
)
{
$this->customerDnaProductRepository = $customerDnaProductRepository;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'onOrderPlaced'
];
}
public function onOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
try {
$order = $event->getOrder();
$customerId = $order->getOrderCustomer()->getCustomerId();
$lineItems = $order->getLineItems();
/** @var OrderLineItemEntity $lineItem */
foreach ($lineItems as $lineItem) {
$payload = $lineItem->getPayload();
$customFields = [];
if (isset($payload['customFields'])) {
$customFields = $payload['customFields'];
}
if ($customFields) {
if (isset($customFields['greco_dna_article']) && $customFields['greco_dna_article'] === true) {
$productId = $lineItem->getReferencedId();
if ($productId && $customerId) {
$this->customerDnaProductRepository->upsert(
[['id' => Uuid::randomHex(), 'customerId' => $customerId, 'productId' => $productId]], $event->getContext()
);
}
}
}
}
} catch (\Exception $exception) {
}
}
}