src/EventSubscriber/Project/ProjectAttachedSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Project;
  3. use App\Event\Project\ProjectAttachedEvent;
  4. use App\Service\Project\ProjectService;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. /**
  8.  * EventSubscriber qui gère la création des sous-projets attachés
  9.  * quand un projet avec un parent est créé via sendOne()
  10.  */
  11. class ProjectAttachedSubscriber implements EventSubscriberInterface
  12. {
  13.     private ProjectService $projectService;
  14.     private EntityManagerInterface $em;
  15.     public function __construct(ProjectService $projectServiceEntityManagerInterface $em)
  16.     {
  17.         $this->projectService $projectService;
  18.         $this->em $em;
  19.     }
  20.     public static function getSubscribedEvents(): array
  21.     {
  22.         return [
  23.             ProjectAttachedEvent::class => 'onProjectAttached',
  24.         ];
  25.     }
  26.     public function onProjectAttached(ProjectAttachedEvent $event): void
  27.     {
  28.         $entity $event->getProject();
  29.         $parent $entity->getParent();
  30.         if (!$parent) {
  31.             return;
  32.         }
  33.         $attachedParents $parent->getAttacheds();
  34.         if (count($attachedParents) === 0) {
  35.             return;
  36.         }
  37.         $created 0;
  38.         foreach ($attachedParents as $attachedParent) {
  39.             $this->projectService->insertAttachedProject($attachedParent$entity);
  40.             $created++;
  41.         }
  42.         if ($created 0) {
  43.             // Un seul flush pour toutes les entités créées (meilleures performances)
  44.             $this->em->flush();
  45.         }
  46.     }
  47. }