XOOPS  2.6.0
JsonFormatter.php
Go to the documentation of this file.
1 <?php
2 namespace Xoops\Core;
3 
4 /*
5  * This file is part of Composer.
6  *
7  * (c) Nils Adermann <naderman@naderman.de>
8  * Jordi Boggiano <j.boggiano@seld.be>
9  *
10  * For the full copyright and license information, please view the LICENSE
11  * file that was distributed with this source code.
12  */
13 
14 //namespace Composer\Json;
15 
25 {
39  public static function format($json, $unescapeUnicode, $unescapeSlashes)
40  {
41  $result = '';
42  $pos = 0;
43  $strLen = strlen($json);
44  $indentStr = ' ';
45  $newLine = "\n";
46  $outOfQuotes = true;
47  $buffer = '';
48  $noescape = true;
49 
50  for ($i = 0; $i < $strLen; ++$i) {
51  // Grab the next character in the string
52  $char = substr($json, $i, 1);
53 
54  // Are we inside a quoted string?
55  if ('"' === $char && $noescape) {
56  $outOfQuotes = !$outOfQuotes;
57  }
58 
59  if (!$outOfQuotes) {
60  $buffer .= $char;
61  $noescape = '\\' === $char ? !$noescape : true;
62  continue;
63  } elseif ('' !== $buffer) {
64  if ($unescapeSlashes) {
65  $buffer = str_replace('\\/', '/', $buffer);
66  }
67 
68  if ($unescapeUnicode && function_exists('mb_convert_encoding')) {
69  // http://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
70  $buffer = preg_replace_callback('/(\\\\+)u([0-9a-f]{4})/i', function ($match) {
71  $l = strlen($match[1]);
72 
73  if ($l % 2) {
74  return str_repeat('\\', $l - 1) . mb_convert_encoding(
75  pack('H*', $match[2]),
76  'UTF-8',
77  'UCS-2BE'
78  );
79  }
80 
81  return $match[0];
82  }, $buffer);
83  }
84 
85  $result .= $buffer.$char;
86  $buffer = '';
87  continue;
88  }
89 
90  if (':' === $char) {
91  // Add a space after the : character
92  $char .= ' ';
93  } elseif (('}' === $char || ']' === $char)) {
94  $pos--;
95  $prevChar = substr($json, $i - 1, 1);
96 
97  if ('{' !== $prevChar && '[' !== $prevChar) {
98  // If this character is the end of an element,
99  // output a new line and indent the next line
100  $result .= $newLine;
101  for ($j = 0; $j < $pos; ++$j) {
102  $result .= $indentStr;
103  }
104  } else {
105  // Collapse empty {} and []
106  $result = rtrim($result)."\n\n".$indentStr;
107  }
108  }
109 
110  $result .= $char;
111 
112  // If the last character was the beginning of an element,
113  // output a new line and indent the next line
114  if (',' === $char || '{' === $char || '[' === $char) {
115  $result .= $newLine;
116 
117  if ('{' === $char || '[' === $char) {
118  ++$pos;
119  }
120 
121  for ($j = 0; $j < $pos; ++$j) {
122  $result .= $indentStr;
123  }
124  }
125  }
126 
127  return $result;
128  }
129 }
$i
Definition: dialog.php:68
$l
Definition: main.php:88
$result
Definition: pda.php:33
static format($json, $unescapeUnicode, $unescapeSlashes)
$j
Definition: help.php:169