<?php
declare(strict_types=1);
namespace MST\MSTManufacturerSlider6\Subscriber;
use MST\MSTManufacturerSlider6\Repository\SliderRepository;
use MST\MSTManufacturerSlider6\Struct\ConfigCollection;
use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
use Shopware\Core\Content\Cms\CmsPageEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
class DataSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
private SliderRepository $sliderRepository;
public function __construct(
RequestStack $requestStack,
SliderRepository $sliderRepository
) {
$this->requestStack = $requestStack;
$this->sliderRepository = $sliderRepository;
}
public static function getSubscribedEvents(): array
{
return [
CmsPageEvents::SLOT_LOADED_EVENT => 'onSlotLoad',
];
}
public function onSlotLoad(EntityLoadedEvent $event): void
{
$navigationId = $this->getNavigationId();
// iterate through all slots on page
// check for mst-manufacturer-sliders
/** @var CmsSlotEntity $entity */
foreach ($event->getEntities() as $entity) {
if ($entity->getType() == 'mst-manufacturer-slider') {
// get element config
$entityConfig = $this->getEntityConfig($entity);
$config = new ConfigCollection($entityConfig);
// if we do not have any config, stop here
if ($config->count() === 0) {
return;
}
$criteria = new Criteria();
$manufacturerIds = $this->sliderRepository->getManufacturerIds($criteria, $config, $navigationId);
// stop if no manufacturers were found - can happen if no logos are defined or no items have been sold in the shop yet
if (count($manufacturerIds) == 0) {
$entity->addExtension('slider-data', new ArrayEntity());
return;
}
$elements = $this->sliderRepository->getManufacturerMedia($manufacturerIds, $criteria, $config);
$entity->addExtension('slider-data', $elements);
}
}
}
/**
* @return array<string, mixed>
*/
private function getEntityConfig(CmsSlotEntity $entity): array
{
$config = $entity->getConfig();
if ($config !== null) {
return $config;
}
$translated = $entity->getTranslated();
if ($config === null && isset($translated['config'])) {
return $translated['config'];
}
return [];
}
private function getNavigationId(): ?string
{
/** @var Request $request */
$request = $this->requestStack->getCurrentRequest();
$navigationId = $request->attributes->get('navigationId');
if ($navigationId !== null && is_string($navigationId)) {
return strval($navigationId);
}
return null;
}
}