PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/zendframework/zendframework/library/Zend/Json/Json.php

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