<?php declare(strict_types=1);
namespace Neon\Configurator\Subscribers;
use Neon\Configurator\Exceptions\CalculationFormulaException;
use Neon\Configurator\Neon6Configurator;
use Neon\Configurator\Services\LineItemEnricher;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class OnLineItemAdded implements EventSubscriberInterface
{
/** @var RequestStack */
private $requestStack;
private LineItemEnricher $lineItemEnricher;
public function __construct($requestStack, $lineItemEnricher)
{
$this->requestStack = $requestStack;
$this->lineItemEnricher = $lineItemEnricher;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
BeforeLineItemAddedEvent::class => 'onLineItemAdded'
];
}
/**
* @param BeforeLineItemAddedEvent $event
* @throws CalculationFormulaException
*/
public function onLineItemAdded(BeforeLineItemAddedEvent $event): void
{
$lineItem = $event->getLineItem();
$isExistingProductAfterLogin = $event->getLineItem()->getPayloadValue(Neon6Configurator::PAYLOAD_KEY) != null;
if (!$isExistingProductAfterLogin && $lineItem->getType() === LineItem::PRODUCT_LINE_ITEM_TYPE) {
$lineItemParam = $this->requestStack->getCurrentRequest()->request->all('lineItems');
if ($lineItemParam != null && array_key_exists($lineItem->getId(), $lineItemParam)) {
$this->lineItemEnricher->enrich($event->getCart(), $lineItem, $lineItemParam[$lineItem->getId()], $event->getSalesChannelContext());
}
}
}
}