1 | <?php |
||
12 | class SecretSanta |
||
13 | { |
||
14 | /** @var PlayersCollection */ |
||
15 | private $players; |
||
16 | /** @var array */ |
||
17 | private $combination; |
||
18 | |||
19 | /** |
||
20 | * SecretSanta constructor. |
||
21 | */ |
||
22 | 20 | public function __construct() |
|
26 | |||
27 | /** |
||
28 | * Add single player to the game |
||
29 | * @param string $name |
||
30 | * @param string $email |
||
31 | * @return SecretSanta |
||
32 | */ |
||
33 | 8 | public function addPlayer($name, $email) |
|
39 | |||
40 | /** |
||
41 | * Add two excluded players to the game |
||
42 | * @param string $name |
||
43 | * @param string $email |
||
44 | * @param string $coupleName |
||
45 | * @param string $coupleEmail |
||
46 | * @return SecretSanta |
||
47 | */ |
||
48 | 12 | public function addCouple($name, $email, $coupleName, $coupleEmail) |
|
57 | |||
58 | /** |
||
59 | * Add multiple exclusive players to the game |
||
60 | * @param array $playersData |
||
61 | * @return $this |
||
62 | * @throws SecretSantaException |
||
63 | */ |
||
64 | 7 | public function addExclusivePlayers(...$playersData) |
|
86 | |||
87 | /** |
||
88 | * @return Player[] |
||
89 | * @throws SecretSantaException |
||
90 | */ |
||
91 | 13 | public function play() |
|
92 | { |
||
93 | try { |
||
94 | 13 | $this->combinePlayers(); |
|
95 | |||
96 | 11 | return $this->associatePlayers(); |
|
97 | 13 | } catch (SecretSantaException $exception) { |
|
98 | 2 | throw $exception; |
|
99 | 11 | } catch (\Exception $exception) { |
|
100 | 11 | throw new SecretSantaException('Error during play, impossible to find secret santa, try again', $exception); |
|
101 | } |
||
102 | } |
||
103 | |||
104 | /** |
||
105 | * @throws SecretSantaException |
||
106 | */ |
||
107 | 13 | private function combinePlayers() |
|
108 | { |
||
109 | 13 | if (count($this->players) < 3) { |
|
110 | 1 | throw new SecretSantaException("Not enough players to play, at least 3 players are required"); |
|
111 | } |
||
112 | |||
113 | 12 | $retry = count($this->players) + $this->players->countExclusivePlayers(); |
|
114 | |||
115 | 12 | while (!$this->tryMatchSecretSantaPlayers() && $retry > 0 ) { |
|
116 | 3 | $retry--; |
|
117 | 3 | } |
|
118 | |||
119 | 12 | if (!$this->isValidCombination()) { |
|
120 | 1 | throw new SecretSantaException("Not enough players to play"); |
|
121 | } |
||
122 | 11 | } |
|
123 | |||
124 | /** |
||
125 | * @return bool |
||
126 | */ |
||
127 | 12 | private function tryMatchSecretSantaPlayers() |
|
143 | |||
144 | /** |
||
145 | * @param Player $player |
||
146 | * @param Player $secretPlayer |
||
147 | * @return bool |
||
148 | */ |
||
149 | 12 | private function isValidSecretSanta(Player $player, Player $secretPlayer) |
|
159 | |||
160 | /** |
||
161 | * @return bool |
||
162 | */ |
||
163 | 12 | private function isValidCombination() |
|
167 | |||
168 | 11 | private function associatePlayers() |
|
169 | { |
||
178 | } |
||
179 |