MediaWiki REL1_41
StaticArrayWriter.php
Go to the documentation of this file.
1<?php
19namespace Wikimedia;
20
33 public function create( array $data, $header = 'Automatically generated' ) {
34 return self::write( $data, $header );
35 }
36
45 public static function write( array $data, $header ) {
46 $code = "<?php\n"
47 . "// " . implode( "\n// ", explode( "\n", $header ) ) . "\n"
48 . "return [\n";
49 foreach ( $data as $key => $value ) {
50 $code .= self::encodePair( $key, $value, 1 );
51 }
52 $code .= "];\n";
53 return $code;
54 }
55
67 public static function writeClass( array $data, array $layout ) {
68 $code = "<?php\n"
69 . "// " . implode( "\n// ", explode( "\n", $layout['header'] ) ) . "\n"
70 . "\n"
71 . "namespace {$layout['namespace']};\n"
72 . "\n"
73 . "class {$layout['class']} {\n"
74 . "\tpublic const {$layout['const']} = [\n";
75 foreach ( $data as $key => $value ) {
76 $code .= self::encodePair( $key, $value, 2 );
77 }
78 $code .= "\t];\n}\n";
79 return $code;
80 }
81
92 private static function encodePair( $key, $value, $indent = 0 ) {
93 $tabs = str_repeat( "\t", $indent );
94 $line = $tabs . var_export( $key, true ) . ' => ';
95 $line .= self::encodeValue( $value, $indent );
96
97 $line .= ",\n";
98 return $line;
99 }
100
110 public static function encodeValue( $value, $indent = 0 ) {
111 if ( is_array( $value ) ) {
112 $tabs = str_repeat( "\t", $indent );
113 $line = "[\n";
114 foreach ( $value as $subkey => $subvalue ) {
115 $line .= self::encodePair( $subkey, $subvalue, $indent + 1 );
116 }
117 $line .= "$tabs]";
118 return $line;
119 } else {
120 $exportedValue = var_export( $value, true );
121 if ( $exportedValue === 'NULL' ) {
122 // var_export() exports nulls as uppercase NULL which
123 // violates our own coding standards.
124 $exportedValue = 'null';
125 }
126 return $exportedValue;
127 }
128 }
129}
Format a static PHP array to be written to a file.
static encodeValue( $value, $indent=0)
Recursively turn one value into properly-indented PHP.
create(array $data, $header='Automatically generated')
static write(array $data, $header)
Create a PHP file that returns the array.
static writeClass(array $data, array $layout)
Create an PHP class file with the array as a class constant.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
$header