<?php
declare(strict_types=1);
namespace Prems\Plugin\PremsIndividualOffer6\Subscriber;
use Prems\Plugin\PremsIndividualOffer6\Core\Entity\Offer\OfferEntity;
use Prems\Plugin\PremsIndividualOffer6\Core\Offer\Storefront\OfferService;
use Prems\Plugin\PremsIndividualOffer6\PremsIndividualOffer6;
use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CheckoutPageLoader implements EventSubscriberInterface
{
private OfferService $offerService;
public function __construct(OfferService $offerService)
{
$this->offerService = $offerService;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutConfirmPageLoadedEvent::class => 'onCheckoutLoaded',
CheckoutCartPageLoadedEvent::class => 'onCheckoutLoaded',
OffcanvasCartPageLoadedEvent::class => 'onCheckoutLoaded'
];
}
public function onCheckoutLoaded(PageLoadedEvent $event): void
{
$page = $event->getPage();
$offerExtension = $event->getPage()->getCart()->getExtension(PremsIndividualOffer6::OFFER_MODE_EXTENSION_NAME);
$customer = $event->getSalesChannelContext()->getCustomer();
if (!$offerExtension || !$offerExtension->getId() || !$customer) {
return;
}
/** @var OfferEntity $offer */
$offer = $this->offerService->getOfferById($offerExtension->getId(), $event->getSalesChannelContext()->getContext(), $customer);
$shippingMethodId = $offer->getShippingMethodId();
if (!$shippingMethodId) {
return;
}
foreach ($page->getShippingMethods() as $key => $shippingMethod) {
if ($shippingMethod->getId() !== $shippingMethodId) {
$page->getShippingMethods()->remove($key);
}
}
}
}