JsonFormatter.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Json;
  12. /**
  13. * Format JSON output
  14. *
  15. * @author Justin Rainbow <justin.rainbow@gmail.com>
  16. */
  17. class JsonFormatter
  18. {
  19. private $indent = ' ';
  20. private $level = 1;
  21. /**
  22. * Indents a flat JSON string to make it more human-readable
  23. *
  24. * Original code for this function can be found at:
  25. * http://recursive-design.com/blog/2008/03/11/format-json-with-php/
  26. *
  27. * @param string $json The original JSON string to process
  28. * @return string Indented version of the original JSON string
  29. */
  30. public function format($json)
  31. {
  32. if (!is_string($json)) {
  33. $json = json_encode($json);
  34. }
  35. $result = '';
  36. $pos = 0;
  37. $strLen = strlen($json);
  38. $indentStr = $this->indent;
  39. $newLine = "\n";
  40. $prevChar = '';
  41. $outOfQuotes = true;
  42. for ($i = 0; $i <= $strLen; $i++) {
  43. // Grab the next character in the string
  44. $char = substr($json, $i, 1);
  45. // Are we inside a quoted string?
  46. if ($char == '"' && $prevChar != '\\') {
  47. $outOfQuotes = !$outOfQuotes;
  48. } else if (($char == '}' || $char == ']') && $outOfQuotes) {
  49. // If this character is the end of an element,
  50. // output a new line and indent the next line
  51. $result .= $newLine;
  52. $pos --;
  53. for ($j=0; $j<$pos; $j++) {
  54. $result .= $indentStr;
  55. }
  56. }
  57. // Add the character to the result string
  58. $result .= $char;
  59. // If the last character was the beginning of an element,
  60. // output a new line and indent the next line
  61. if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
  62. $result .= $newLine;
  63. if ($char == '{' || $char == '[') {
  64. $pos ++;
  65. }
  66. for ($j = 0; $j < $pos; $j++) {
  67. $result .= $indentStr;
  68. }
  69. }
  70. $prevChar = $char;
  71. }
  72. return $result;
  73. }
  74. }