MediaWiki master
StaticArrayWriter.php
Go to the documentation of this file.
1<?php
6namespace Wikimedia;
7
20 public function create( array $data, $header = 'Automatically generated' ) {
21 return self::write( $data, $header );
22 }
23
32 public static function write( array $data, $header ) {
33 $code = "<?php\n"
34 . "// " . implode( "\n// ", explode( "\n", $header ) ) . "\n"
35 . "return " . self::encodeArray( $data ) . ";\n";
36 return $code;
37 }
38
50 public static function writeClass( array $data, array $layout ) {
51 $code = "<?php\n"
52 . "// " . implode( "\n// ", explode( "\n", $layout['header'] ) ) . "\n"
53 . "\n"
54 . "namespace {$layout['namespace']};\n"
55 . "\n"
56 . "class {$layout['class']} {\n"
57 . "\tpublic const {$layout['const']} = " . self::encodeArray( $data, "\t\t" ) . ";\n}\n";
58 return $code;
59 }
60
68 private static function encodeArray( array $array, string $tabs = "\t" ): string {
69 $code = "[\n";
70 if ( array_is_list( $array ) ) {
71 foreach ( $array as $value ) {
72 $code .= $tabs . self::encodeValue( $value, $tabs ) . ",\n";
73 }
74 } else {
75 foreach ( $array as $key => $value ) {
76 $code .= $tabs . var_export( $key, true ) . ' => ' .
77 self::encodeValue( $value, $tabs ) . ",\n";
78 }
79 }
80 return $code . substr( $tabs, 0, -1 ) . ']';
81 }
82
90 private static function encodeValue( $value, string $tabs ): string {
91 if ( is_array( $value ) ) {
92 return self::encodeArray( $value, $tabs . "\t" );
93 }
94
95 // var_export() exports nulls as uppercase NULL which
96 // violates our own coding standards.
97 return $value === null ? 'null' : var_export( $value, true );
98 }
99}
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
Format a static PHP array to be written to a file.
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.