Completed
Push — master ( a743c4...8e8354 )
by Tomáš
02:35
created

WithGames::setGameAutoincrementId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
ccs 3
cts 3
cp 1
crap 1
rs 10
c 2
b 0
f 0
1
<?php
2
3
4
namespace TournamentGenerator\Traits;
5
6
7
use Exception;
8
use TournamentGenerator\Containers\GameContainer;
9
use TournamentGenerator\Game;
10
use TournamentGenerator\Interfaces\WithGames as WithGamesInterface;
11
12
/**
13
 * Trait WithGames
14
 *
15
 * @package TournamentGenerator\Traits
16
 * @author  Tomáš Vojík <[email protected]>
17
 * @since   0.4
18
 */
19
trait WithGames
20
{
21
	/** @var GameContainer List of games */
22
	protected GameContainer $games;
23
24
	/**
25
	 * Add a child container for games
26
	 *
27
	 * @param GameContainer $container
28
	 *
29
	 * @return WithGamesInterface
30
	 * @throws Exception
31
	 */
32 142
	public function addGameContainer(GameContainer $container) : WithGamesInterface {
33 142
		$this->games->addChild($container);
34 142
		return $this;
35
	}
36
37
	/**
38
	 * Get all tournament games
39
	 *
40
	 * @return Game[]
41
	 */
42 65
	public function getGames() : array {
43 65
		return $this->games->get();
44
	}
45
46
	/**
47
	 * Get the container for games
48
	 *
49
	 * @return GameContainer
50
	 */
51 149
	public function getGameContainer() : GameContainer {
52 149
		return $this->games;
53
	}
54
55
	/**
56
	 * Sets a new autoincrement value (start) for the generated games
57
	 *
58
	 * @param int $id Id - probably from the database
59
	 *
60
	 * @warning Do this on the top-level hierarchy element (Tournament class) or else, it might be reset later
61
	 *
62
	 * @post    Propagates the value to all child hierarchy objects
63
	 *
64
	 * @return WithGamesInterface
65
	 * @see     GameContainer::setAutoIncrement()
66
	 *
67
	 * @since   0.5
68
	 */
69 76
	public function setGameAutoincrementId(int $id) : WithGamesInterface {
70 76
		$this->games->setAutoIncrement($id);
71 76
		return $this;
72
	}
73
74
	/**
75
	 * Set the game's results
76
	 *
77
	 * Results is an array of [teamId => teamScore] key-value pairs. This method will look for a game with given teams and try to set the first not played.
78
	 *
79
	 * @param int[] $results array of [teamId => teamScore] key-value pairs
80
	 *
81
	 * @return Game|null
82
	 * @throws Exception
83
	 */
84 4
	public function setResults(array $results) : ?Game {
85 4
		$ids = array_keys($results);
86
		/** @var Game|null $game */
87 4
		$game = $this->games->filter(static function(Game $game) use ($ids) {
88 4
			return !$game->isPlayed() && count(array_diff($ids, $game->getTeamsIds())) === 0;
89 4
		})->getFirst();
90 4
		if (isset($game)) {
91 4
			$game->setResults($results);
92
		}
93 4
		return $game;
94
	}
95
}