Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 25 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
Yaml | |
0.00% |
0 / 25 |
|
0.00% |
0 / 4 |
272 | |
0.00% |
0 / 1 |
loadString | |
0.00% |
0 / 12 |
|
0.00% |
0 / 1 |
42 | |||
fixSpycSpaces | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
30 | |||
load | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
dump | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
20 |
1 | <?php |
2 | declare( strict_types = 1 ); |
3 | |
4 | namespace MediaWiki\Extension\Translate\Utilities; |
5 | |
6 | use InvalidArgumentException; |
7 | use RuntimeException; |
8 | use Spyc; |
9 | use function spyc_load; |
10 | use function yaml_emit; |
11 | use function yaml_parse; |
12 | |
13 | /** |
14 | * A wrapper class to provide interface to parse |
15 | * and generate YAML files with phpyaml or spyc backend. |
16 | * @author Ævar Arnfjörð Bjarmason |
17 | * @author Niklas Laxström |
18 | * @copyright Copyright © 2009-2013, Niklas Laxström, Ævar Arnfjörð Bjarmason |
19 | * @license GPL-2.0-or-later |
20 | */ |
21 | class Yaml { |
22 | public static function loadString( string $text ): array { |
23 | global $wgTranslateYamlLibrary; |
24 | |
25 | switch ( $wgTranslateYamlLibrary ) { |
26 | case 'phpyaml': |
27 | // Harden: do not support unserializing objects. |
28 | $previousValue = ini_set( 'yaml.decode_php', '0' ); |
29 | $ret = yaml_parse( $text ); |
30 | if ( $previousValue !== false ) { |
31 | ini_set( 'yaml.decode_php', $previousValue ); |
32 | } |
33 | |
34 | if ( $ret === false ) { |
35 | // Convert failures to exceptions |
36 | throw new InvalidArgumentException( 'Invalid Yaml string' ); |
37 | } |
38 | |
39 | return $ret; |
40 | case 'spyc': |
41 | $yaml = spyc_load( $text ); |
42 | |
43 | return self::fixSpycSpaces( $yaml ); |
44 | default: |
45 | throw new RuntimeException( 'Unknown Yaml library' ); |
46 | } |
47 | } |
48 | |
49 | private static function fixSpycSpaces( array &$yaml ): array { |
50 | foreach ( $yaml as $key => &$value ) { |
51 | if ( is_array( $value ) ) { |
52 | self::fixSpycSpaces( $value ); |
53 | } elseif ( is_string( $value ) && $key === 'header' ) { |
54 | $value = preg_replace( '~^\*~m', ' *', $value ) . "\n"; |
55 | } |
56 | } |
57 | |
58 | return $yaml; |
59 | } |
60 | |
61 | public static function load( string $file ): array { |
62 | $text = file_get_contents( $file ); |
63 | |
64 | return self::loadString( $text ); |
65 | } |
66 | |
67 | public static function dump( array $text ): string { |
68 | global $wgTranslateYamlLibrary; |
69 | |
70 | switch ( $wgTranslateYamlLibrary ) { |
71 | case 'phpyaml': |
72 | return yaml_emit( $text, YAML_UTF8_ENCODING ); |
73 | case 'spyc': |
74 | return Spyc::YAMLDump( $text ); |
75 | default: |
76 | throw new RuntimeException( 'Unknown Yaml library' ); |
77 | } |
78 | } |
79 | } |