<?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 ServiceBoxElementResolver extends AbstractCmsElementResolver
{
protected const ELEMENT_TYPE = 'service-box';
public function getType(): string
{
return static::ELEMENT_TYPE;
}
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
$config = $slot->getFieldConfig();
// "mediaDesktop" is legacy for old elements. Now there is only "media" configured
$mediaConfig = $config->get('media') ?? $config->get('mediaDesktop');
if (empty($mediaConfig?->getValue())) {
return null;
}
$criteriaCollection = new CriteriaCollection();
$criteria = new Criteria([$mediaConfig->getValue()]);
$criteriaCollection->add('service_box_' . $mediaConfig->getValue(), MediaDefinition::class, $criteria);
return $criteriaCollection;
}
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
$config = $slot->getFieldConfig();
// "mediaDesktop" is legacy for old elements. Now there is only "media" configured
$mediaConfig = $config->get('media') ?? $config->get('mediaDesktop');
if ($mediaConfig->isStatic()) {
$mediaID = $mediaConfig->getValue();
$searchResult = $result->get('service_box_' . $mediaID);
if ($searchResult) {
$slot->assign(['media' => $searchResult->get($mediaID)]);
}
}
}
}