<?php
namespace IcebergStorefrontChildTheme\Subscriber;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* In store front we need to know base price for each product in cart.
* This subscriber adds it.
*/
class CartSubscriber implements EventSubscriberInterface
{
private SalesChannelRepository $productRepository;
public function __construct(SalesChannelRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents()
{
return [
BeforeLineItemAddedEvent::class => 'beforeLineItemAdded'
];
}
public function beforeLineItemAdded(BeforeLineItemAddedEvent $beforeLineItemAddedEvent)
{
$context = $beforeLineItemAddedEvent->getSalesChannelContext();
$lineItem = $beforeLineItemAddedEvent->getLineItem();
if ($lineItem->getType() !== "product")
return;
/** @var SalesChannelProductEntity $product */
$product = $this->productRepository->search(new Criteria([$lineItem->getReferencedId()]), $context)->first();
if ($product === null)
return;
$prices = $product->getPrices();
$prices->sortByQuantity();
$lineItem->setPayloadValue('basePrice', $prices->first()->getPrice()->first()->getGross());
}
}