StaticArrayWriter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. *
  17. */
  18. namespace Wikimedia;
  19. /**
  20. * Format a static PHP array to be written to a file
  21. *
  22. * @since 1.32
  23. */
  24. class StaticArrayWriter {
  25. /**
  26. * @param array $data Array with keys/values to export
  27. * @param string $header
  28. *
  29. * @return string PHP code
  30. */
  31. public function create( array $data, $header = 'Automatically generated' ) {
  32. $code = "<?php\n"
  33. . "// " . implode( "\n// ", explode( "\n", $header ) ) . "\n"
  34. . "return [\n";
  35. foreach ( $data as $key => $value ) {
  36. $code .= $this->encode( $key, $value, 1 );
  37. }
  38. $code .= "];\n";
  39. return $code;
  40. }
  41. /**
  42. * Recursively turn one k/v pair into properly-indented PHP
  43. *
  44. * @param string|int $key
  45. * @param array|mixed $value
  46. * @param int $indent Indentation level
  47. *
  48. * @return string
  49. */
  50. private function encode( $key, $value, $indent ) {
  51. $tabs = str_repeat( "\t", $indent );
  52. $line = $tabs .
  53. var_export( $key, true ) .
  54. ' => ';
  55. if ( is_array( $value ) ) {
  56. $line .= "[\n";
  57. foreach ( $value as $key2 => $value2 ) {
  58. $line .= $this->encode( $key2, $value2, $indent + 1 );
  59. }
  60. $line .= "$tabs]";
  61. } else {
  62. $line .= var_export( $value, true );
  63. }
  64. $line .= ",\n";
  65. return $line;
  66. }
  67. }