<?php declare(strict_types=1);
namespace Crehler\MojeBambinoEngine\Subscriber;
use Crehler\MojeBambinoEngine\Service\CrehlerContextService;
use Shopware\Core\Content\Property\PropertyEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PropertyGroupSubscriber implements EventSubscriberInterface
{
private EntityRepository $propertyGroupIncrementRepository;
private CrehlerContextService $crehlerContextService;
public function __construct(EntityRepository $propertyGroupIncrementRepository, CrehlerContextService $crehlerContextService)
{
$this->propertyGroupIncrementRepository = $propertyGroupIncrementRepository;
$this->crehlerContextService = $crehlerContextService;
}
public static function getSubscribedEvents(): array
{
return [
PropertyEvents::PROPERTY_GROUP_LOADED_EVENT => 'onPropertyGroupLoaded'
];
}
public function onPropertyGroupLoaded(EntityLoadedEvent $event): void
{
try {
if ($this->crehlerContextService->get(CrehlerContextService::PRODUCT_EXPORT_GENERATE, false)) return;
$context = $event->getContext();
foreach ($event->getEntities() as $entity) {
if (null === $entity->getExtension('propertyGroupIncrement')) {
$criteria = (new Criteria())
->addFilter(new EqualsFilter('propertyGroupId', $entity->getId()));
$this->propertyGroupIncrementRepository->upsert([['propertyGroupId' => $entity->getId()]], $context);
$increment = $this->propertyGroupIncrementRepository->search($criteria, $context)->first();
$entity->addExtension('propertyGroupIncrement', $increment);
}
}
} catch (\Throwable $exception) {
dd($exception);
}
}
}