<?php
# src/EventSubscriber/EasyAdminSubscriber.php
namespace App\EventSubscriber;
use App\Entity\BlogPost;
use App\Entity\Comida;
use App\Entity\ComidaIngredientesReceta;
use App\Entity\Ingrediente;
use App\Entity\PerfilAlimentacion;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityBuiltEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
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 IngredientePerfilSubcriber implements EventSubscriberInterface
{
private $em;
private $logger;
public function __construct(EntityManagerInterface $em, LoggerInterface $logger)
{
$this->em = $em;
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return [
AfterEntityPersistedEvent::class => ['perfilAlimentacionCreate'],
AfterEntityUpdatedEvent::class => ['perfilAlimentacionUpdate'],
];
}
/**
* Fix para aƱadir un perfil de alimentaciĆ³n a un nuevo ingrediente
*/
public function perfilAlimentacionCreate(AfterEntityPersistedEvent $event){
$entity = $event->getEntityInstance();
if (!($entity instanceof Ingrediente)) {
return;
}
$this->logger->info("AfterEntityPersistedEvent perfilAlimentacionCreate Ingrediente");
$perfil = new PerfilAlimentacion();
$perfil->setTipo(3);
$perfil->setCodigo($entity->getNombre());
$entity->setPerfilAlimentacion($perfil);
$this->em->persist($entity);
$this->em->persist($perfil);
$this->em->flush();
}
/**
* Fix para eliminar las entidades relacionadas con el ingrediente que se duplican al utilizar el formulario de ingredientes
*/
public function perfilAlimentacionUpdate(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Ingrediente)) {
return;
}
$this->logger->info("AfterEntityUpdatedEvent perfilAlimentacionUpdate Ingrediente");
$perfiles = $this->em->getRepository(PerfilAlimentacion::class)->findBy(["tipo" => 3]);
$this->logger->info("Perfiles: " . count($perfiles));
foreach ($perfiles as $key => $perfil) {
if(!($perfil->getIngrediente())){
$this->logger->info("Borrando perfil huerfano");
$this->em->remove($perfil);
}
}
$perfiles = $this->em->getRepository(ComidaIngredientesReceta::class)->findBy(["ingrediente" => 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();
}
}