<?php declare(strict_types=1);
namespace GrimmTheme\Storefront\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\System\Country\CountryCollection;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\Country\SalesChannel\AbstractCountryRoute;
use Symfony\Component\HttpFoundation\Request;
use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
class AddCountriesToPage implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $countryRepository;
/**
* @var CountryCollection
*/
protected $countries;
/**
* @var AbstractCountryRoute
*/
private $countryRoute;
public function __construct(AbstractCountryRoute $countryRoute)
{
$this->countryRoute = $countryRoute;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'addCountries',
CheckoutCartPageLoadedEvent::class => 'addCountries'
];
}
public function addCountries($event): void
{
$countries = $this->getCountries($event->getSalesChannelContext());
$event->getPage()->addExtension('grimm_countries', $countries);
}
private function getCountries(SalesChannelContext $salesChannelContext): CountryCollection
{
$criteria = (new Criteria())
->addFilter(new EqualsFilter('active', true))
->addAssociation('country.states');
$countries = $this->countryRoute->load(new Request(), $criteria, $salesChannelContext)->getCountries();
$countries->sortCountryAndStates();
return $countries;
}
}