<?php declare(strict_types=1);
namespace WbfkExtensions\CmsElementResolver;
use Shopware\Core\Content\Cms\Aggregate\CmsSlot\CmsSlotEntity;
use Shopware\Core\Content\Cms\DataResolver\CriteriaCollection;
use Shopware\Core\Content\Cms\DataResolver\Element\AbstractCmsElementResolver;
use Shopware\Core\Content\Cms\DataResolver\Element\ElementDataCollection;
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\ResolverContext;
use Shopware\Core\Content\Media\MediaDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class DynamicSliderCmsElementResolver extends AbstractCmsElementResolver
{
public function getType(): string
{
return 'dynamic-slider';
}
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
$sliderImageIds = [];
$config = $slot->getFieldConfig();
$sliderElements = $config->getElements()["sliderElements"]->getValue();
foreach ($sliderElements as $element) {
foreach (["mediaDesktopId", "mediaMobileId"] as $type) {
if (isset($element[$type])) {
if (is_array($element[$type])) {
array_push($sliderImageIds, $element[$type]["id"]);
} else {
array_push($sliderImageIds, $element[$type]);
}
}
}
}
if (empty($sliderImageIds)) {
return null;
}
$criteria = new Criteria($sliderImageIds);
$criteriaCollection = new CriteriaCollection();
$criteriaCollection->add('media', MediaDefinition::class, $criteria);
return $criteriaCollection;
}
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
$slides = [];
$config = $slot->getFieldConfig()->getElements()["sliderElements"]->getValue();
$sliderElementsCollection = $result->get('media')?->getEntities()?->getElements();
foreach ($config as $element) {
$slide = [];
foreach (["mediaDesktopId", "mediaMobileId"] as $mediaType) {
if (! empty($element[$mediaType])) {
$mediaId = $element[$mediaType];
if (isset($sliderElementsCollection[$mediaId])) {
$slide[$mediaType] = $sliderElementsCollection[$mediaId];
}
}
}
$slides[] = $slide;
}
$slot->assign([
'slides' => $slides
]);
}
}