<?php declare(strict_types=1);
namespace Crehler\MojeBambinoEngine\Subscriber;
use Crehler\MojeBambinoEngine\Entity\Property\PropertyGroupOptionIncrementEntity;
use Crehler\MojeBambinoEngine\Struct\AutoIncrementStruct;
use Shopware\Core\Content\Property\PropertyEvents;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\Context;
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 Shopware\Core\Framework\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PropertyGroupOptionSubscriber implements EventSubscriberInterface
{
private EntityRepository $productGroupOptionIncrementRepository;
public function __construct(EntityRepository $productGroupOptionIncrementRepository)
{
$this->productGroupOptionIncrementRepository = $productGroupOptionIncrementRepository;
}
public static function getSubscribedEvents(): array
{
return [
PropertyEvents::PROPERTY_GROUP_OPTION_LOADED_EVENT => 'onProductGroupOptionEventLoaded'
];
}
public function onProductGroupOptionEventLoaded(EntityLoadedEvent $event): void
{
if ($event->getContext()->getSource() instanceof SalesChannelApiSource) {
return;
}
try {
foreach ($event->getEntities() as $entity) {
$criteria = new Criteria();
$criteria->addFilter(
new EqualsFilter('propertyGroupOptionId', $entity->getId())
);
/** @var PropertyGroupOptionIncrementEntity $increment */
$increment = $this->productGroupOptionIncrementRepository->search($criteria, Context::createDefaultContext())->first();
if (!$increment) {
$this->productGroupOptionIncrementRepository->upsert([['propertyGroupOptionId' => $entity->getId()]], Context::createDefaultContext());
$increment = $this->productGroupOptionIncrementRepository->search($criteria, Context::createDefaultContext())->first();
}
$struct = new AutoIncrementStruct($increment->getAutoIncrement());
$entity->addExtension('autoIncrement', $struct);
}
} catch (\Throwable $exception) {
dd($exception);
}
}
}