PageRenderTime 26ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/tine20/library/Zend/Json.php

https://gitlab.com/rsilveira1987/Expresso
PHP | 339 lines | 125 code | 31 blank | 183 comment | 31 complexity | abfc4567dec51db413b78316a492e37d 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-2009 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 10020 2009-08-18 14:34:09Z j.fischer@metaways.de $
  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-2009 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. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  69. return json_decode($encodedValue, $objectDecodeType);
  70. }
  71. require_once 'Zend/Json/Decoder.php';
  72. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  73. }
  74. /**
  75. * Encode the mixed $valueToEncode into the JSON format
  76. *
  77. * Encodes using ext/json's json_encode() if available.
  78. *
  79. * NOTE: Object should not contain cycles; the JSON format
  80. * does not allow object reference.
  81. *
  82. * NOTE: Only public variables will be encoded
  83. *
  84. * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
  85. * You can enable this by setting $options['enableJsonExprFinder'] = true
  86. *
  87. * @see Zend_Json_Expr
  88. *
  89. * @param mixed $valueToEncode
  90. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  91. * @param array $options Additional options used during encoding
  92. * @return string JSON encoded object
  93. */
  94. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  95. {
  96. if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
  97. return $valueToEncode->toJson();
  98. }
  99. // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
  100. $javascriptExpressions = array();
  101. if(isset($options['enableJsonExprFinder'])
  102. && ($options['enableJsonExprFinder'] == true)
  103. ) {
  104. /**
  105. * @see Zend_Json_Encoder
  106. */
  107. require_once "Zend/Json/Encoder.php";
  108. $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  109. }
  110. // Encoding
  111. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  112. $encodedResult = json_encode($valueToEncode);
  113. } else {
  114. require_once 'Zend/Json/Encoder.php';
  115. $encodedResult = Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  116. }
  117. //only do post-proccessing 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 Zend_Json_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 : Zend_Json_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] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  162. }
  163. } elseif (is_object($value)) {
  164. foreach ($value as $k => $v) {
  165. $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  166. }
  167. }
  168. return $value;
  169. }
  170. /**
  171. * fromXml - Converts XML to JSON
  172. *
  173. * Converts a XML formatted string into a JSON formatted string.
  174. * The value returned will be a string in JSON format.
  175. *
  176. * The caller of this function needs to provide only the first parameter,
  177. * which is an XML formatted String. The second parameter is optional, which
  178. * lets the user to select if the XML attributes in the input XML string
  179. * should be included or ignored in xml2json conversion.
  180. *
  181. * This function converts the XML formatted string into a PHP array by
  182. * calling a recursive (protected static) function in this class. Then, it
  183. * converts that PHP array into JSON by calling the "encode" static funcion.
  184. *
  185. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  186. * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
  187. *
  188. * @static
  189. * @access public
  190. * @param string $xmlStringContents XML String to be converted
  191. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  192. * the xml2json conversion process.
  193. * @return mixed - JSON formatted string on success
  194. * @throws Zend_Json_Exception
  195. */
  196. public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
  197. // Load the XML formatted string into a Simple XML Element object.
  198. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  199. // If it is not a valid XML content, throw an exception.
  200. if ($simpleXmlElementObject == null) {
  201. require_once 'Zend/Json/Exception.php';
  202. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  203. } // End of if ($simpleXmlElementObject == null)
  204. $resultArray = null;
  205. // Call the recursive function to convert the XML into a PHP array.
  206. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  207. // Convert the PHP array to JSON using Zend_Json encode method.
  208. // It is just that simple.
  209. $jsonStringOutput = self::encode($resultArray);
  210. return($jsonStringOutput);
  211. } // End of function fromXml.
  212. /**
  213. * _processXml - Contains the logic for xml2json
  214. *
  215. * The logic in this function is a recursive one.
  216. *
  217. * The main caller of this function (i.e. fromXml) needs to provide
  218. * only the first two parameters i.e. the SimpleXMLElement object and
  219. * the flag for ignoring or not ignoring XML attributes. The third parameter
  220. * will be used internally within this function during the recursive calls.
  221. *
  222. * This function converts the SimpleXMLElement object into a PHP array by
  223. * calling a recursive (protected static) function in this class. Once all
  224. * the XML elements are stored in the PHP array, it is returned to the caller.
  225. *
  226. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  227. *
  228. * @static
  229. * @access protected
  230. * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted
  231. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  232. * the xml2json conversion process.
  233. * @param int $recursionDepth Current recursion depth of this function
  234. * @return mixed - On success, a PHP associative array of traversed XML elements
  235. * @throws Zend_Json_Exception
  236. */
  237. protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
  238. // Keep an eye on how deeply we are involved in recursion.
  239. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  240. // XML tree is too deep. Exit now by throwing an exception.
  241. require_once 'Zend/Json/Exception.php';
  242. throw new Zend_Json_Exception(
  243. "Function _processXml exceeded the allowed recursion depth of " .
  244. self::$maxRecursionDepthAllowed);
  245. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  246. if ($recursionDepth == 0) {
  247. // Store the original SimpleXmlElementObject sent by the caller.
  248. // We will need it at the very end when we return from here for good.
  249. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
  250. } // End of if ($recursionDepth == 0)
  251. if ($simpleXmlElementObject instanceof SimpleXMLElement) {
  252. // Get a copy of the simpleXmlElementObject
  253. $copyOfSimpleXmlElementObject = $simpleXmlElementObject;
  254. // Get the object variables in the SimpleXmlElement object for us to iterate.
  255. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
  256. } // End of if (get_class($simpleXmlElementObject) == "SimpleXMLElement")
  257. // It needs to be an array of object variables.
  258. if (is_array($simpleXmlElementObject)) {
  259. // Initialize a result array.
  260. $resultArray = array();
  261. // Is the input array size 0? Then, we reached the rare CDATA text if any.
  262. if (count($simpleXmlElementObject) <= 0) {
  263. // Let us return the lonely CDATA. It could even be
  264. // an empty element or just filled with whitespaces.
  265. return (trim(strval($copyOfSimpleXmlElementObject)));
  266. } // End of if (count($simpleXmlElementObject) <= 0)
  267. // Let us walk through the child elements now.
  268. foreach($simpleXmlElementObject as $key=>$value) {
  269. // Check if we need to ignore the XML attributes.
  270. // If yes, you can skip processing the XML attributes.
  271. // Otherwise, add the XML attributes to the result array.
  272. if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
  273. continue;
  274. } // End of if(($ignoreXmlAttributes == true) && ($key == "@attributes"))
  275. // Let us recursively process the current XML element we just visited.
  276. // Increase the recursion depth by one.
  277. $recursionDepth++;
  278. $resultArray[$key] = self::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);
  279. // Decrease the recursion depth by one.
  280. $recursionDepth--;
  281. } // End of foreach($simpleXmlElementObject as $key=>$value) {
  282. if ($recursionDepth == 0) {
  283. // That is it. We are heading to the exit now.
  284. // Set the XML root element name as the root [top-level] key of
  285. // the associative array that we are going to return to the original
  286. // caller of this recursive function.
  287. $tempArray = $resultArray;
  288. $resultArray = array();
  289. $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
  290. } // End of if ($recursionDepth == 0)
  291. return($resultArray);
  292. } else {
  293. // We are now looking at either the XML attribute text or
  294. // the text between the XML tags.
  295. // In order to allow Zend_Json_Expr from xml, we check if the node
  296. // matchs the pattern that try to detect if it is a new Zend_Json_Expr
  297. // if it matches, we return a new Zend_Json_Expr instead of a text node
  298. $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  299. $matchings = array();
  300. $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
  301. if ($match) {
  302. return new Zend_Json_Expr($matchings[1]);
  303. } else {
  304. return (trim(strval($simpleXmlElementObject)));
  305. }
  306. } // End of if (is_array($simpleXmlElementObject))
  307. } // End of function _processXml.
  308. }