Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
Yaml.php
1<?php
2declare( strict_types = 1 );
3
5
6use InvalidArgumentException;
7use RuntimeException;
8use Spyc;
9use function spyc_load;
10use function yaml_emit;
11use function yaml_parse;
12
21class 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}
Essentially random collection of helper functions, similar to GlobalFunctions.php.
Definition Utilities.php:31
A wrapper class to provide interface to parse and generate YAML files with phpyaml or spyc backend.
Definition Yaml.php:21