<?php declare(strict_types=1);
namespace Nd\Srs\Subscriber;
use Shopware\Core\Checkout\Cart\Event\AfterLineItemAddedEvent;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class ModifyLineItems implements EventSubscriberInterface
{
protected $productRepository;
public function __construct(EntityRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
BeforeLineItemAddedEvent::class => 'changeLineItem',
];
}
function changeLineItem(BeforeLineItemAddedEvent $event)
{
$lineItem = $event->getLineItem();
if ($lineItem->getType() == "product") {
if (!$lineItem->hasPayloadValue("manufacturerName")) {
$product = $this->getProductById($lineItem->getReferencedId(), $event->getContext());
if ($product) {
$ean = $product->getEan();
if ($ean) {
$lineItem->setPayloadValue("ean", $ean);
}
}
}
}
}
function getProductById(string $productId, Context $context)
{
if (!$productId) {
return;
}
$criteria = new Criteria([$productId]);
return $this->productRepository->search($criteria, $context)->first();
}
}