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