custom/plugins/NrbnLittleVanGogh/src/Subscriber/ProductSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace NrbnLittleVanGogh\Subscriber;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  5. use Shopware\Core\System\CustomField\CustomFieldEntity;
  6. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  10. class ProductSubscriber implements EventSubscriberInterface
  11. {
  12.     protected EntityRepositoryInterface $customFieldRepository;
  13.     public function __construct(
  14.         EntityRepositoryInterface $customFieldRepository
  15.     ) {
  16.         $this->customFieldRepository $customFieldRepository;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.    {
  20.        return [
  21.            ProductPageLoadedEvent::class => 'onProductLoaded'
  22.        ];
  23.    }
  24.    public function onProductLoaded(ProductPageLoadedEvent $event)
  25.    {
  26.        $product $event->getPage()->getProduct();
  27.        if (!$product->getManufacturer() || !$product->getManufacturer()->getCustomFields()){
  28.            return $event;
  29.        }
  30.        $customfields $product->getManufacturer()->getCustomFields();
  31.        foreach ($customfields as $key => &$customfield) {
  32.            if (!is_array($customfield)) continue;
  33.            $criteria = new Criteria();
  34.            $criteria->addFilter(
  35.                new EqualsFilter("name"$key),
  36.            );
  37.            /** @var CustomFieldEntity $fieldConfig */
  38.            $fieldConfig $this->customFieldRepository->search($criteria,$event->getContext())->first();
  39.            if(!$fieldConfig) continue;
  40.            $fieldConfig $fieldConfig->getConfig()['options'];
  41.            $options = [];
  42.            foreach ($fieldConfig as $option){
  43.                $options[$option['value']] = $option['label']['en-GB'];
  44.            }
  45.            foreach ($customfield as &$field) {
  46.                $field = [
  47.                    'value' => $field,
  48.                    'label' => ($options[$field])??''
  49.                ];
  50.            }
  51.        }
  52.        $product->getManufacturer()->setCustomFields($customfields);
  53.        return $event;
  54.    }
  55. }