<?php
namespace B2bSellersCore\Components\Checkout\Subscriber;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class LineItemCommentSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents(): array
{
return [
BeforeLineItemAddedEvent::class => 'addLineItemComment'
];
}
public function addLineItemComment(BeforeLineItemAddedEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
if (empty($request)) {
return;
}
$lineItems = $request->get('items', null);
if(empty($items)) {
$lineItems = $request->get('lineItems', null);
}
if(empty($lineItems)) {
return;
}
$id = $event->getLineItem()->getReferencedId();
if(empty($lineItems[$id])) {
return;
}
$lineItem = $lineItems[$id];
$comment = $lineItem['comment'] ?? null;
if(empty($comment)) {
return;
}
$lineItem = $event->getLineItem();
if($event->isMerged()) {
$lineItem = $event->getCart()->getLineItems()->get($lineItem->getId());
}
$payload = $lineItem->getPayload();
$payload['comment'] = $comment;
$lineItem->setPayload($payload);
}
}