Untitled

mail@pastecode.io avatar
unknown
php
7 months ago
1.9 kB
2
Indexable
Never
<?php

namespace ScoreBoard;

class Board
{
    private array $games = [];

    public function startGame(Team $homeTeam, Team $awayTeam): Game
    {
        $game = new Game($homeTeam, $awayTeam);

        $key = $this->findGameKey($game);

        assert(is_null($key));

        $this->games[] = $game;

        return $game;
    }

    public function updateScore(Game $game, int $homeScore, int $awayScore): void
    {
        $key = $this->findGameKey($game);

        assert(!is_null($key));

        $game->updateScore($homeScore, $awayScore);
    }

    public function finishGame(Game $game): void
    {
        $key = $this->findGameKey($game);

        assert(!is_null($key));

        //napisać w readme czy tak czy tak
//        if(is_null($key)){
//            return;
//        }

        unset($this->games[$key]);
    }

    private function findGameKey(Game $game): ?int
    {
        foreach ($this->games as $key => $g) {
            if ($g->getHomeTeam() === $game->getHomeTeam() && $g->getAwayTeam() === $game->getAwayTeam()) {
                return $key;
            }
        }

        return null;
    }

    public function summary(): string
    {
        $games = $this->games;

        usort(
            $games,
            fn(Game $a, Game $b) => ($a->getHomeScore() + $a->getAwayScore()) <=> ($b->getHomeScore(
                    ) + $b->getAwayScore())
        );

        krsort($games);

        $summary = '';

        /** @var Game $game */
        foreach ($games as $game) {
            $summary .= sprintf(
                "%s %d - %s %d\n",
                $game->getHomeTeam()->getName(),
                $game->getHomeScore(),
                $game->getAwayTeam()->getName(),
                $game->getAwayScore(),
            );
        }

        return $summary;
    }
}