<?php
namespace App\EventSubscriber\Import\EntityMapper\ProductTag;
use App\Application\EntityImportBundle\Event\EntityPreInitEvent;
use App\Entity\SonataClassificationCategory;
use App\Entity\Product;
use App\Entity\ProductPreInitImport;
use App\Entity\VOD\Title;
use App\EventSubscriber\Import\EntityMapper\BasePreInitSubscriber;
class EntityPreInitSubscriber extends BasePreInitSubscriber
{
public static function getSubscribedEvents(): array
{
return [
EntityPreInitEvent::class => 'onEntityPreInit',
];
}
public function onEntityPreInit(EntityPreInitEvent $event): void
{
if (ProductPreInitImport::class !== $event->getTargetClassName()) {
return;
}
$configuredProperties = $event->getConfigurationProperties();
$titleCodeProperty = $this->filterConfiguredProperty('titleCode', $configuredProperties, true);
$tagsProperty = $this->filterConfiguredProperty('tag', $configuredProperties, true);
if (!isset($titleCodeProperty, $tagsProperty)) {
$event->setSkipRowProcessing(true);
return;
}
$titleCode = $this->getValue($titleCodeProperty, $event->getData());
$tags = explode(',', $this->getValue($tagsProperty, $event->getData()));
if (!$titleCode || !$tags) {
$event->setSkipRowProcessing(true);
return;
}
$productRepo = $this->getEntityManager()->getRepository(Product::class);
$entity = $productRepo->findOneByNavCode($titleCode);
if ($entity instanceof Product) {
$tagRepo = $this->getEntityManager()->getRepository(SonataClassificationCategory::class);
$tags = $tagRepo->findBy([
'context' => 'tag',
'slug' => $tags,
]);
$isProductUpdated = false;
foreach ($tags as $tag) {
if (!$this->isTagExists($entity, $tag)) {
$entity->getTags()->add($tag);
$isProductUpdated = true;
}
}
if (!$isProductUpdated) {
$event->setSkipRowProcessing(true);
return;
}
$this->updateVodTitles($entity);
}
$event->setEntity($entity);
}
private function isTagExists(Product $entity, SonataClassificationCategory $tag): bool
{
return (bool) $entity->getTags()->filter(fn (SonataClassificationCategory $category) => $category === $tag)->toArray();
}
public function updateVodTitles(Product $entity): void
{
/** @var Title $vodTitle */
foreach ($entity->getVodTitles() as $vodTitle) {
// In the definition of the field in DB there is no configuration to use CURRENT_TIMESTAMP on every update
$vodTitle->setUpdatedAt(new \DateTime());
$this->getEntityManager()->persist($vodTitle);
}
$this->getEntityManager()->flush();
}
}