<?php declare(strict_types=1);
namespace cutvert\CrosssellingCart\Subscriber;
use Petstore30\controllers\Store;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Content\Product\SalesChannel\CrossSelling\AbstractProductCrossSellingRoute;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\StorefrontRenderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
use Symfony\Component\HttpFoundation\Request;
class Subscriber implements EventSubscriberInterface
{
/**
* @var SystemConfigService
*/
private $systemConfigService;
private AbstractProductCrossSellingRoute $crossSellingRoute;
private CartService $cartService;
public function __construct(SystemConfigService $systemConfigService, AbstractProductCrossSellingRoute $crossSellingRoute, CartService $cartService)
{
$this->systemConfigService = $systemConfigService;
$this->crossSellingRoute = $crossSellingRoute;
$this->cartService = $cartService;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded',
StorefrontRenderEvent::class => 'onStorefrontRender'
];
}
public function onProductsLoaded(EntityLoadedEvent $event): void
{
$this->PreviewSettings = $this->systemConfigService->get('cutvertCrosssellingCart.config');
}
public function onStorefrontRender(StorefrontRenderEvent $event){
$products = [];
$cart = $this->cartService->getCart($event->getSalesChannelContext()->getToken(), $event->getSalesChannelContext());
/** @var LineItem $lineItem */
$lineItems = $cart->getLineItems()->filterFlatByType(LineItem::PRODUCT_LINE_ITEM_TYPE);
foreach($lineItems as $lineItem){
$productId = $lineItem->getReferencedId();
$crossSellingProducts = $this->crossSellingRoute->load($productId, new Request(), $event->getSalesChannelContext(), new Criteria());
/** @var SalesChannelProductEntity $object */
foreach ($crossSellingProducts->getObject() as $object){
foreach ($object->getProducts() as $product){
$products[$product->getId()] = $product;
}
}
}
$event->setParameter('cutvertCartCrossselling',$products);
}
}