nhl-schedule/src/Application/UseCase/GenerateGamesCalendar.php

71 lines
2.5 KiB
PHP

<?php
namespace App\Application\UseCase;
use App\Application\ReadModel\Game;
use App\Application\ReadModel\Team;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use Spatie\IcalendarGenerator\Components\Calendar;
use Spatie\IcalendarGenerator\Components\Event;
class GenerateGamesCalendar
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
) {
}
public function __invoke(GenerateGamesCalendarRequest $request): string
{
$calendar = Calendar::create()
->name('Game')
->description('List game schedule');
if (empty($request->teams)) {
return $calendar->get();
}
$teams = [];
foreach ($request->teams as $team) {
$teams[$team] = $this->entityManager->getRepository(Team::class)->find($team);
}
// $criteria = Criteria::create()
// ->where(Criteria::expr()->in('homeTeamId', $request->teams))
// ->orWhere(Criteria::expr()->in('awayTeamId', $request->teams))
// ->orderBy(['startTimeScheduled' => 'ASC']);
//
// /** @var Game[] $games */
// $games = $this->entityManager->getRepository(Game::class)->matching($criteria);
/** @var Game[] $homeGames */
$homeGames = $this->entityManager->getRepository(Game::class)->findBy(['homeTeamId' => $request->teams]);
/** @var Game[] $awayGames */
$awayGames = $this->entityManager->getRepository(Game::class)->findBy(['awayTeamId' => $request->teams]);
$gamesById = [];
foreach (array_merge($homeGames, $awayGames) as $game) {
$gamesById[$game->id] = $game;
}
/** @var Game[] $games */
$games = array_values($gamesById);
$events = [];
foreach ($games as $game) {
$home = $this->entityManager->getRepository(Team::class)->find($game->homeTeamId) ?? throw new \Exception('Team not found');
$away = $this->entityManager->getRepository(Team::class)->find($game->awayTeamId) ?? throw new \Exception('Team not found');
$events[] = Event::create($away->name . ' vs ' . $home->name)
->startsAt($game->startTimeScheduled)
->endsAt($game->endTimeScheduled ?? $game->startTimeScheduled->modify('+3 hours')) // should be a parameter of the league
->address($game->venue);
}
return $calendar
->event($events)
->get()
;
}
}