Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
23.08% |
6 / 26 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
StoryConverter | |
23.08% |
6 / 26 |
|
0.00% |
0 / 3 |
22.39 | |
0.00% |
0 / 1 |
fromV0 | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
2 | |||
toLatest | |
40.00% |
2 / 5 |
|
0.00% |
0 / 1 |
4.94 | |||
withSchemaVersion | |
80.00% |
4 / 5 |
|
0.00% |
0 / 1 |
2.03 |
1 | <?php |
2 | |
3 | namespace MediaWiki\Extension\Wikistories; |
4 | |
5 | use FormatJson; |
6 | use LogicException; |
7 | |
8 | class StoryConverter { |
9 | |
10 | /** |
11 | * @param StoryContent $story |
12 | * @return StoryContent New instance migrated to the latest version of the schema |
13 | */ |
14 | private function fromV0( StoryContent $story ): StoryContent { |
15 | return new StoryContent( FormatJson::encode( [ |
16 | 'fromArticle' => $story->getFromArticle(), |
17 | 'articleId' => $story->getArticleId(), |
18 | 'frames' => array_map( static function ( $f ) { |
19 | $parts = explode( '/', parse_url( $f->img, PHP_URL_PATH ) ); |
20 | $filename = preg_replace( '/^\d+px\-/', '', urldecode( end( $parts ) ) ); |
21 | return [ |
22 | 'image' => [ |
23 | 'filename' => $filename, |
24 | ], |
25 | 'text' => [ |
26 | 'value' => $f->text |
27 | ] |
28 | ]; |
29 | }, $story->getFrames() ) |
30 | ] ) ); |
31 | } |
32 | |
33 | /** |
34 | * @param StoryContent $story Story to convert to latest version |
35 | * @return StoryContent converted story or same instance if already at latest version |
36 | */ |
37 | public function toLatest( StoryContent $story ): StoryContent { |
38 | if ( $story->getSchemaVersion() === 0 ) { |
39 | return $this->fromV0( $story ); |
40 | } |
41 | if ( $story->isLatestVersion() ) { |
42 | return $story; |
43 | } |
44 | throw new LogicException( 'Unknown schema version: ' . $story->getSchemaVersion() ); |
45 | } |
46 | |
47 | /** |
48 | * @param StoryContent $story |
49 | * @return StoryContent New instance with the latest schema version set |
50 | * or the same instance if the version is already set |
51 | */ |
52 | public function withSchemaVersion( StoryContent $story ): StoryContent { |
53 | if ( $story->isLatestVersion() ) { |
54 | return $story; |
55 | } |
56 | $content = $story->getData()->getValue(); |
57 | $content->schemaVersion = StoryContent::SCHEMA_VERSION; |
58 | return new StoryContent( FormatJson::encode( $content ) ); |
59 | } |
60 | } |