Translate extension for MediaWiki
 
Loading...
Searching...
No Matches
Yaml.php
1<?php
2declare( strict_types = 1 );
3
5
6use InvalidArgumentException;
7use RuntimeException;
8use Spyc;
9
18class Yaml {
19 public static function loadString( string $text ): array {
20 global $wgTranslateYamlLibrary;
21
22 switch ( $wgTranslateYamlLibrary ) {
23 case 'phpyaml':
24 // Harden: do not support unserializing objects.
25 $previousValue = ini_set( 'yaml.decode_php', '0' );
26 $ret = yaml_parse( $text );
27 if ( $previousValue !== false ) {
28 ini_set( 'yaml.decode_php', $previousValue );
29 }
30
31 if ( $ret === false ) {
32 // Convert failures to exceptions
33 throw new InvalidArgumentException( 'Invalid Yaml string' );
34 }
35
36 return $ret;
37 case 'spyc':
38 $yaml = spyc_load( $text );
39
40 return self::fixSpycSpaces( $yaml );
41 default:
42 throw new RuntimeException( 'Unknown Yaml library' );
43 }
44 }
45
46 private static function fixSpycSpaces( array &$yaml ): array {
47 foreach ( $yaml as $key => &$value ) {
48 if ( is_array( $value ) ) {
49 self::fixSpycSpaces( $value );
50 } elseif ( is_string( $value ) && $key === 'header' ) {
51 $value = preg_replace( '~^\*~m', ' *', $value ) . "\n";
52 }
53 }
54
55 return $yaml;
56 }
57
58 public static function load( string $file ): array {
59 $text = file_get_contents( $file );
60
61 return self::loadString( $text );
62 }
63
64 public static function dump( array $text ): string {
65 global $wgTranslateYamlLibrary;
66
67 switch ( $wgTranslateYamlLibrary ) {
68 case 'phpyaml':
69 return yaml_emit( $text, YAML_UTF8_ENCODING );
70 case 'spyc':
71 return Spyc::YAMLDump( $text );
72 default:
73 throw new RuntimeException( 'Unknown Yaml library' );
74 }
75 }
76}
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:18