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