PageRenderTime 22ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Json/Json.php

https://github.com/shevron/zf2
PHP | 380 lines | 191 code | 34 blank | 155 comment | 53 complexity | 8513be440fa8cc9f154ef3515b4e4784 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-2012 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. * @package Zend_Json
  9. */
  10. namespace Zend\Json;
  11. use Zend\Json\Exception\RecursionException;
  12. use Zend\Json\Exception\RuntimeException;
  13. /**
  14. * Class for encoding to and decoding from JSON.
  15. *
  16. * @category Zend
  17. * @package Zend_Json
  18. */
  19. class Json
  20. {
  21. /**
  22. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  23. * so that it is a boolean true value, allowing it to be used with
  24. * ext/json's functions.
  25. */
  26. const TYPE_ARRAY = 1;
  27. const TYPE_OBJECT = 0;
  28. /**
  29. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  30. *
  31. * @var int
  32. */
  33. public static $maxRecursionDepthAllowed=25;
  34. /**
  35. * @var bool
  36. */
  37. public static $useBuiltinEncoderDecoder = false;
  38. /**
  39. * Decodes the given $encodedValue string which is
  40. * encoded in the JSON format
  41. *
  42. * Uses ext/json's json_decode if available.
  43. *
  44. * @param string $encodedValue Encoded in JSON format
  45. * @param int $objectDecodeType Optional; flag indicating how to decode
  46. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  47. * @return mixed
  48. * @throws Zend\Json\Exception\RuntimeException
  49. */
  50. public static function decode($encodedValue, $objectDecodeType = self::TYPE_OBJECT)
  51. {
  52. $encodedValue = (string) $encodedValue;
  53. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  54. $decode = json_decode($encodedValue, $objectDecodeType);
  55. switch (json_last_error()) {
  56. case JSON_ERROR_NONE:
  57. break;
  58. case JSON_ERROR_DEPTH:
  59. throw new RuntimeException('Decoding failed: Maximum stack depth exceeded');
  60. case JSON_ERROR_CTRL_CHAR:
  61. throw new RuntimeException('Decoding failed: Unexpected control character found');
  62. case JSON_ERROR_SYNTAX:
  63. throw new RuntimeException('Decoding failed: Syntax error');
  64. default:
  65. throw new RuntimeException('Decoding failed');
  66. }
  67. return $decode;
  68. }
  69. return Decoder::decode($encodedValue, $objectDecodeType);
  70. }
  71. /**
  72. * Encode the mixed $valueToEncode into the JSON format
  73. *
  74. * Encodes using ext/json's json_encode() if available.
  75. *
  76. * NOTE: Object should not contain cycles; the JSON format
  77. * does not allow object reference.
  78. *
  79. * NOTE: Only public variables will be encoded
  80. *
  81. * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
  82. * You can enable this by setting $options['enableJsonExprFinder'] = true
  83. *
  84. * @see Zend_Json_Expr
  85. *
  86. * @param mixed $valueToEncode
  87. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  88. * @param array $options Additional options used during encoding
  89. * @return string JSON encoded object
  90. */
  91. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  92. {
  93. if (is_object($valueToEncode)) {
  94. if (method_exists($valueToEncode, 'toJson')) {
  95. return $valueToEncode->toJson();
  96. } elseif (method_exists($valueToEncode, 'toArray')) {
  97. return self::encode($valueToEncode->toArray(), $cycleCheck, $options);
  98. }
  99. }
  100. // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
  101. $javascriptExpressions = array();
  102. if(isset($options['enableJsonExprFinder'])
  103. && ($options['enableJsonExprFinder'] == true)
  104. ) {
  105. $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  106. }
  107. // Encoding
  108. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  109. $encodedResult = json_encode($valueToEncode);
  110. } else {
  111. $encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
  112. }
  113. //only do post-proccessing 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 $valueToCheck a string - object property to be encoded
  141. * @return void
  142. */
  143. protected static function _recursiveJsonExprFinder(
  144. &$value, array &$javascriptExpressions, $currentKey = null
  145. ) {
  146. if ($value instanceof Expr) {
  147. // TODO: Optimize with ascii keys, if performance is bad
  148. $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
  149. $javascriptExpressions[] = array(
  150. //if currentKey is integer, encodeUnicodeString call is not required.
  151. "magicKey" => (is_int($currentKey)) ? $magicKey : Encoder::encodeUnicodeString($magicKey),
  152. "value" => $value->__toString(),
  153. );
  154. $value = $magicKey;
  155. } elseif (is_array($value)) {
  156. foreach ($value as $k => $v) {
  157. $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  158. }
  159. } elseif (is_object($value)) {
  160. foreach ($value as $k => $v) {
  161. $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  162. }
  163. }
  164. return $value;
  165. }
  166. /**
  167. * Return the value of an XML attribute text or the text between
  168. * the XML tags
  169. *
  170. * In order to allow Zend_Json_Expr from xml, we check if the node
  171. * matchs the pattern that try to detect if it is a new Zend_Json_Expr
  172. * if it matches, we return a new Zend_Json_Expr instead of a text node
  173. *
  174. * @param SimpleXMLElement $simpleXmlElementObject
  175. * @return Zend_Json_Expr|string
  176. */
  177. protected static function _getXmlValue($simpleXmlElementObject)
  178. {
  179. $pattern = '/^[\s]*new Zend[_\\]Json[_\\]Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  180. $matchings = array();
  181. $match = preg_match($pattern, $simpleXmlElementObject, $matchings);
  182. if ($match) {
  183. return new Expr($matchings[1]);
  184. } else {
  185. return (trim(strval($simpleXmlElementObject)));
  186. }
  187. }
  188. /**
  189. * _processXml - Contains the logic for xml2json
  190. *
  191. * The logic in this function is a recursive one.
  192. *
  193. * The main caller of this function (i.e. fromXml) needs to provide
  194. * only the first two parameters i.e. the SimpleXMLElement object and
  195. * the flag for ignoring or not ignoring XML attributes. The third parameter
  196. * will be used internally within this function during the recursive calls.
  197. *
  198. * This function converts the SimpleXMLElement object into a PHP array by
  199. * calling a recursive (protected static) function in this class. Once all
  200. * the XML elements are stored in the PHP array, it is returned to the caller.
  201. *
  202. * Throws a Zend\Json\RecursionException if the XML tree is deeper than the allowed limit.
  203. *
  204. * @param SimpleXMLElement $simpleXmlElementObject
  205. * @param boolean $ignoreXmlAttributes
  206. * @param integer $recursionDepth
  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 > self::$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. . self::$maxRecursionDepthAllowed
  217. );
  218. }
  219. $children = $simpleXmlElementObject->children();
  220. $name = $simpleXmlElementObject->getName();
  221. $value = self::_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] = self::_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 = self::_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] = self::_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 funcion.
  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 boolean $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. // Load the XML formatted string into a Simple XML Element object.
  287. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  288. // If it is not a valid XML content, throw an exception.
  289. if ($simpleXmlElementObject == null) {
  290. throw new RuntimeException('Function fromXml was called with an invalid XML formatted string.');
  291. } // End of if ($simpleXmlElementObject == null)
  292. $resultArray = null;
  293. // Call the recursive function to convert the XML into a PHP array.
  294. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  295. // Convert the PHP array to JSON using Zend_Json encode method.
  296. // It is just that simple.
  297. $jsonStringOutput = self::encode($resultArray);
  298. return($jsonStringOutput);
  299. }
  300. /**
  301. * Pretty-print JSON string
  302. *
  303. * Use 'indent' option to select indentation string - by default it's a tab
  304. *
  305. * @param string $json Original JSON string
  306. * @param array $options Encoding options
  307. * @return string
  308. */
  309. public static function prettyPrint($json, $options = array())
  310. {
  311. $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
  312. $result = "";
  313. $indent = 0;
  314. $ind = "\t";
  315. if(isset($options['indent'])) {
  316. $ind = $options['indent'];
  317. }
  318. $inLiteral = false;
  319. foreach($tokens as $token) {
  320. if($token == "") continue;
  321. $prefix = str_repeat($ind, $indent);
  322. if(!$inLiteral && ($token == "{" || $token == "[")) {
  323. $indent++;
  324. if($result != "" && $result[strlen($result)-1] == "\n") {
  325. $result .= $prefix;
  326. }
  327. $result .= "$token\n";
  328. } else if(!$inLiteral && ($token == "}" || $token == "]")) {
  329. $indent--;
  330. $prefix = str_repeat($ind, $indent);
  331. $result .= "\n$prefix$token";
  332. } else if(!$inLiteral && $token == ",") {
  333. $result .= "$token\n";
  334. } else {
  335. $result .= ($inLiteral ? '' : $prefix) . $token;
  336. // Count # of unescaped double-quotes in token, subtract # of
  337. // escaped double-quotes and if the result is odd then we are
  338. // inside a string literal
  339. if ((substr_count($token, "\"")-substr_count($token, "\\\"")) % 2 != 0) {
  340. $inLiteral = !$inLiteral;
  341. }
  342. }
  343. }
  344. return $result;
  345. }
  346. }