<?php declare(strict_types=1);
namespace ChespackTheme\Subscriber;
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\Product\ProductEvents;
class ProductSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $categoryRepository;
private EntityRepositoryInterface $mediaRepository;
public function __construct(
EntityRepositoryInterface $categoryRepository,
EntityRepositoryInterface $mediaRepository
) {
$this->categoryRepository = $categoryRepository;
$this->mediaRepository = $mediaRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductLoaded'
];
}
public function onProductLoaded(EntityLoadedEvent $event): void
{
// loop through all loaded product
/** @var ProductEntity $productEntity */
foreach ($event->getEntities() as $productEntity) {
$customFields = $productEntity->getCustomFields();
// loop through each product's custom fields
if($customFields) {
foreach ($customFields as $name => $value) {
if ($name !== 'related_resource_categories' || empty($value)) {
continue;
}
$context = $event->getContext();
$relatedCategories = [];
foreach ($value as $key => $categoryID) {
// search the entity via the repository here
/** @var CategoryEntity $categoryEntity */
/*value may come in as a String, Array or an Object type */
$categoryid = $categoryID;
$objectType = gettype($categoryID);
if ($objectType=="array"){
$categoryid = $categoryID['id'];
} elseif ($objectType == 'object'){
$categoryid = $categoryID->getId();
}
$category = $this->categoryRepository
->search(new Criteria([$categoryid]), $context)->first();
if ($category) {
//Now get the media associated with the category
$media = $this->mediaRepository
->search(new Criteria([$category->getMediaId()]), $context)->first();
$category->setMedia($media);
$relatedCategories[] = $category;
}
}
$customFields[$name] = $relatedCategories;
}
$productEntity->setCustomFields($customFields);
}
}
}
}