<?php declare(strict_types=1);
namespace Uandi\EFB\Storefront\Subscriber;
use Shopware\Core\Checkout\Cart\Cart;
use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\Framework\Struct\Struct;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Uandi\EFB\Storefront\Trait\DecodeStockInformation;
class ConfirmPageSubscriber implements EventSubscriberInterface
{
use DecodeStockInformation;
public static function getSubscribedEvents(): array
{
return [
CheckoutConfirmPageLoadedEvent::class => 'onConfirmPageLoadedEvent'
];
}
private EntityRepository $productRepository;
public function __construct(EntityRepository $productRepository)
{
$this->productRepository = $productRepository;
}
public function onConfirmPageLoadedEvent(PageLoadedEvent $event)
{
$cart = $event->getPage()->getCart();
$context = $event->getSalesChannelContext();
$productIds = $this->getProductIds($cart);
if (empty($productIds)) {
return;
}
$cart->addExtensions([
'stockInfo' => $this->fetchStockInformation($productIds, $context),
]);
}
private function getProductIds(Cart $cart): array
{
$products = $cart->getLineItems()->filterFlatByType(LineItem::PRODUCT_LINE_ITEM_TYPE);
return array_map(function (LineItem $lineItem) {
return $lineItem->getReferencedId();
}, $products);
}
private function fetchStockInformation(array $productIds, SalesChannelContext $context): ?Struct
{
$criteria = new Criteria($productIds);
$products = $this->productRepository->search($criteria, $context->getContext());
return new ArrayStruct($products->map(function (ProductEntity $productEntity) use ($context) {
return $this->decodeStockInfo($productEntity, $context);
}));
}
}