<?php declare(strict_types=1);
namespace MoorlFormBuilder\Subscriber;
use MoorlFormBuilder\Core\Service\FormService;
use Shopware\Core\Content\Cms\Events\CmsPageLoadedEvent;
use Shopware\Core\Content\Media\Event\MediaFileExtensionWhitelistEvent;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class StorefrontSubscriber implements EventSubscriberInterface
{
private FormService $formService;
public function __construct(
FormService $formService
)
{
$this->formService = $formService;
}
public static function getSubscribedEvents(): array
{
return [
// CIO-AI-Driven: Use CmsPageLoadedEvent, because slot config overrides (e.g. category_translation.slot_config)
// are applied in SalesChannelCmsPageLoader::overwriteSlotConfig() after the DAL slot loaded event.
// Listening on cms_slot.loaded would only see the base cms_slot_translation.config.
CmsPageLoadedEvent::class => 'onCmsPageLoaded',
MediaFileExtensionWhitelistEvent::class => 'onMediaFileExtensionWhitelist'
];
}
public function onMediaFileExtensionWhitelist(MediaFileExtensionWhitelistEvent $event)
{
$whitelist = $event->getWhitelist();
$whitelist = $this->formService->extendFileTypeWhitelist($whitelist);
$event->setWhitelist($whitelist);
}
public function onCmsPageLoaded(CmsPageLoadedEvent $event): void
{
$source = $event->getContext()->getSource();
if (!$source instanceof SalesChannelApiSource) {
return;
}
foreach ($event->getResult() as $page) {
$sections = $page->getSections();
if ($sections === null) {
continue;
}
foreach ($sections->getBlocks()->getSlots() as $slot) {
if ($slot->getType() !== 'moorl-form-builder') {
continue;
}
$config = $slot->getConfig();
if ($config === null) {
$config = $slot->getTranslation('config');
}
$formId = $config['form']['value'] ?? null;
if (!$formId) {
continue;
}
$this->formService->setContext($event->getContext());
$this->formService->setCheckCache(true);
$this->formService->initCurrentForm($formId);
if (!$this->formService->getCurrentForm()) {
continue;
}
$this->formService->setCheckCache(false);
$slot->setData($this->formService->getCurrentForm());
}
}
}
}