custom/static-plugins/NdSRS/src/Subscriber/ModifyLineItems.php line 30

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Nd\Srs\Subscriber;
  3. use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
  4. use Shopware\Core\Framework\Context;
  5. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  6. use Shopware\Core\Framework\Uuid\Uuid;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. class ModifyLineItems implements EventSubscriberInterface
  11. {
  12.     protected $productRepository;
  13.     public function __construct(EntityRepository $productRepository)
  14.     {
  15.         $this->productRepository $productRepository;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         // Return the events to listen to as array like this:  <event to listen to> => <method to execute>
  20.         return [
  21.             BeforeLineItemAddedEvent::class => 'changeLineItem',
  22.         ];
  23.     }
  24.     function changeLineItem(BeforeLineItemAddedEvent $event)
  25.     {
  26.         $lineItem $event->getLineItem();
  27.         if ($lineItem->getType() == "product") {
  28.             if (!$lineItem->hasPayloadValue("manufacturerName")) {
  29.                 $product $this->getProductById($lineItem->getReferencedId(), $event->getContext());
  30.                 if ($product) {
  31.                     $ean $product->getEan();
  32.                     if ($ean) {
  33.                         $lineItem->setPayloadValue("ean"$ean);
  34.                     }
  35.                 }
  36.             }
  37.         }
  38.     }
  39.     function getProductById(string $productIdContext $context)
  40.     {
  41.         if (!$productId) {
  42.             return;
  43.         }
  44.         $criteria = new Criteria([$productId]);
  45.         return $this->productRepository->search($criteria$context)->first();
  46.     }
  47. }