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

/lib/Zend/Json.php

https://github.com/jpratt/cal
PHP | 243 lines | 71 code | 24 blank | 148 comment | 22 complexity | e3935dbc8dbfa688abfae12e742e9eab 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-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /**
  21. * Class for encoding to and decoding from JSON.
  22. *
  23. * @category Zend
  24. * @package Zend_Json
  25. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  26. * @license http://framework.zend.com/license/new-bsd New BSD License
  27. */
  28. class Zend_Json
  29. {
  30. /**
  31. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  32. * so that it is a boolean true value, allowing it to be used with
  33. * ext/json's functions.
  34. */
  35. const TYPE_ARRAY = 1;
  36. const TYPE_OBJECT = 0;
  37. /**
  38. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  39. *
  40. * @var int
  41. */
  42. public static $maxRecursionDepthAllowed=25;
  43. /**
  44. * @var bool
  45. */
  46. public static $useBuiltinEncoderDecoder = false;
  47. /**
  48. * Decodes the given $encodedValue string which is
  49. * encoded in the JSON format
  50. *
  51. * Uses ext/json's json_decode if available.
  52. *
  53. * @param string $encodedValue Encoded in JSON format
  54. * @param int $objectDecodeType Optional; flag indicating how to decode
  55. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  56. * @return mixed
  57. */
  58. public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
  59. {
  60. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  61. return json_decode($encodedValue, $objectDecodeType);
  62. }
  63. #require_once 'Zend/Json/Decoder.php';
  64. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  65. }
  66. /**
  67. * Encode the mixed $valueToEncode into the JSON format
  68. *
  69. * Encodes using ext/json's json_encode() if available.
  70. *
  71. * NOTE: Object should not contain cycles; the JSON format
  72. * does not allow object reference.
  73. *
  74. * NOTE: Only public variables will be encoded
  75. *
  76. * @param mixed $valueToEncode
  77. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  78. * @param array $options Additional options used during encoding
  79. * @return string JSON encoded object
  80. */
  81. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  82. {
  83. if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
  84. return $valueToEncode->toJson();
  85. }
  86. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  87. return json_encode($valueToEncode);
  88. }
  89. #require_once 'Zend/Json/Encoder.php';
  90. return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  91. }
  92. /**
  93. * fromXml - Converts XML to JSON
  94. *
  95. * Converts a XML formatted string into a JSON formatted string.
  96. * The value returned will be a string in JSON format.
  97. *
  98. * The caller of this function needs to provide only the first parameter,
  99. * which is an XML formatted String. The second parameter is optional, which
  100. * lets the user to select if the XML attributes in the input XML string
  101. * should be included or ignored in xml2json conversion.
  102. *
  103. * This function converts the XML formatted string into a PHP array by
  104. * calling a recursive (protected static) function in this class. Then, it
  105. * converts that PHP array into JSON by calling the "encode" static funcion.
  106. *
  107. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  108. *
  109. * @static
  110. * @access public
  111. * @param string $xmlStringContents XML String to be converted
  112. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  113. * the xml2json conversion process.
  114. * @return mixed - JSON formatted string on success
  115. * @throws Zend_Json_Exception
  116. */
  117. public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
  118. // Load the XML formatted string into a Simple XML Element object.
  119. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  120. // If it is not a valid XML content, throw an exception.
  121. if ($simpleXmlElementObject == null) {
  122. #require_once 'Zend/Json/Exception.php';
  123. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  124. } // End of if ($simpleXmlElementObject == null)
  125. $resultArray = null;
  126. // Call the recursive function to convert the XML into a PHP array.
  127. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  128. // Convert the PHP array to JSON using Zend_Json encode method.
  129. // It is just that simple.
  130. $jsonStringOutput = self::encode($resultArray);
  131. return($jsonStringOutput);
  132. } // End of function fromXml.
  133. /**
  134. * _processXml - Contains the logic for xml2json
  135. *
  136. * The logic in this function is a recursive one.
  137. *
  138. * The main caller of this function (i.e. fromXml) needs to provide
  139. * only the first two parameters i.e. the SimpleXMLElement object and
  140. * the flag for ignoring or not ignoring XML attributes. The third parameter
  141. * will be used internally within this function during the recursive calls.
  142. *
  143. * This function converts the SimpleXMLElement object into a PHP array by
  144. * calling a recursive (protected static) function in this class. Once all
  145. * the XML elements are stored in the PHP array, it is returned to the caller.
  146. *
  147. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  148. *
  149. * @static
  150. * @access protected
  151. * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted
  152. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  153. * the xml2json conversion process.
  154. * @param int $recursionDepth Current recursion depth of this function
  155. * @return mixed - On success, a PHP associative array of traversed XML elements
  156. * @throws Zend_Json_Exception
  157. */
  158. protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
  159. // Keep an eye on how deeply we are involved in recursion.
  160. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  161. // XML tree is too deep. Exit now by throwing an exception.
  162. #require_once 'Zend/Json/Exception.php';
  163. throw new Zend_Json_Exception(
  164. "Function _processXml exceeded the allowed recursion depth of " .
  165. self::$maxRecursionDepthAllowed);
  166. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  167. if ($recursionDepth == 0) {
  168. // Store the original SimpleXmlElementObject sent by the caller.
  169. // We will need it at the very end when we return from here for good.
  170. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
  171. } // End of if ($recursionDepth == 0)
  172. if ($simpleXmlElementObject instanceof SimpleXMLElement) {
  173. // Get a copy of the simpleXmlElementObject
  174. $copyOfSimpleXmlElementObject = $simpleXmlElementObject;
  175. // Get the object variables in the SimpleXmlElement object for us to iterate.
  176. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
  177. } // End of if (get_class($simpleXmlElementObject) == "SimpleXMLElement")
  178. // It needs to be an array of object variables.
  179. if (is_array($simpleXmlElementObject)) {
  180. // Initialize a result array.
  181. $resultArray = array();
  182. // Is the input array size 0? Then, we reached the rare CDATA text if any.
  183. if (count($simpleXmlElementObject) <= 0) {
  184. // Let us return the lonely CDATA. It could even be
  185. // an empty element or just filled with whitespaces.
  186. return (trim(strval($copyOfSimpleXmlElementObject)));
  187. } // End of if (count($simpleXmlElementObject) <= 0)
  188. // Let us walk through the child elements now.
  189. foreach($simpleXmlElementObject as $key=>$value) {
  190. // Check if we need to ignore the XML attributes.
  191. // If yes, you can skip processing the XML attributes.
  192. // Otherwise, add the XML attributes to the result array.
  193. if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
  194. continue;
  195. } // End of if(($ignoreXmlAttributes == true) && ($key == "@attributes"))
  196. // Let us recursively process the current XML element we just visited.
  197. // Increase the recursion depth by one.
  198. $recursionDepth++;
  199. $resultArray[$key] = self::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);
  200. // Decrease the recursion depth by one.
  201. $recursionDepth--;
  202. } // End of foreach($simpleXmlElementObject as $key=>$value) {
  203. if ($recursionDepth == 0) {
  204. // That is it. We are heading to the exit now.
  205. // Set the XML root element name as the root [top-level] key of
  206. // the associative array that we are going to return to the original
  207. // caller of this recursive function.
  208. $tempArray = $resultArray;
  209. $resultArray = array();
  210. $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
  211. } // End of if ($recursionDepth == 0)
  212. return($resultArray);
  213. } else {
  214. // We are now looking at either the XML attribute text or
  215. // the text between the XML tags.
  216. return (trim(strval($simpleXmlElementObject)));
  217. } // End of if (is_array($simpleXmlElementObject))
  218. } // End of function _processXml.
  219. }