<?php
namespace App\EventSubscriber\Import\EntityMapper\VOD\TitleChapters;
use App\Application\EntityImportBundle\Event\EntityPreInitEvent;
use App\Entity\SonataClassificationCategory;
use App\Entity\VOD\Title;
use App\Entity\VOD\TitleChapters;
use App\Entity\VOD\TitlePreInitImport;
use App\EventSubscriber\Import\EntityMapper\BasePreInitSubscriber;
use App\Form\VOD\TitleChapterType;
/**
* Class EntityPreInitSubscriber.
*/
class EntityPreInitSubscriber extends BasePreInitSubscriber
{
public static function getSubscribedEvents(): array
{
return [
EntityPreInitEvent::class => 'onEntityPreInit',
];
}
public function onEntityPreInit(EntityPreInitEvent $event): void
{
if (TitlePreInitImport::class !== $event->getTargetClassName()) {
return;
}
$configuredProperties = $event->getConfigurationProperties();
$extendedNavCodeProp = $this->filterConfiguredProperty('extendedNavCode', $configuredProperties, true);
$chapterTypeSlugProp = $this->filterConfiguredProperty('chapterType', $configuredProperties, true);
$offsetProp = $this->filterConfiguredProperty('offset', $configuredProperties, true);
$endOffsetProp = $this->filterConfiguredProperty('endOffset', $configuredProperties, true);
if (!isset($extendedNavCodeProp, $chapterTypeSlugProp, $offsetProp)) {
$event->setSkipRowProcessing(true);
return;
}
$extendedNavCode = $this->getValue($extendedNavCodeProp, $event->getData());
$chapterTypeSlug = $this->getValue($chapterTypeSlugProp, $event->getData());
$chapterType = $this->getChapterTypeObj($chapterTypeSlug);
$offset = $this->getValue($offsetProp, $event->getData());
$endOffset = $this->getValue($endOffsetProp, $event->getData());
if (!$extendedNavCode || !$chapterType || !$offset) {
$event->setSkipRowProcessing(true);
return;
}
$titleRepo = $this->getEntityManager()->getRepository(Title::class);
$entity = $titleRepo->findOneBy(['extendedNavCode' => $extendedNavCode]);
if ($entity instanceof Title) {
//Update Vod title "modified" date
$entity->setUpdatedAt(new \DateTime());
/** @var TitleChapters $chapter */
foreach ($entity->getChapters() as $chapter) {
if ($chapter->getType() === $chapterType) {
// overwriting the existing titleChapter
$chapter->setOffset($offset);
$chapter->setEndOffset($endOffset);
$event->setEntity($entity);
return;
}
}
// create a new titleChapter
$chapter = new TitleChapters();
$chapter->setTitle($entity);
$chapter->setType($chapterType);
$chapter->setOffset($offset);
$chapter->setEndOffset($endOffset);
$entity->addChapters($chapter);
$event->setEntity($entity);
}
}
/**
* @return TitleChapterType|null
*/
private function getChapterTypeObj(string $chapterSlug): ?SonataClassificationCategory
{
$repo = $this->getEntityManager()->getRepository(SonataClassificationCategory::class);
$chapterTypes = $repo->findBy([
'context' => 'chapters',
]);
foreach ($chapterTypes as $chapterType) {
if ($chapterType->getSlug() === $chapterSlug) {
return $chapterType;
}
}
return null;
}
}