<?php
declare(strict_types=1);
namespace NrbnLittleVanGogh\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\System\CustomField\CustomFieldEntity;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class ProductSubscriber implements EventSubscriberInterface
{
protected EntityRepositoryInterface $customFieldRepository;
public function __construct(
EntityRepositoryInterface $customFieldRepository
) {
$this->customFieldRepository = $customFieldRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductLoaded'
];
}
public function onProductLoaded(ProductPageLoadedEvent $event)
{
$product = $event->getPage()->getProduct();
if (!$product->getManufacturer() || !$product->getManufacturer()->getCustomFields()){
return $event;
}
$customfields = $product->getManufacturer()->getCustomFields();
foreach ($customfields as $key => &$customfield) {
if (!is_array($customfield)) continue;
$criteria = new Criteria();
$criteria->addFilter(
new EqualsFilter("name", $key),
);
/** @var CustomFieldEntity $fieldConfig */
$fieldConfig = $this->customFieldRepository->search($criteria,$event->getContext())->first();
if(!$fieldConfig) continue;
$fieldConfig = $fieldConfig->getConfig()['options'];
$options = [];
foreach ($fieldConfig as $option){
$options[$option['value']] = $option['label']['en-GB'];
}
foreach ($customfield as &$field) {
$field = [
'value' => $field,
'label' => ($options[$field])??''
];
}
}
$product->getManufacturer()->setCustomFields($customfields);
return $event;
}
}