<?php
namespace App\EventSubscriber;
use App\Entity\Adresse;
use App\Entity\AdresseCommentaire;
use App\Entity\AvanceAdresse;
use App\Event\Adresse\AdresseCreatedEvent;
use App\Event\Adresse\AdresseUpdatedEvent;
use App\Repository\EtatAdresseRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AdresseSubscriber implements EventSubscriberInterface
{
/**
* @var EtatAdresseRepository
*/
private $etatAdresseRepository;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(EtatAdresseRepository $etatAdresseRepository, EntityManagerInterface $entityManager)
{
$this->etatAdresseRepository = $etatAdresseRepository;
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
AdresseCreatedEvent::class => ['onAdresseCreated', 100],
AdresseUpdatedEvent::class => ['onAdresseUpdated', 100],
];
}
public function onAdresseCreated(AdresseCreatedEvent $event)
{
// Ajout de l'état pas défaut
$adresse = $event->getAdresse();
$etatDefaut = $this->etatAdresseRepository->findOneBy(['defaut' => true]);
$avance = new AvanceAdresse();
$avance->setAdresse($adresse)
->setAvancement($etatDefaut)
->setDateRdv(new \DateTime());
$adresse->addAvanceAdress($avance);
// Ajout du commentaire
$this->addCommentaire($adresse);
}
public function onAdresseUpdated(AdresseUpdatedEvent $event)
{
$adresse = $event->getAdresse();
// Ajout du commentaire
$this->addCommentaire($adresse);
}
/**
* @param Adresse $adresse
*/
public function addCommentaire (Adresse $adresse) {
// On ajoute le commentaire si pas vide
if ($adresse->getCommentaire()) {
$commentaire = new AdresseCommentaire();
$commentaire->setCommentaire($adresse->getCommentaire())
->setAdresse($adresse);
$this->entityManager->persist($commentaire);
}
}
}