<?php declare(strict_types=1);
namespace GrecoBarcode\Subscriber;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SalesChannel\Event\SalesChannelContextTokenChangeEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OrderBarcodeSubscriber implements EventSubscriberInterface
{
private EntityRepository $cartBarcodeRepository;
private SystemConfigService $systemConfigService;
public function __construct(
EntityRepository $cartBarcodeRepository,
SystemConfigService $systemConfigService
)
{
$this->cartBarcodeRepository = $cartBarcodeRepository;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
CartConvertedEvent::class => 'onCartConverted',
SalesChannelContextTokenChangeEvent::class => 'onTokenChanged'
];
}
public function onCartConverted(CartConvertedEvent $event): void
{
$configBarcodeActive = $this->systemConfigService->get('GrecoBarcode.config.active');
if ($configBarcodeActive === false) {
return;
}
/**
* ["id", "orderNumber"]
*/
$order = $event->getConvertedCart();
$cart = $event->getCart();
$configBarcodeProducts = $this->systemConfigService->get('GrecoBarcode.config.products');
if (!$configBarcodeProducts || count($configBarcodeProducts) <= 0) {
$active = true;
} else {
$active = false;
foreach ($cart->getLineItems() as $item) {
if (in_array($item->getId(), $configBarcodeProducts)) {
$active = true;
}
}
}
if (!$active) {
return;
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('cart_token', $cart->getToken()));
try {
$cartBarcode = $this->cartBarcodeRepository->search($criteria, Context::createDefaultContext())->first();
if ($cartBarcode) {
$cartBarcode = $cartBarcode->getBarcode();
}
} catch (\Exception $ex) {
$cartBarcode = null;
}
if (!$cartBarcode) {
return;
}
$order['customFields']['barcode'] = $cartBarcode;
$event->setConvertedCart($order);
}
public function onTokenChanged(SalesChannelContextTokenChangeEvent $event) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('cart_token', $event->getPreviousToken()));
try {
$cartBarcode = $this->cartBarcodeRepository->search($criteria, Context::createDefaultContext())->first();
} catch (\Exception $ex) {
$cartBarcode = null;
}
if ($cartBarcode) {
$this->cartBarcodeRepository->update([
[
'id' => $cartBarcode->getId(),
'cart_token' => $event->getCurrentToken(),
]
], Context::createDefaultContext());
}
}
}