src/EventSubscriber/Tournament/TournamentStartedEventSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Tournament;
  3. use App\Entity\Notification;
  4. use App\Entity\Phase;
  5. use App\Event\Tournament\TournamentStartedEvent;
  6. use App\Helper\PhaseHelper;
  7. use DateTimeImmutable;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use LogicException;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class TournamentStartedEventSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(private EntityManagerInterface $entityManager)
  14.     {
  15.     }
  16.     public function onTournamentStartedEvent(TournamentStartedEvent $tournamentStartedEvent): void
  17.     {
  18.         $tournament $tournamentStartedEvent->getTournament();
  19.         $players $tournament->getPlayers()->toArray();
  20.         if (empty($players)) {
  21.             throw new LogicException('A tournament cannot be players-less.');
  22.         }
  23.         /** @var Phase $currentPhase */
  24.         $currentPhase $tournament->getPhases()->first();
  25.         // at this state, the first created phase is the current tournament phase
  26.         $tournament->setCurrentPhase($tournament->getPhases()->first());
  27.         // shuffle player on first phase
  28.         shuffle($players);
  29.         PhaseHelper::generatePhaseContests($tournament->getCurrentPhase(), $players);
  30.         foreach ($tournament->getPlayers() as $player) {
  31.             $player->addNotification(
  32.                 (new Notification())
  33.                     ->setType(Notification::TOURNAMENT_STARTED)
  34.                     ->setMessage(sprintf(
  35.                         "%s commence ! ðŸ¥³ C'est le moment de montrer vos talents de surdoué.e ðŸ˜Ž",
  36.                         $tournament->getName()
  37.                     ))
  38.                     ->setExtraData(['tournamentId' => $tournament->getId()])
  39.             );
  40.         }
  41.         // starts the phase
  42.         $currentPhase
  43.             ->setStatus(Phase::STARTED_STATUS)
  44.             ->setStartedAt(new DateTimeImmutable())
  45.         ;
  46.         $this->entityManager->flush();
  47.     }
  48.     public static function getSubscribedEvents(): array
  49.     {
  50.         return [
  51.             TournamentStartedEvent::class => 'onTournamentStartedEvent',
  52.         ];
  53.     }
  54. }