<?php declare(strict_types=1);
namespace WbfkExtensions\CmsElementResolver;
use Shopware\Core\Content\Category\CategoryDefinition;
use Shopware\Core\Content\Category\Service\AbstractCategoryUrlGenerator;
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\Content\Media\MediaEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class CategoriesCmsElementResolver extends AbstractCmsElementResolver
{
/**
* @var AbstractCategoryUrlGenerator
*/
private $categoryUrlGenerator;
public function __construct(
AbstractCategoryUrlGenerator $categoryUrlGenerator
) {
$this->categoryUrlGenerator = $categoryUrlGenerator;
}
public function getType(): string
{
return 'icon-banner';
}
public function collect(CmsSlotEntity $slot, ResolverContext $resolverContext): ?CriteriaCollection
{
$categoryId = $slot->getConfig()['linkUrl']['value'];
$criteria = new Criteria([$categoryId]);
$criteria->addAssociations([
'children.children.translated.externalLink',
'children.children',
'children.translated.externalLink',
'children.active'
]);
$config = $slot->getFieldConfig();
$icon = $config->get('icon');
$criteriaCollection = new CriteriaCollection();
$criteriaCollection->add('category', CategoryDefinition::class, $criteria);
if ($icon && $icon->getValue() !== null) {
$criteria = new Criteria([$icon->getValue()]);
$criteriaCollection->add('desktop_' . $icon->getValue(), MediaDefinition::class, $criteria);
}
return $criteriaCollection;
}
public function enrich(CmsSlotEntity $slot, ResolverContext $resolverContext, ElementDataCollection $result): void
{
if (!(count($result->get('category')->getCriteria()->getIds()) > 0)) {
return;
}
$categoryId = $result->get('category')->getCriteria()->getIds()[0];
$saleschannel = $resolverContext->getSalesChannelContext()->getSalesChannel();
$category = $result->get('category')->getEntities()->getElements()[$categoryId];
$data["linkUrl"] = [
"name" => $category->getName(),
"url" => $this->categoryUrlGenerator->generate($category, $saleschannel)
];
$config = $slot->getFieldConfig();
$desktop = $this->getMedia('desktop', $config->get('icon'), $result);
$slot->assign(
[
'images' => [
'bannerIcon' => $desktop
]
]
);
$slot->setConfig($data);
}
private function getMedia($size, $mediaConfig, $result)
{
if (is_null($mediaConfig)) {
return;
}
if ($mediaConfig->isStatic()) {
$mediaID = $mediaConfig->getValue();
$searchResult = $result->get($size . '_' . $mediaID);
if ($searchResult) {
/** @var MediaEntity|null $media */
return $searchResult->get($mediaID);
}
}
return false;
}
}