<?php
namespace Proclane\WegmannTheme\Subscriber;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\Exception\LineItemNotFoundException;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Content\Product\Cart\ProductNotFoundError;
class CartSubscriber implements EventSubscriberInterface {
public function __construct(private readonly EntityRepository $productRepository) {
}
public static function getSubscribedEvents(): array
{
return [
BeforeLineItemAddedEvent::class => 'onBeforeLineItemAdded'
];
}
public function onBeforeLineItemAdded(BeforeLineItemAddedEvent $event): void
{
// If promotion --> skip
if($event->getLineItem()->getType() === LineItem::PROMOTION_LINE_ITEM_TYPE) {
return;
}
$customFields = $event->getSalesChannelContext()?->getCustomer()?->getCustomFields();
$lineItemId = $event->getLineItem()->getId();
$context = $event->getContext();
$cart = $event->getCart();
$criteria = new Criteria([$lineItemId]);
$products = $this->productRepository->search($criteria, $context)->getEntities()->first();
$lineItemProductNumber = $products->getProductNumber();
$allowedProducts = $customFields['custom_product_listing_numbers'] ?? null;
if ($allowedProducts) {
$allowedProducts = explode("," , $allowedProducts);
if(!in_array($lineItemProductNumber, $allowedProducts)) {
// throw new LineItemNotFoundException($lineItemProductNumber);
$cart->remove($lineItemId);
$event->getCart()->getErrors()->add(new ProductNotFoundError($lineItemId));
}
}
}
}