<?php declare(strict_types=1);
namespace Dupp\Sync4Api\Subscriber;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductLoadedSubscriber implements EventSubscriberInterface
{
/**
* @var string
*/
private $pluginName = 'Sync4ApiExport';
/**
* @var string
*/
private $customFieldName = 'sync4_api_visual_order';
public static function getSubscribedEvents(): array
{
return [
ProductPageLoadedEvent::class => 'onProductLoaded'
];
}
public function onProductLoaded(ProductPageLoadedEvent $event): void
{
$config = [];
$page = $event->getPage();
$product = $page->getProduct();
$customFields = $product->getCustomFields();
if (!$customFields) {
return;
}
// loop through each product's custom fields
foreach($customFields as $name => $value) {
if ($name !== $this->customFieldName || empty($value)) {
continue;
}
$config['visualOrder'] = json_decode($value);
}
$event->getContext()->addExtension($this->pluginName, new ArrayEntity($config));
}
}