entityManager = $entityManager; $this->demandeRepository = $demandeRepository; $this->statsRepository = $statsRepository; } protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Creating Stats objects for cities with Demandes but no Stats'); // Find all Demandes with INSEE codes $demandesWithInsee = $this->demandeRepository->createQueryBuilder('d') ->where('d.insee IS NOT NULL') ->getQuery() ->getResult(); if (empty($demandesWithInsee)) { $io->warning('No Demandes with INSEE codes found.'); return Command::SUCCESS; } $io->info(sprintf('Found %d Demandes with INSEE codes.', count($demandesWithInsee))); // Group Demandes by INSEE code $demandesByInsee = []; /** @var Demande $demande */ foreach ($demandesWithInsee as $demande) { $insee = $demande->getInsee(); if (!isset($demandesByInsee[$insee])) { $demandesByInsee[$insee] = []; } $demandesByInsee[$insee][] = $demande; } $io->info(sprintf('Found %d unique INSEE codes.', count($demandesByInsee))); // Check which INSEE codes don't have Stats objects $newStatsCount = 0; foreach ($demandesByInsee as $insee => $demandes) { $stats = $this->statsRepository->findOneBy(['zone' => $insee]); if ($stats === null) { // Create a new Stats object for this INSEE code $stats = new Stats(); $stats->setZone((string) $insee); // Try to set the city name from the first Demande $firstDemande = $demandes[0]; if ($firstDemande->getQuery()) { // Use the query as a fallback name (will be updated during labourage) $stats->setName($firstDemande->getQuery()); } $stats->setDateCreated(new \DateTime()); $stats->setDateLabourageRequested(new \DateTime()); $this->entityManager->persist($stats); $newStatsCount++; $io->text(sprintf('Created Stats for INSEE code %s', $insee)); } } if ($newStatsCount > 0) { $this->entityManager->flush(); $io->success(sprintf('Created %d new Stats objects.', $newStatsCount)); } else { $io->info('No new Stats objects needed to be created.'); } return Command::SUCCESS; } }