<?php
namespace Boab\CmsBundle\EventListener;
use Boab\CmsBundle\Entity\TermInterface;
use Boab\CmsBundle\Entity\TermRoute;
use Boab\CmsBundle\Entity\Term;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Boab\CmsBundle\Event\TermPostPersistEvent;
class TermListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$entities = array_merge(
$uow->getScheduledEntityInsertions(),
$uow->getScheduledEntityUpdates()
);
foreach ($entities as $entity) {
if (!$entity instanceof TermInterface) {
continue;
}
//$changeSet = $uow->getEntityChangeSet($entity);
//dump($changeSet);
$route = $this->createRouteFromTerm($entity);
$em->persist($route);
$tmd = $em->getClassMetadata(TermRoute::class);
$uow->computeChangeSet($tmd, $route);
$entity->setRoute($route);
if(!$entity->getId()){
$md = $em->getClassMetadata(Term::class);
$uow->recomputeSingleEntityChangeSet($md, $entity);
}
}
}
public function onTermPersist(TermPostPersistEvent $event):void
{
$term = $event->getTerm();
$route = $this->createRouteFromTerm($term);
$term->setRoute($route);
}
private function createRouteFromTerm(TermInterface $term): TermRoute
{
$route = $term->getRoute();
if(!$route){
$route = new TermRoute;
$route->setDateCreated( new \DateTime('now'));
}
$route->setTitle($term->getName())
->setSlug($term->getSlug())
->setPath($term->getPath())
->setVisibility($term->isEnabled());
if($parent = $term->getParent()){
$route->setParentId($parent->getRoute()->getId());
}else{
$route->setParentId(0) ;
}
return $route;
}
}