<?php
namespace App\EventSubscriber\Tournament;
use App\Entity\Contest;
use App\Entity\Phase;
use App\Entity\Transaction;
use App\Event\Tournament\TournamentCancelledEvent;
use App\Factory\TransactionFactory;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TournamentCancelledEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $entityManager, private TransactionFactory $transactionFactory
) {
}
public function onTournamentCancelledEvent(TournamentCancelledEvent $tournamentCancelledEvent): void
{
$tournament = $tournamentCancelledEvent->getTournament();
if ($tournament->getPlayers()->isEmpty()) {
return;
}
// refunds the tickets
foreach ($tournament->getPlayers() as $player) {
$this->transactionFactory
->forPlayer($player)
->giveTickets($tournament->getCost())
->because(Transaction::REFUND_REGISTER_IN_TOURNAMENT_TYPE)
->save()
;
}
if ($tournament->getPhases()->isEmpty()) {
return;
}
foreach ($tournament->getPhases() as $phase) {
if ($phase->getStatus() === Phase::ENDED_STATUS) {
continue;
}
if ($phase->getContests()->isEmpty()) {
continue;
}
foreach ($phase->getContests() as $contest) {
// no need to dispatch the event here
$contest->setStatus(Contest::CANCELLED_STATUS);
}
$phase->setStatus(Phase::CANCELLED_STATUS);
}
$this->entityManager->flush();
}
public static function getSubscribedEvents(): array
{
return [
TournamentCancelledEvent::class => 'onTournamentCancelledEvent',
];
}
}