<?php declare(strict_types=1);
namespace FourtwosixChooseDeliveryCountryInSideCart\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Storefront\Page\Checkout\Offcanvas\OffcanvasCartPageLoadedEvent;
use Shopware\Core\System\Country\SalesChannel\AbstractCountryRoute;
use Shopware\Core\System\Country\CountryCollection;
use Shopware\Core\Checkout\Payment\PaymentMethodCollection;
use Shopware\Core\Checkout\Payment\SalesChannel\AbstractPaymentMethodRoute;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class AddDataToOffcanvas implements EventSubscriberInterface
{
private AbstractCountryRoute $countryRoute;
private AbstractPaymentMethodRoute $paymentMethodRoute;
public function __construct(
AbstractCountryRoute $countryRoute,
AbstractPaymentMethodRoute $paymentMethodRoute
)
{
$this->countryRoute = $countryRoute;
$this->paymentMethodRoute = $paymentMethodRoute;
}
public static function getSubscribedEvents(): array
{
return [
OffcanvasCartPageLoadedEvent::class => 'onOffcanvasCartLoaded'
];
}
public function onOffcanvasCartLoaded(OffcanvasCartPageLoadedEvent $event)
{
$countries = $this->getCountries($event->getSalesChannelContext());
$paymentMethods = $this->getPaymentMethods($event->getSalesChannelContext());
$event->getPage()->addExtension(
'availableCountries',
$countries
);
$event->getPage()->addExtension(
'availablePaymentMethods',
$paymentMethods
);
}
private function getCountries(SalesChannelContext $context): CountryCollection
{
$countries = $this->countryRoute->load(new Request(), new Criteria(), $context)->getCountries();
$countries->sortByPositionAndName();
return $countries;
}
private function getPaymentMethods(SalesChannelContext $context): PaymentMethodCollection
{
$request = new Request();
$request->query->set('onlyAvailable', '1');
return $this->paymentMethodRoute->load($request, $context, new Criteria())->getPaymentMethods();
}
}