<?php declare(strict_types=1);
namespace Wabs\OrderExtension\Subscriber;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\Event\LineItemAddedEvent;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FrontendSubscriber implements EventSubscriberInterface
{
private $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
$listeners = [];
if (class_exists('Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent')) {
$listeners[BeforeLineItemAddedEvent::class] = 'onLineItemAdded';
} else {
$listeners[LineItemAddedEvent::class] = 'onLineItemAdded';
}
return $listeners;
}
public function onLineItemAdded($event): void
{
$lineItem = $event->getLineItem();
if ($lineItem->getType() === 'product') {
$context = Context::createDefaultContext();
/** @var ProductEntity $product */
$product = $this->productRepository->search((new Criteria([$lineItem->getReferencedId()])),
$context)->first();
if ($product->getActive()) {
$lineItem->setPayloadValue('packUnit', $product->getPackUnit());
$lineItem->setPayloadValue('packUnitPlural', $product->getPackUnitPlural());
$lineItem->setPayloadValue('purchaseUnit', $product->getPurchaseUnit());
}
}
}
}