<?php declare(strict_types=1);
namespace Atl\ProductConfigurator\Subscriber;
use Atl\ProductConfigurator\Extension\Content\Product\ProductExtensionEntity;
use Atl\ProductConfigurator\Migration\Migration1628124328ProductExtension;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductLoadedSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $productExtensionRepository;
public function __construct(EntityRepositoryInterface $productExtensionRepository)
{
$this->productExtensionRepository = $productExtensionRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded'
];
}
/**
* @param EntityLoadedEvent $event
*/
public function onProductsLoaded(EntityLoadedEvent $event): void
{
$products = $event->getEntities();
if (count($products) > 1) {
return;
}
$product = $products[0];
$productId = $product->getId();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productId', $productId));
$criteria->setLimit(1);
$criteria->addAssociation('atlProductConfigurator.media');
$criteria->getAssociation("atlProductConfigurator.atlProductConfiguratorFields")->addSorting(new FieldSorting("position", FieldSorting::ASCENDING));
$criteria->addAssociation("atlProductConfigurator.atlProductConfiguratorFields.media");
/** @var ProductExtensionEntity $productExtension */
$productExtension = $this->productExtensionRepository->search($criteria, $event->getContext())->first();
if (empty($productExtension)) {
return;
}
$ext = $product->getExtensions();
$ext[Migration1628124328ProductExtension::PRODUCT_EXTENSION] = $productExtension->getAtlProductConfigurator();
$product->setExtensions($ext);
}
}