<?php declare(strict_types=1);
namespace DonCarneTheme\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Shopware\Storefront\Page\Page;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerGroupSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
GenericPageLoadedEvent::class => 'onGenericPageLoaded',
];
}
public function onGenericPageLoaded(GenericPageLoadedEvent $event): void
{
$page = $event->getPage();
$context = $event->getSalesChannelContext();
$customer = $context->getCustomer();
if (!$customer instanceof CustomerEntity) {
$this->addCustomerGroupInfo($page, null, null);
return;
}
// Hole die Kundengruppe aus dem SalesChannelContext, da dort die Übersetzungen geladen sind
$customerGroup = $context->getCurrentCustomerGroup();
if ($customerGroup) {
$this->addCustomerGroupInfo(
$page,
$customerGroup->getId(),
$customerGroup->getTranslation('name') ?? $customerGroup->getName()
);
} else {
$this->addCustomerGroupInfo($page, null, null);
}
}
private function addCustomerGroupInfo(Page $page, ?string $groupId, ?string $groupName): void
{
if($groupName){
$groupName = str_replace(' ', '_', $groupName);
}
$page->addExtension('customerGroupInfo', new ArrayStruct([
'id' => $groupId,
'name' => $groupName,
'isLoggedIn' => $groupId !== null,
]));
}
}