This repository has been archived by the owner on Jan 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormatter.php
93 lines (91 loc) · 2.35 KB
/
Formatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
namespace RedCat\JSON5;
class Formatter {
protected $json;
protected $indent;
protected $linebreak;
public function __construct($json, $indent = ' ', $linebreak = "\n") {
$this->json = $json;
$this->indent = $indent;
$this->linebreak = $linebreak;
}
public function format($options = 0, $keepComments = false) {
return $this->json_encode($this->json, $options, $keepComments, $this->indent, $this->linebreak);
}
public static function json_encode($value, $options = 0, $keepComments = false, $indent = ' ', $linebreak = "\n", $nested = 1) {
$pretty = $options&JSON_PRETTY_PRINT;
$indent = $pretty?$indent:'';
$linebreak = $pretty?$linebreak:'';
if (is_null($value)) {
return 'null';
}
elseif (is_scalar($value)) {
return json_encode($value,$options);
}
elseif (is_array($value)) {
$with_keys = false;
$n = count($value);
for ($i = 0, reset($value); $i < $n; $i++, next($value)) {
if (key($value) !== $i) {
$with_keys = true;
break;
}
}
}
elseif (is_object($value)) {
$with_keys = true;
if($value instanceof \JsonSerializable){
$value = $value->jsonSerialize();
}
}
else {
return '';
}
$result = [];
$c = 0;
foreach ($value as $key => $v) {
if(!$v instanceof Comment){
$c++;
}
}
$i = 1;
$lastchr = null;
foreach ($value as $key => $v) {
if($v instanceof Comment){
if(!$keepComments)
continue;
$r = $v;
}
else{
$r = '';
if($lastchr!=$linebreak){ //don't duplicate linebreak from comments
$r .= $linebreak;
}
$r .= str_repeat($indent,$nested);
if ($with_keys) {
$r .= json_encode($key, $options) . ': ';
}
$r .= self::json_encode($v, $options, $keepComments, $indent, $linebreak, $nested+1);
if($i<$c){
$r .= ',';
}
if($pretty&&(is_object($v)||is_array($v))){
$r .= $linebreak;
}
$i++;
}
$result[] = $r;
$lastchr = substr($r,-1);
}
$r = $with_keys?'{':'[';
$r .= implode('', $result);
if($lastchr!=$linebreak){ //don't duplicate linebreak from comments
$r .= $linebreak;
}
if($pretty&&$nested>1){
$r .= str_repeat($indent, $nested-1);
}
$r .= $with_keys?'}':']';
return $r;
}
}