Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 34 |
|
0.00% |
0 / 6 |
CRAP | |
0.00% |
0 / 1 |
| JsonDumpFormatter | |
0.00% |
0 / 34 |
|
0.00% |
0 / 6 |
90 | |
0.00% |
0 / 1 |
| format | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
6 | |||
| close | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
6 | |||
| getHeader | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getFooter | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| formatEntry | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
6 | |||
| indent | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace ContentTranslation; |
| 4 | |
| 5 | use MediaWiki\Json\FormatJson; |
| 6 | |
| 7 | class JsonDumpFormatter { |
| 8 | /** @var bool */ |
| 9 | private $isStarted = false; |
| 10 | |
| 11 | public function format( array $entry ): string { |
| 12 | $output = ''; |
| 13 | |
| 14 | if ( !$this->isStarted ) { |
| 15 | $this->isStarted = true; |
| 16 | $output .= $this->getHeader(); |
| 17 | $output .= $this->formatEntry( $entry ); |
| 18 | } else { |
| 19 | $output .= ",\n"; |
| 20 | $output .= $this->formatEntry( $entry ); |
| 21 | } |
| 22 | |
| 23 | return $output; |
| 24 | } |
| 25 | |
| 26 | public function close(): string { |
| 27 | if ( !$this->isStarted ) { |
| 28 | return '[]'; |
| 29 | } |
| 30 | |
| 31 | $output = "\n"; |
| 32 | $output .= $this->getFooter(); |
| 33 | |
| 34 | return $output; |
| 35 | } |
| 36 | |
| 37 | private function getHeader(): string { |
| 38 | return "[\n"; |
| 39 | } |
| 40 | |
| 41 | private function getFooter(): string { |
| 42 | return "]\n"; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * @param array $entry |
| 47 | * @return string |
| 48 | */ |
| 49 | private function formatEntry( array $entry ): string { |
| 50 | $output = ''; |
| 51 | $indent = ' '; |
| 52 | |
| 53 | foreach ( $entry['corpora'] as $id => $unit ) { |
| 54 | unset( $unit['source']['timestamp'], $unit['user']['timestamp'], $unit['mt']['timestamp'] ); |
| 55 | |
| 56 | $globalId = "{$entry['id']}/$id"; |
| 57 | $section = [ |
| 58 | 'id' => $globalId, |
| 59 | 'sourceLanguage' => $entry['sourceLanguage'], |
| 60 | 'targetLanguage' => $entry['targetLanguage'], |
| 61 | 'source' => $unit['source'], |
| 62 | 'mt' => $unit['mt'], |
| 63 | 'target' => $unit['user'], |
| 64 | ]; |
| 65 | |
| 66 | $json = FormatJson::encode( $section, $indent, FormatJson::ALL_OK ); |
| 67 | $output .= self::indent( $indent, $json ) . ",\n"; |
| 68 | } |
| 69 | |
| 70 | $output = rtrim( $output, "\n," ); |
| 71 | return $output; |
| 72 | } |
| 73 | |
| 74 | private static function indent( string $indent, string $text ): string { |
| 75 | // Assuming literal newlines do not occur within strings |
| 76 | $text = $indent . str_replace( "\n", "\n$indent", $text ); |
| 77 | return $text; |
| 78 | } |
| 79 | } |