1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Michaelc\Voting\STV; |
4
|
|
|
|
5
|
|
|
use Psr\Log\LoggerInterface as Logger; |
6
|
|
|
use Michaelc\Voting\Exception\VotingLogicException as LogicException; |
7
|
|
|
use Michaelc\Voting\Exception\VotingRuntimeException as RuntimeException; |
8
|
|
|
use Michaelc\Voting\ElectionFactory as ElectionFactoryInterface; |
9
|
|
|
use Michaelc\Voting\Election as ElectionInterface; |
10
|
|
|
|
11
|
|
|
class ElectionFactory implements ElectionFactoryInterface |
12
|
|
|
{ |
13
|
4 |
|
public static function createBallotCollection(array $rankings): array |
14
|
|
|
{ |
15
|
4 |
|
$ballotCollection = []; |
16
|
|
|
|
17
|
4 |
|
foreach ($rankings as $ranking) { |
18
|
4 |
|
$ballotCollection[] = new Ballot($ranking); |
19
|
|
|
} |
20
|
|
|
|
21
|
4 |
|
return $ballotCollection; |
22
|
|
|
} |
23
|
|
|
|
24
|
1 |
|
public static function createCandidateCollection(array $candidates): array |
25
|
|
|
{ |
26
|
1 |
|
$candidateCollection = []; |
27
|
|
|
|
28
|
1 |
|
$candidates = array_values($candidates); |
29
|
|
|
|
30
|
1 |
|
foreach ($candidates as $i => $candidate) { |
31
|
1 |
|
$candidateCollection[] = new Candidate($i); |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
return $candidateCollection; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public static function createCandidateBallotCollection(array $candidates, array $rankings): array |
38
|
|
|
{ |
39
|
|
|
$candidateMatchup = $candidateCollection = []; |
40
|
|
|
|
41
|
|
|
$candidates = array_values($candidates); |
42
|
|
|
|
43
|
|
|
foreach ($candidates as $i => $name) { |
44
|
|
|
$candidateCollection[] = new Candidate($i); |
45
|
|
|
$candidateMatchup[$name] = $i; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
foreach ($rankings as $ranking) { |
49
|
|
|
array_walk($ranking, function(&$value) { |
|
|
|
|
50
|
|
|
$value = $candidateMatchup[$value]; |
|
|
|
|
51
|
|
|
}); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$ballotCollection = $this->createBallotCollection($rankings); |
|
|
|
|
55
|
|
|
|
56
|
|
|
return ['ballots' => $ballotCollection, 'candidates' => $candidateCollection]; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public static function createElection(array $candidates, array $rankings, int $winnerCount, bool $ids = true): ElectionInterface |
60
|
|
|
{ |
61
|
|
|
if ($ids) { |
62
|
|
|
$candidateCollection = $this->createCandidateSet($candidates); |
|
|
|
|
63
|
|
|
$ballotCollection = $this->createBallotCollection($rankings); |
|
|
|
|
64
|
|
|
} else { |
65
|
|
|
$collections = $this->createCandidateBallotCollection($candidates, $rankings); |
66
|
|
|
$candidates = $collections['candidates']; |
67
|
|
|
$ballots = $collections['ballots']; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return new Election($winnerCount, $candidates, $ballots); |
|
|
|
|
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|