<?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 PartnerGridCmsElementResolver extends AbstractCmsElementResolver
{
public function getType(): string
{
return 'partner-grid';
}
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
$partnerImageIds = [];
$partnerElements = $slot->getFieldConfig()->get('partners')?->getValue();
if (!isset($partnerElements)) {
return null;
}
foreach ($partnerElements as $element) {
if (isset($element['imageId'])) {
if (is_array($element['imageId'])) {
$partnerImageIds[] = $element['imageId']["id"];
} else {
$partnerImageIds[] = $element['imageId'];
}
}
}
if (empty($partnerImageIds)) {
return null;
}
$criteria = new Criteria($partnerImageIds);
$criteriaCollection = new CriteriaCollection();
$criteriaCollection->add('media', MediaDefinition::class, $criteria);
return $criteriaCollection;
}
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
$partners = [];
$partnerElements = $slot->getFieldConfig()->get('partners')?->getValue();
if (!isset($partnerElements)) {
return;
}
$partnerElementsCollection = $result->get('media')->getEntities()->getElements();
foreach ($partnerElements as $element) {
if (isset($element['imageId']) && isset($partnerElementsCollection[$element['imageId']])) {
$partners[] = [
'media' => $partnerElementsCollection[$element['imageId']],
'element' => $element
];
}
}
$slot->assign([
'partners' => $partners
]);
}
}