custom/plugins/ProcWegmannTheme/src/Subscriber/CartSubscriber.php line 26

Open in your IDE?
  1. <?php 
  2. namespace Proclane\WegmannTheme\Subscriber;
  3. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
  6. use Shopware\Core\Checkout\Cart\Exception\LineItemNotFoundException;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  9. use Shopware\Core\Content\Product\Cart\ProductNotFoundError;
  10. class CartSubscriber implements EventSubscriberInterface {
  11.     public function __construct(private readonly EntityRepository $productRepository) {
  12.     }
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             BeforeLineItemAddedEvent::class => 'onBeforeLineItemAdded'
  17.         ];
  18.     }
  19.     public function onBeforeLineItemAdded(BeforeLineItemAddedEvent $event): void
  20.     {
  21.         // If promotion --> skip
  22.         if($event->getLineItem()->getType() === LineItem::PROMOTION_LINE_ITEM_TYPE) {
  23.             return;
  24.         }
  25.         $customFields $event->getSalesChannelContext()?->getCustomer()?->getCustomFields();
  26.         $lineItemId $event->getLineItem()->getId();
  27.         $context $event->getContext();
  28.         $cart $event->getCart();
  29.         
  30.         $criteria = new Criteria([$lineItemId]);
  31.         $products $this->productRepository->search($criteria$context)->getEntities()->first();
  32.         $lineItemProductNumber $products->getProductNumber();
  33.         $allowedProducts $customFields['custom_product_listing_numbers'] ?? null;
  34.         if ($allowedProducts) {
  35.             $allowedProducts explode("," $allowedProducts);
  36.             if(!in_array($lineItemProductNumber$allowedProducts)) {
  37.                // throw new LineItemNotFoundException($lineItemProductNumber);
  38.                 $cart->remove($lineItemId);
  39.                 $event->getCart()->getErrors()->add(new ProductNotFoundError($lineItemId));
  40.             }
  41.         }
  42.     }
  43. }