custom/plugins/WabsOrderExtension/src/Subscriber/FrontendSubscriber.php line 35

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Wabs\OrderExtension\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
  4. use Shopware\Core\Checkout\Cart\Event\LineItemAddedEvent;
  5. use Shopware\Core\Content\Product\ProductEntity;
  6. use Shopware\Core\Framework\Context;
  7. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. class FrontendSubscriber implements EventSubscriberInterface
  11. {
  12.     private $productRepository;
  13.     public function __construct(EntityRepositoryInterface $productRepository)
  14.     {
  15.         $this->productRepository $productRepository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         $listeners = [];
  20.         if (class_exists('Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent')) {
  21.             $listeners[BeforeLineItemAddedEvent::class] = 'onLineItemAdded';
  22.         } else {
  23.             $listeners[LineItemAddedEvent::class] = 'onLineItemAdded';
  24.         }
  25.         return $listeners;
  26.     }
  27.     public function onLineItemAdded($event): void
  28.     {
  29.         $lineItem $event->getLineItem();
  30.         if ($lineItem->getType() === 'product') {
  31.             $context Context::createDefaultContext();
  32.             /** @var ProductEntity $product */
  33.             $product $this->productRepository->search((new Criteria([$lineItem->getReferencedId()])),
  34.                 $context)->first();
  35.             if ($product->getActive()) {
  36.                 $lineItem->setPayloadValue('packUnit'$product->getPackUnit());
  37.                 $lineItem->setPayloadValue('packUnitPlural'$product->getPackUnitPlural());
  38.                 $lineItem->setPayloadValue('purchaseUnit'$product->getPurchaseUnit());
  39.             }
  40.         }
  41.     }
  42. }