|
1
|
|
|
<?php declare(strict_types = 1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Churn\Result; |
|
4
|
|
|
|
|
5
|
|
|
use function array_filter; |
|
6
|
|
|
use SplFixedArray; |
|
7
|
|
|
|
|
8
|
|
|
class HighestScores |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var SplFixedArray |
|
12
|
|
|
*/ |
|
13
|
|
|
private $scores; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @param int $maxSize Max number of results to keep. |
|
17
|
|
|
*/ |
|
18
|
|
|
public function __construct(int $maxSize) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->scores = new SplFixedArray($maxSize); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Returns the results as a normal PHP array. |
|
25
|
|
|
* @return Result[] |
|
26
|
|
|
*/ |
|
27
|
|
|
public function toArray(): array |
|
28
|
|
|
{ |
|
29
|
|
|
return array_filter($this->scores->toArray()); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Add the result if its priority is high enough. |
|
34
|
|
|
* @param Result $result The result for a file. |
|
35
|
|
|
* @return void |
|
36
|
|
|
*/ |
|
37
|
|
|
public function add(Result $result): void |
|
38
|
|
|
{ |
|
39
|
|
|
if ($this->scores[$this->scores->getSize() - 1] !== null |
|
40
|
|
|
&& $result->getPriority() <= $this->scores[$this->scores->getSize() - 1]->getPriority()) { |
|
41
|
|
|
return; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$this->insertAt($result, $this->findPosition($result)); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Returns the position where the result must be inserted. |
|
49
|
|
|
* @param Result $result The result for a file. |
|
50
|
|
|
* @return integer |
|
51
|
|
|
*/ |
|
52
|
|
|
private function findPosition(Result $result): int |
|
53
|
|
|
{ |
|
54
|
|
|
$pos = 0; |
|
55
|
|
|
|
|
56
|
|
|
$this->scores->rewind(); |
|
57
|
|
|
foreach ($this->scores as $score) { |
|
58
|
|
|
if ($score === null || $result->getPriority() > $score->getPriority()) { |
|
59
|
|
|
break; |
|
60
|
|
|
} |
|
61
|
|
|
$pos++; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return $pos; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* Inserts the result at a given position and shifts the lower elements. |
|
69
|
|
|
* @param Result $result The result for a file. |
|
70
|
|
|
* @param int $position The position where the result must be inserted. |
|
71
|
|
|
* @return void |
|
72
|
|
|
*/ |
|
73
|
|
|
private function insertAt(Result $result, int $position): void |
|
74
|
|
|
{ |
|
75
|
|
|
for ($i = $this->scores->getSize() - 1; $i > $position; $i--) { |
|
76
|
|
|
$this->scores[$i] = $this->scores[$i - 1]; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
$this->scores[$position] = $result; |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|