<?php declare(strict_types=1);
namespace Compra\StagingSW6\Storefront\Subscriber;
use Compra\FoundationSW6\Core\System\PluginConfigService;
use Compra\StagingSW6\Core\System\Service\StagingService;
use Compra\StagingSW6\Core\System\StagingConfiguration\StagingConfigurationEntity;
use Exception;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FrontendSubscriber implements EventSubscriberInterface
{
protected ContainerInterface $container;
protected StagingService $stagingService;
protected PluginConfigService $pluginConfigService;
public function __construct(
ContainerInterface $container,
StagingService $stagingService,
PluginConfigService $pluginConfigService
)
{
$this->container = $container;
$this->stagingService = $stagingService;
$this->pluginConfigService = $pluginConfigService;
}
public static function getSubscribedEvents(): array
{
return [
HeaderPageletLoadedEvent::class => 'onHeaderPageletLoaded'
];
}
/**
* @param HeaderPageletLoadedEvent $event
*/
public function onHeaderPageletLoaded(HeaderPageletLoadedEvent $event): void
{
$shopDomains = $event->getSalesChannelContext()->getSalesChannel()->getDomains();
if (!$shopDomains) {
return;
}
$domain = $shopDomains->first();
if (!$domain) {
return;
}
try {
$showHint = $this->checkShowHint($domain->getUrl());
$currentValue = $this->pluginConfigService->getPluginConfig('showHint');
if ($currentValue !== $showHint['showHint']) {
$this->pluginConfigService->setPluginConfig('showHint', $showHint['showHint']);
}
$currentValue = $this->pluginConfigService->getPluginConfig('showHintName');
if ($currentValue !== $showHint['name']) {
$this->pluginConfigService->setPluginConfig('showHintName', $showHint['name']);
}
} catch (Exception $e) {}
}
/**
* @param string $domain
* @return array
* @throws Exception
*/
public function checkShowHint(string $domain): array
{
/** @var StagingConfigurationEntity[] $stagingConfigurations */
$stagingConfigurations = $this->stagingService->getStagingConfigurationData();
foreach ($stagingConfigurations as $configuration) {
$domainNeedle = $configuration->getDirectory() . '/public';
if ($this->stagingService->endsWith($domain,$domainNeedle)
&& $configuration->getShowHintInFrontend()) {
return [
'showHint' => true,
'name' => $configuration->getDirectory()
];
}
}
return [
'showHint' => false,
'name' => ''
];
}
}