Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
17 / 17 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
FileRevisions | |
100.00% |
17 / 17 |
|
100.00% |
4 / 4 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
toArray | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
getLatest | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
calculateLatestKey | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
4 |
1 | <?php |
2 | |
3 | namespace FileImporter\Data; |
4 | |
5 | use Wikimedia\Assert\Assert; |
6 | |
7 | /** |
8 | * @license GPL-2.0-or-later |
9 | * @author Addshore |
10 | */ |
11 | class FileRevisions { |
12 | |
13 | /** @var FileRevision[] */ |
14 | private array $fileRevisions; |
15 | /** @var int|null */ |
16 | private $latestKey = null; |
17 | |
18 | /** |
19 | * @param FileRevision[] $fileRevisions |
20 | */ |
21 | public function __construct( array $fileRevisions ) { |
22 | Assert::parameter( $fileRevisions !== [], '$fileRevisions', 'cannot be empty' ); |
23 | Assert::parameterElementType( FileRevision::class, $fileRevisions, '$fileRevisions' ); |
24 | $this->fileRevisions = $fileRevisions; |
25 | } |
26 | |
27 | /** |
28 | * @return FileRevision[] |
29 | */ |
30 | public function toArray(): array { |
31 | return $this->fileRevisions; |
32 | } |
33 | |
34 | /** |
35 | * @return FileRevision |
36 | */ |
37 | public function getLatest() { |
38 | $this->latestKey ??= $this->calculateLatestKey(); |
39 | return $this->fileRevisions[$this->latestKey]; |
40 | } |
41 | |
42 | private function calculateLatestKey(): int { |
43 | $latestTimestamp = 0; |
44 | $latestKey = null; |
45 | foreach ( $this->fileRevisions as $key => $revision ) { |
46 | if ( $revision->getField( 'archivename' ) ) { |
47 | continue; |
48 | } |
49 | |
50 | $timestamp = strtotime( $revision->getField( 'timestamp' ) ); |
51 | if ( $latestTimestamp < $timestamp ) { |
52 | $latestTimestamp = $timestamp; |
53 | $latestKey = $key; |
54 | } |
55 | } |
56 | |
57 | Assert::postcondition( $latestKey !== null, 'cannot determine latest file revision' ); |
58 | return $latestKey; |
59 | } |
60 | |
61 | } |