src/EventSubscriber/AdresseSubscriber.php line 59

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Adresse;
  4. use App\Entity\AdresseCommentaire;
  5. use App\Entity\AvanceAdresse;
  6. use App\Event\Adresse\AdresseCreatedEvent;
  7. use App\Event\Adresse\AdresseUpdatedEvent;
  8. use App\Repository\EtatAdresseRepository;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class AdresseSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var EtatAdresseRepository
  15.      */
  16.     private $etatAdresseRepository;
  17.     /**
  18.      * @var EntityManagerInterface
  19.      */
  20.     private $entityManager;
  21.     public function __construct(EtatAdresseRepository $etatAdresseRepositoryEntityManagerInterface $entityManager)
  22.     {
  23.         $this->etatAdresseRepository $etatAdresseRepository;
  24.         $this->entityManager $entityManager;
  25.     }
  26.     public static function getSubscribedEvents(): array
  27.     {
  28.         return [
  29.             AdresseCreatedEvent::class => ['onAdresseCreated'100],
  30.             AdresseUpdatedEvent::class => ['onAdresseUpdated'100],
  31.         ];
  32.     }
  33.     public function onAdresseCreated(AdresseCreatedEvent $event)
  34.     {
  35.         // Ajout de l'état pas défaut
  36.         $adresse $event->getAdresse();
  37.         $etatDefaut $this->etatAdresseRepository->findOneBy(['defaut' => true]);
  38.         $avance = new AvanceAdresse();
  39.         $avance->setAdresse($adresse)
  40.             ->setAvancement($etatDefaut)
  41.             ->setDateRdv(new \DateTime());
  42.         $adresse->addAvanceAdress($avance);
  43.         // Ajout du commentaire
  44.         $this->addCommentaire($adresse);
  45.     }
  46.     public function onAdresseUpdated(AdresseUpdatedEvent $event)
  47.     {
  48.         $adresse $event->getAdresse();
  49.         // Ajout du commentaire
  50.         $this->addCommentaire($adresse);
  51.     }
  52.     /**
  53.      * @param Adresse $adresse
  54.      */
  55.     public function addCommentaire (Adresse $adresse) {
  56.         // On ajoute le commentaire si pas vide
  57.         if ($adresse->getCommentaire()) {
  58.             $commentaire = new AdresseCommentaire();
  59.             $commentaire->setCommentaire($adresse->getCommentaire())
  60.                 ->setAdresse($adresse);
  61.             $this->entityManager->persist($commentaire);
  62.         }
  63.     }
  64. }