<?php
# src/EventSubscriber/EasyAdminSubscriber.php
namespace App\EventSubscriber;
use App\Entity\BlogPost;
use App\Entity\Comida;
use App\Entity\ComidaIngredientesReceta;
use App\Entity\PerfilAlimentacion;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ComidaPerfilSubcriber implements EventSubscriberInterface
{
private $em;
private $logger;
public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
{
$this->em = $em;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
AfterEntityUpdatedEvent::class => ['perfilAlimentacionUpdate'],
];
}
/**
* Fix para eliminar las entidades relacionadas con la comida que se duplican al utilizar el formulario de comida
*/
public function perfilAlimentacionUpdate(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Comida)) {
return;
}
$this->logger->info("BeforeEntityUpdatedEvent perfilAlimentacionUpdate");
$perfiles = $this->em->getRepository(PerfilAlimentacion::class)->findBy(["tipo" => 2]);
$this->logger->info("Perfiles: " . count($perfiles));
foreach ($perfiles as $key => $perfil) {
if(!($perfil->getComida())){
$this->logger->info("Borrando perfil huerfano");
$this->em->remove($perfil);
}
}
$perfiles = $this->em->getRepository(ComidaIngredientesReceta::class)->findBy(["comida" => null]);
$this->logger->info("ComidaIngredientes: " . count($perfiles));
foreach ($perfiles as $key => $perfil) {
if(!($perfil->getComida())){
$this->logger->info("Borrando ComidaIngredientes huerfano");
$this->em->remove($perfil);
}
}
$this->em->flush();
}
}