<?php declare(strict_types=1);
namespace TigerMedia\General\TigerLanguageSwitcher\Subscriber;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SalesChannel\SalesChannelEntity;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class SalesChannelSubscriber implements EventSubscriberInterface
{
private EntityRepository $salesChannelsRepository;
public function __construct
(
EntityRepository $salesChannelsRepository,
)
{
$this->salesChannelsRepository = $salesChannelsRepository;
}
public static function getSubscribedEvents(): array
{
return [
GenericPageLoadedEvent::class => 'assignVariables',
];
}
/**
* @return array<mixed>
*/
private function getSalesChannelsPageLinks(): array
{
$output = [];
/** @var SalesChannelEntity $salesChannel */
foreach ($this->getSalesChannels() as $salesChannelId => $salesChannel) {
$url = $salesChannel->getDomains()?->first()?->getUrl();
if ($url === null || str_contains($url, 'headless')) {
continue;
}
$domain = $salesChannel->getDomains()->first();
if (is_null($domain)) {
continue;
}
$language = $salesChannel->getLanguage();
$languageId = $domain->getLanguageId();
$languageName = $language->getName();
$locale = $language->getLocale()->getCode();
$locale = strtolower(explode('-', $locale)[1]);
$output[$languageId] = [
'link' => $domain->getUrl(),
'languageName' => $languageName,
'locale' => str_replace('gb', 'en', $locale),
'countrycode' => $locale
];
}
return $output;
}
/**
* @return EntitySearchResult
*/
private function getSalesChannels(): EntitySearchResult
{
$criteria = new Criteria();
$criteria->addAssociations(['domains', 'language', 'language.locale']);
return $this->salesChannelsRepository->search($criteria, Context::createDefaultContext());
}
public function assignVariables(PageLoadedEvent $event): void
{
$event->getPage()->assign([
'salesChannels' => $this->getSalesChannelsPageLinks()
]);
}
}