Created
September 20, 2019 23:37
-
-
Save d4rkne55/f300c995ee7d2f7134b80eb66484bee2 to your computer and use it in GitHub Desktop.
Class for dumping/beautifying JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JsonDumper | |
{ | |
/** @var string */ | |
private $json; | |
/** @var int spaces to use for one indentation level */ | |
private $indentation; | |
public function __construct($json, $indentation = 4) { | |
// TODO: check if json is valid first | |
$this->json = $json; | |
$this->indentation = $indentation; | |
$this->process(); | |
} | |
private function process() { | |
$pos = 0; | |
$currentIndent = 0; | |
while (($nextPos = $this->getNextToken($pos)) !== false) { | |
$newLine = true; | |
// if a token is at current position | |
if ($nextPos === $pos) { | |
$token = $this->json[$pos]; | |
if ($token == '}' || $token == ']') { | |
$currentIndent -= $this->indentation; | |
$newLine = false; | |
echo "\n", str_repeat(' ', $currentIndent); | |
} elseif ($token == '{' || $token == '[') { | |
$currentIndent += $this->indentation; | |
} | |
echo $token; | |
if ($token == ':') { | |
$newLine = false; | |
echo ' '; | |
} | |
$pos++; | |
} | |
if ($newLine) { | |
echo "\n", str_repeat(' ', $currentIndent); | |
} | |
$nextPos = ($this->getNextToken($pos) !== false) ? $this->getNextToken($pos) : strlen($this->json); | |
echo substr($this->json, $pos, $nextPos - $pos); | |
$pos = $nextPos; | |
} | |
} | |
private function getNextToken($currentPos) { | |
$tokens = '{}[]:,'; | |
$regex = preg_quote($tokens); | |
preg_match("/[$regex]/", $this->json, $matches, PREG_OFFSET_CAPTURE, $currentPos); | |
if (isset($matches[0][1])) { | |
return $matches[0][1]; | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment