/framework/vendor/zend/Zend/Json.php

http://zoop.googlecode.com/ · PHP · 406 lines · 175 code · 37 blank · 194 comment · 55 complexity · 62715221d3b96e0ecdbb92a2397c3054 MD5 · raw file

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