Exemplo n.º 1
0
 /**
  * Formats a JSON string into a pretty JSON string.
  * 
  * @todo Fix so text-qualified characters eg. ",{[" don't break formatting.
  * 
  * @param string $json
  * @return string
  */
 public static function format($json)
 {
     $indent_character = '    ';
     $indent_count = 0;
     $json_length = strlen($json);
     $position = 0;
     $insert_newline_after = function ($offset) use(&$json, &$indent_character, &$indent_count, &$position) {
         $indent = str_repeat($indent_character, $indent_count);
         $json = \Altumo\String\String::insert("\n" . $indent, $json, $offset + 1);
         $position += strlen($indent) + 1;
     };
     for (; $position < $json_length; $position++) {
         $character = $json[$position];
         switch ($character) {
             case ':':
                 //insert a space after colons
                 $json = \Altumo\String\String::insert(" ", $json, $position + 1);
                 $position++;
                 break;
             case ',':
                 $insert_newline_after($position);
                 break;
             case '[':
             case '{':
                 $indent_count++;
                 $insert_newline_after($position);
                 break;
             case ']':
             case '}':
                 $indent_count--;
                 $insert_newline_after($position - 1);
                 break;
             default:
         }
         $json_length = strlen($json);
     }
     return $json;
 }