<?php
namespace App\EventSubscriber\Tournament;
use App\Entity\Notification;
use App\Entity\Phase;
use App\Event\Tournament\TournamentRegistrationClosedEvent;
use DateInterval;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TournamentRegistrationClosedEventSubscriber implements EventSubscriberInterface
{
public function __construct(private EntityManagerInterface $entityManager)
{
}
public function onTournamentRegistrationClosedEvent(TournamentRegistrationClosedEvent $tournamentRegistrationClosedEvent): void
{
$tournament = $tournamentRegistrationClosedEvent->getTournament();
$currentDateTime = new DateTime();
// used to ease with the calculation of the tournament start date
$supposedStartingTime = $tournament->getStartingTime()->setDate(
(int) $currentDateTime->format('Y'),
(int) $currentDateTime->format('m'),
(int) $currentDateTime->format('d'),
);
// sets the tournament start date if the supposedStartingDate is later today
if ($supposedStartingTime > $currentDateTime) {
$tournament->setStartDate($supposedStartingTime);
} else {
// otherwise, we add one day to the supposed starting date and set it as the tournament start date
$tournament->setStartDate(
$supposedStartingTime->add(
new DateInterval(sprintf('P%sD', 1))
)
);
}
// creates the tournament phases
for ($i = 0; $i < $tournament->getPhaseCount(); ++$i) {
/** @var Phase|false $previousPhase */
$previousPhase = $tournament->getPhases()->last();
if ($previousPhase) {
$startDate = $previousPhase->getEndDate();
$endDate = $startDate->add(new DateInterval(sprintf('PT%sH', $tournament->getPhaseDuration())));
} else {
$startDate = $tournament->getStartDate();
$endDate = $tournament->getStartDate()->add(new DateInterval(sprintf('PT%sH', $tournament->getPhaseDuration())));
}
$tournament->addPhase(
(new Phase())
->setGame($tournament->getGame())
->setStartDate($startDate)
->setEndDate($endDate)
);
}
$players = $tournament->getPlayers();
foreach ($players as $player) {
$player->addNotification(
(new Notification())
->setType(Notification::TOURNAMENT_REGISTRATION_CLOSED)
->setMessage(sprintf(
'%s : Préparez-vous ! Le tournoi démarre le %s, à %s.',
$tournament->getName(),
$tournament->getStartDate()->format('jS M'),
$tournament->getStartDate()->format('H:i')
))
->setExtraData(['tournamentId' => $tournament->getId()])
);
}
$this->entityManager->flush();
}
public static function getSubscribedEvents(): array
{
return [
TournamentRegistrationClosedEvent::class => 'onTournamentRegistrationClosedEvent',
];
}
}