<?php declare(strict_types=1);
namespace Compra\OrganizationLogoSW6\Storefront\Subscriber;
use Compra\FoundationSW6\Core\System\PluginConfigService;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FrontendSubscriber implements EventSubscriberInterface
{
/** @var PluginConfigService */
protected $pluginConfigService;
public function __construct(
PluginConfigService $pluginConfigService
)
{
$this->pluginConfigService = $pluginConfigService;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
HeaderPageletLoadedEvent::class => 'onHeaderPageletLoaded'
];
}
/**
* Subscribes the HeaderPageletLoadedEvent to add customer group logos to header.
*
* @param HeaderPageletLoadedEvent $event
*/
public function onHeaderPageletLoaded(HeaderPageletLoadedEvent $event)
{
// get customer
$customer = $event->getSalesChannelContext()->getCustomer();
// get all customer group logos
$customerGroupLogos = $this->getCustomerGroupLogos();
if (!$customer || !$customerGroupLogos || !array_key_exists($customer->getGroupId(), $customerGroupLogos)) {
return;
}
// only add extension to page, if current customer's group has an organization logo
$event->getPagelet()->addExtension('compra_organization_logo', new ArrayEntity([
'mediaId' => $customerGroupLogos[$customer->getGroupId()]
]));
}
/**
* Helper function to get all customer group logos.
* - key = customerGroupId
* - value = logo mediaId
*
* @return array
*/
protected function getCustomerGroupLogos()
{
$customerGroupLogos = [];
for ($i = 1; $i <= 2; $i++) {
$customerGroup = $this->pluginConfigService->getPluginConfig("customerGroup$i");
$logo = $this->pluginConfigService->getPluginConfig("logo$i");
if ($customerGroup && $logo) {
$customerGroupLogos[$customerGroup] = $logo;
}
}
return $customerGroupLogos;
}
}