PageRenderTime 35ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/app/classes/Zend/Json/Json.php

https://gitlab.com/jalon/doadoronline
PHP | 382 lines | 195 code | 35 blank | 152 comment | 48 complexity | 2175f55fda0c66246e3ce653db7f082e MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Json;
  10. use SimpleXMLElement;
  11. use Zend\Json\Exception\RecursionException;
  12. use Zend\Json\Exception\RuntimeException;
  13. /**
  14. * Class for encoding to and decoding from JSON.
  15. */
  16. class Json
  17. {
  18. /**
  19. * How objects should be encoded -- arrays or as stdClass. TYPE_ARRAY is 1
  20. * so that it is a boolean true value, allowing it to be used with
  21. * ext/json's functions.
  22. */
  23. const TYPE_ARRAY = 1;
  24. const TYPE_OBJECT = 0;
  25. /**
  26. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  27. *
  28. * @var int
  29. */
  30. public static $maxRecursionDepthAllowed = 25;
  31. /**
  32. * @var bool
  33. */
  34. public static $useBuiltinEncoderDecoder = false;
  35. /**
  36. * Decodes the given $encodedValue string which is
  37. * encoded in the JSON format
  38. *
  39. * Uses ext/json's json_decode if available.
  40. *
  41. * @param string $encodedValue Encoded in JSON format
  42. * @param int $objectDecodeType Optional; flag indicating how to decode
  43. * objects. See {@link Zend\Json\Decoder::decode()} for details.
  44. * @return mixed
  45. * @throws RuntimeException
  46. */
  47. public static function decode($encodedValue, $objectDecodeType = self::TYPE_OBJECT)
  48. {
  49. $encodedValue = (string) $encodedValue;
  50. if (function_exists('json_decode') && static::$useBuiltinEncoderDecoder !== true) {
  51. $decode = json_decode($encodedValue, $objectDecodeType);
  52. switch (json_last_error()) {
  53. case JSON_ERROR_NONE:
  54. break;
  55. case JSON_ERROR_DEPTH:
  56. throw new RuntimeException('Decoding failed: Maximum stack depth exceeded');
  57. case JSON_ERROR_CTRL_CHAR:
  58. throw new RuntimeException('Decoding failed: Unexpected control character found');
  59. case JSON_ERROR_SYNTAX:
  60. throw new RuntimeException('Decoding failed: Syntax error');
  61. default:
  62. throw new RuntimeException('Decoding failed');
  63. }
  64. return $decode;
  65. }
  66. return Decoder::decode($encodedValue, $objectDecodeType);
  67. }
  68. /**
  69. * Encode the mixed $valueToEncode into the JSON format
  70. *
  71. * Encodes using ext/json's json_encode() if available.
  72. *
  73. * NOTE: Object should not contain cycles; the JSON format
  74. * does not allow object reference.
  75. *
  76. * NOTE: Only public variables will be encoded
  77. *
  78. * NOTE: Encoding native javascript expressions are possible using Zend\Json\Expr.
  79. * You can enable this by setting $options['enableJsonExprFinder'] = true
  80. *
  81. * @see Zend\Json\Expr
  82. *
  83. * @param mixed $valueToEncode
  84. * @param bool $cycleCheck Optional; whether or not to check for object recursion; off by default
  85. * @param array $options Additional options used during encoding
  86. * @return string JSON encoded object
  87. */
  88. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  89. {
  90. if (is_object($valueToEncode)) {
  91. if (method_exists($valueToEncode, 'toJson')) {
  92. return $valueToEncode->toJson();
  93. } elseif (method_exists($valueToEncode, 'toArray')) {
  94. return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
  95. }
  96. }
  97. // Pre-encoding look for Zend\Json\Expr objects and replacing by tmp ids
  98. $javascriptExpressions = array();
  99. if (isset($options['enableJsonExprFinder'])
  100. && ($options['enableJsonExprFinder'] == true)
  101. ) {
  102. $valueToEncode = static::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  103. }
  104. // Encoding
  105. if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
  106. $encodedResult = json_encode(
  107. $valueToEncode,
  108. JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
  109. );
  110. } else {
  111. $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
  112. }
  113. //only do post-processing to revert back the Zend\Json\Expr if any.
  114. if (count($javascriptExpressions) > 0) {
  115. $count = count($javascriptExpressions);
  116. for ($i = 0; $i < $count; $i++) {
  117. $magicKey = $javascriptExpressions[$i]['magicKey'];
  118. $value = $javascriptExpressions[$i]['value'];
  119. $encodedResult = str_replace(
  120. //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
  121. '"' . $magicKey . '"',
  122. $value,
  123. $encodedResult
  124. );
  125. }
  126. }
  127. return $encodedResult;
  128. }
  129. /**
  130. * Check & Replace Zend\Json\Expr for tmp ids in the valueToEncode
  131. *
  132. * Check if the value is a Zend\Json\Expr, and if replace its value
  133. * with a magic key and save the javascript expression in an array.
  134. *
  135. * NOTE this method is recursive.
  136. *
  137. * NOTE: This method is used internally by the encode method.
  138. *
  139. * @see encode
  140. * @param mixed $value a string - object property to be encoded
  141. * @param array $javascriptExpressions
  142. * @param null|string|int $currentKey
  143. * @return mixed
  144. */
  145. protected static function _recursiveJsonExprFinder(
  146. &$value, array &$javascriptExpressions, $currentKey = null
  147. ) {
  148. if ($value instanceof Expr) {
  149. // TODO: Optimize with ascii keys, if performance is bad
  150. $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
  151. $javascriptExpressions[] = array(
  152. //if currentKey is integer, encodeUnicodeString call is not required.
  153. "magicKey" => (is_int($currentKey)) ? $magicKey : Encoder::encodeUnicodeString($magicKey),
  154. "value" => $value->__toString(),
  155. );
  156. $value = $magicKey;
  157. } elseif (is_array($value)) {
  158. foreach ($value as $k => $v) {
  159. $value[$k] = static::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  160. }
  161. } elseif (is_object($value)) {
  162. foreach ($value as $k => $v) {
  163. $value->$k = static::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  164. }
  165. }
  166. return $value;
  167. }
  168. /**
  169. * Return the value of an XML attribute text or the text between
  170. * the XML tags
  171. *
  172. * In order to allow Zend\Json\Expr from xml, we check if the node
  173. * matches the pattern that try to detect if it is a new Zend\Json\Expr
  174. * if it matches, we return a new Zend\Json\Expr instead of a text node
  175. *
  176. * @param SimpleXMLElement $simpleXmlElementObject
  177. * @return Expr|string
  178. */
  179. protected static function _getXmlValue($simpleXmlElementObject)
  180. {
  181. $pattern = '/^[\s]*new Zend[_\\]Json[_\\]Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  182. $matchings = array();
  183. $match = preg_match($pattern, $simpleXmlElementObject, $matchings);
  184. if ($match) {
  185. return new Expr($matchings[1]);
  186. }
  187. return (trim(strval($simpleXmlElementObject)));
  188. }
  189. /**
  190. * _processXml - Contains the logic for xml2json
  191. *
  192. * The logic in this function is a recursive one.
  193. *
  194. * The main caller of this function (i.e. fromXml) needs to provide
  195. * only the first two parameters i.e. the SimpleXMLElement object and
  196. * the flag for ignoring or not ignoring XML attributes. The third parameter
  197. * will be used internally within this function during the recursive calls.
  198. *
  199. * This function converts the SimpleXMLElement object into a PHP array by
  200. * calling a recursive (protected static) function in this class. Once all
  201. * the XML elements are stored in the PHP array, it is returned to the caller.
  202. *
  203. * @param SimpleXMLElement $simpleXmlElementObject
  204. * @param bool $ignoreXmlAttributes
  205. * @param int $recursionDepth
  206. * @throws Exception\RecursionException if the XML tree is deeper than the allowed limit.
  207. * @return array
  208. */
  209. protected static function _processXml($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth = 0)
  210. {
  211. // Keep an eye on how deeply we are involved in recursion.
  212. if ($recursionDepth > static::$maxRecursionDepthAllowed) {
  213. // XML tree is too deep. Exit now by throwing an exception.
  214. throw new RecursionException(
  215. "Function _processXml exceeded the allowed recursion depth of "
  216. . static::$maxRecursionDepthAllowed
  217. );
  218. }
  219. $children = $simpleXmlElementObject->children();
  220. $name = $simpleXmlElementObject->getName();
  221. $value = static::_getXmlValue($simpleXmlElementObject);
  222. $attributes = (array) $simpleXmlElementObject->attributes();
  223. if (!count($children)) {
  224. if (!empty($attributes) && !$ignoreXmlAttributes) {
  225. foreach ($attributes['@attributes'] as $k => $v) {
  226. $attributes['@attributes'][$k] = static::_getXmlValue($v);
  227. }
  228. if (!empty($value)) {
  229. $attributes['@text'] = $value;
  230. }
  231. return array($name => $attributes);
  232. }
  233. return array($name => $value);
  234. }
  235. $childArray = array();
  236. foreach ($children as $child) {
  237. $childname = $child->getName();
  238. $element = static::_processXml($child, $ignoreXmlAttributes, $recursionDepth + 1);
  239. if (array_key_exists($childname, $childArray)) {
  240. if (empty($subChild[$childname])) {
  241. $childArray[$childname] = array($childArray[$childname]);
  242. $subChild[$childname] = true;
  243. }
  244. $childArray[$childname][] = $element[$childname];
  245. } else {
  246. $childArray[$childname] = $element[$childname];
  247. }
  248. }
  249. if (!empty($attributes) && !$ignoreXmlAttributes) {
  250. foreach ($attributes['@attributes'] as $k => $v) {
  251. $attributes['@attributes'][$k] = static::_getXmlValue($v);
  252. }
  253. $childArray['@attributes'] = $attributes['@attributes'];
  254. }
  255. if (!empty($value)) {
  256. $childArray['@text'] = $value;
  257. }
  258. return array($name => $childArray);
  259. }
  260. /**
  261. * fromXml - Converts XML to JSON
  262. *
  263. * Converts a XML formatted string into a JSON formatted string.
  264. * The value returned will be a string in JSON format.
  265. *
  266. * The caller of this function needs to provide only the first parameter,
  267. * which is an XML formatted String. The second parameter is optional, which
  268. * lets the user to select if the XML attributes in the input XML string
  269. * should be included or ignored in xml2json conversion.
  270. *
  271. * This function converts the XML formatted string into a PHP array by
  272. * calling a recursive (protected static) function in this class. Then, it
  273. * converts that PHP array into JSON by calling the "encode" static function.
  274. *
  275. * NOTE: Encoding native javascript expressions via Zend\Json\Expr is not possible.
  276. *
  277. * @static
  278. * @access public
  279. * @param string $xmlStringContents XML String to be converted
  280. * @param bool $ignoreXmlAttributes Include or exclude XML attributes in
  281. * the xml2json conversion process.
  282. * @return mixed - JSON formatted string on success
  283. * @throws \Zend\Json\Exception\RuntimeException if the input not a XML formatted string
  284. */
  285. public static function fromXml($xmlStringContents, $ignoreXmlAttributes = true)
  286. {
  287. // Load the XML formatted string into a Simple XML Element object.
  288. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  289. // If it is not a valid XML content, throw an exception.
  290. if ($simpleXmlElementObject == null) {
  291. throw new RuntimeException('Function fromXml was called with an invalid XML formatted string.');
  292. } // End of if ($simpleXmlElementObject == null)
  293. $resultArray = null;
  294. // Call the recursive function to convert the XML into a PHP array.
  295. $resultArray = static::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  296. // Convert the PHP array to JSON using Zend\Json\Json encode method.
  297. // It is just that simple.
  298. $jsonStringOutput = static::encode($resultArray);
  299. return($jsonStringOutput);
  300. }
  301. /**
  302. * Pretty-print JSON string
  303. *
  304. * Use 'indent' option to select indentation string - by default it's a tab
  305. *
  306. * @param string $json Original JSON string
  307. * @param array $options Encoding options
  308. * @return string
  309. */
  310. public static function prettyPrint($json, $options = array())
  311. {
  312. $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
  313. $result = "";
  314. $indent = 0;
  315. $ind = "\t";
  316. if (isset($options['indent'])) {
  317. $ind = $options['indent'];
  318. }
  319. $inLiteral = false;
  320. foreach ($tokens as $token) {
  321. if ($token == "") continue;
  322. $prefix = str_repeat($ind, $indent);
  323. if (!$inLiteral && ($token == "{" || $token == "[")) {
  324. $indent++;
  325. if ($result != "" && $result[strlen($result)-1] == "\n") {
  326. $result .= $prefix;
  327. }
  328. $result .= "$token\n";
  329. } elseif (!$inLiteral && ($token == "}" || $token == "]")) {
  330. $indent--;
  331. $prefix = str_repeat($ind, $indent);
  332. $result .= "\n$prefix$token";
  333. } elseif (!$inLiteral && $token == ",") {
  334. $result .= "$token\n";
  335. } else {
  336. $result .= ($inLiteral ? '' : $prefix) . $token;
  337. // Count # of unescaped double-quotes in token, subtract # of
  338. // escaped double-quotes and if the result is odd then we are
  339. // inside a string literal
  340. if ((substr_count($token, "\"")-substr_count($token, "\\\"")) % 2 != 0) {
  341. $inLiteral = !$inLiteral;
  342. }
  343. }
  344. }
  345. return $result;
  346. }
  347. }