<?php declare(strict_types=1);
namespace Okeonline\MyKeje\Storefront\Subscriber;
use Doctrine\DBAL\Connection;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderCreatedEventSubscriber implements EventSubscriberInterface
{
/** @var EntityRepository $orderRepository */
private $orderRepository;
/** @var Connection $connection */
private $connection;
public function __construct(
EntityRepository $orderRepository,
Connection $connection
)
{
$this->orderRepository = $orderRepository;
$this->connection = $connection;
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'manipulateReferenceTable'
];
}
public function manipulateReferenceTable(EntityWrittenEvent $event)
{
$writeResults = $event->getWriteResults();
$entityName = $event->getEntityName();
if( ! $entityName == 'order' || ! $writeResults || ! is_array($writeResults) || count($writeResults) == 0)
return;
foreach ($writeResults as $entityWriteResult)
{
$orderId = $entityWriteResult->getPrimaryKey();
$criteria = new Criteria([$orderId]);
$criteria->addAssociation('order_customer');
$result = $this->orderRepository->search($criteria, $event->getContext());
if($result->count() !== 1)
continue;
$order = $result->getEntities()->first();
$customerId = $order->getOrderCustomer()->getCustomerId();
$this->connection->executeStatement(sprintf("
DELETE FROM `oo_mykeje_reference` WHERE `customer_id` = UNHEX('%s') AND `order_id` = UNHEX('%s') AND `order_line_item_id` = NULL;
", $customerId, $orderId));
if(is_array($order->getCustomFields()) && array_key_exists('oo_checkout_extra_data_reference', $order->getCustomFields()) && !is_null($order->getCustomFields()['oo_checkout_extra_data_reference']))
{
$reference = addslashes($order->getCustomFields()['oo_checkout_extra_data_reference']);
$this->connection->executeStatement(sprintf("
INSERT INTO `oo_mykeje_reference` (`customer_id`, `order_id`, `order_line_item_id`, `reference`) VALUES (UNHEX('%s'), UNHEX('%s'), NULL, '%s');
", $customerId, $orderId, $reference));
}
}
}
}