<?php declare(strict_types=1);
namespace LoyxxSeminar\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\Salutation\SalesChannel\AbstractSalutationRoute;
use Shopware\Core\System\Salutation\SalutationCollection;
use Shopware\Core\System\Salutation\SalutationEntity;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\RouteRequest\SalutationRouteRequestEvent;
use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class CheckoutPageLoadedEventSubscriber implements EventSubscriberInterface
{
private SalesChannelRepositoryInterface $salutationRepository;
private SystemConfigService $systemConfigService;
private AbstractSalutationRoute $salutationRoute;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
SalesChannelRepositoryInterface $salutationRepository,
AbstractSalutationRoute $salutationRoute,
SystemConfigService $systemConfigService,
EventDispatcherInterface $eventDispatcher
)
{
$this->salutationRepository = $salutationRepository;
$this->systemConfigService = $systemConfigService;
$this->salutationRoute = $salutationRoute;
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutCartPageLoadedEvent::class => 'onCheckoutCartPageLoadedEvent',
CheckoutConfirmPageLoadedEvent::class => 'onCheckoutCartPageLoadedEvent'
];
}
public function onCheckoutCartPageLoadedEvent(PageLoadedEvent $event)
{
if ($this->systemConfigService->getBool('LoyxxSeminar.config.isSalutationEnabled')) {
$event->getPage()->addExtensions([
'salutations' => $this->getSalutations($event->getSalesChannelContext(), $event->getRequest())
]);
}
}
private function getSalutations(SalesChannelContext $context, Request $request): SalutationCollection
{
$event = new SalutationRouteRequestEvent($request, new Request(), $context, new Criteria());
$this->eventDispatcher->dispatch($event);
$salutations = $this->salutationRoute
->load($event->getStoreApiRequest(), $context, $event->getCriteria())
->getSalutations();
$salutations->sort(static function (SalutationEntity $a, SalutationEntity $b) {
return $b->getSalutationKey() <=> $a->getSalutationKey();
});
return $salutations;
}
}