MediaWiki master
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 " . self::encodeArray( $data ) . ";\n";
49 return $code;
50 }
51
63 public static function writeClass( array $data, array $layout ) {
64 $code = "<?php\n"
65 . "// " . implode( "\n// ", explode( "\n", $layout['header'] ) ) . "\n"
66 . "\n"
67 . "namespace {$layout['namespace']};\n"
68 . "\n"
69 . "class {$layout['class']} {\n"
70 . "\tpublic const {$layout['const']} = " . self::encodeArray( $data, 1 ) . ";\n}\n";
71 return $code;
72 }
73
81 private static function encodeArray( array $array, $indent = 0 ) {
82 $code = "[\n";
83 $tabs = str_repeat( "\t", $indent );
84 if ( array_is_list( $array ) ) {
85 foreach ( $array as $item ) {
86 $code .= self::encodeItem( $item, $indent + 1 );
87 }
88 } else {
89 foreach ( $array as $key => $value ) {
90 $code .= self::encodePair( $key, $value, $indent + 1 );
91 }
92 }
93 $code .= "$tabs]";
94 return $code;
95 }
96
105 private static function encodePair( $key, $value, $indent = 0 ) {
106 $tabs = str_repeat( "\t", $indent );
107 $line = $tabs . var_export( $key, true ) . ' => ';
108 $line .= self::encodeValue( $value, $indent );
109
110 $line .= ",\n";
111 return $line;
112 }
113
121 private static function encodeItem( $value, $indent = 0 ) {
122 $tabs = str_repeat( "\t", $indent );
123 $line = $tabs . self::encodeValue( $value, $indent );
124
125 $line .= ",\n";
126 return $line;
127 }
128
137 public static function encodeValue( $value, $indent = 0 ) {
138 if ( is_array( $value ) ) {
139 return self::encodeArray( $value, $indent );
140 } else {
141 $exportedValue = var_export( $value, true );
142 if ( $exportedValue === 'NULL' ) {
143 // var_export() exports nulls as uppercase NULL which
144 // violates our own coding standards.
145 $exportedValue = 'null';
146 }
147 return $exportedValue;
148 }
149 }
150}
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