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

/lib/Zend/Json/Encoder.php

https://bitbucket.org/mengqing/magento-mirror
PHP | 574 lines | 283 code | 77 blank | 214 comment | 39 complexity | 50923a3bcb5ca06a185b6e23e12fc960 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: Encoder.php 22452 2010-06-18 18:13:23Z ralph $
  20. */
  21. /**
  22. * Encode PHP constructs to JSON
  23. *
  24. * @category Zend
  25. * @package Zend_Json
  26. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  27. * @license http://framework.zend.com/license/new-bsd New BSD License
  28. */
  29. class Zend_Json_Encoder
  30. {
  31. /**
  32. * Whether or not to check for possible cycling
  33. *
  34. * @var boolean
  35. */
  36. protected $_cycleCheck;
  37. /**
  38. * Additional options used during encoding
  39. *
  40. * @var array
  41. */
  42. protected $_options = array();
  43. /**
  44. * Array of visited objects; used to prevent cycling.
  45. *
  46. * @var array
  47. */
  48. protected $_visited = array();
  49. /**
  50. * Constructor
  51. *
  52. * @param boolean $cycleCheck Whether or not to check for recursion when encoding
  53. * @param array $options Additional options used during encoding
  54. * @return void
  55. */
  56. protected function __construct($cycleCheck = false, $options = array())
  57. {
  58. $this->_cycleCheck = $cycleCheck;
  59. $this->_options = $options;
  60. }
  61. /**
  62. * Use the JSON encoding scheme for the value specified
  63. *
  64. * @param mixed $value The value to be encoded
  65. * @param boolean $cycleCheck Whether or not to check for possible object recursion when encoding
  66. * @param array $options Additional options used during encoding
  67. * @return string The encoded value
  68. */
  69. public static function encode($value, $cycleCheck = false, $options = array())
  70. {
  71. $encoder = new self(($cycleCheck) ? true : false, $options);
  72. return $encoder->_encodeValue($value);
  73. }
  74. /**
  75. * Recursive driver which determines the type of value to be encoded
  76. * and then dispatches to the appropriate method. $values are either
  77. * - objects (returns from {@link _encodeObject()})
  78. * - arrays (returns from {@link _encodeArray()})
  79. * - basic datums (e.g. numbers or strings) (returns from {@link _encodeDatum()})
  80. *
  81. * @param $value mixed The value to be encoded
  82. * @return string Encoded value
  83. */
  84. protected function _encodeValue(&$value)
  85. {
  86. if (is_object($value)) {
  87. return $this->_encodeObject($value);
  88. } else if (is_array($value)) {
  89. return $this->_encodeArray($value);
  90. }
  91. return $this->_encodeDatum($value);
  92. }
  93. /**
  94. * Encode an object to JSON by encoding each of the public properties
  95. *
  96. * A special property is added to the JSON object called '__className'
  97. * that contains the name of the class of $value. This is used to decode
  98. * the object on the client into a specific class.
  99. *
  100. * @param $value object
  101. * @return string
  102. * @throws Zend_Json_Exception If recursive checks are enabled and the object has been serialized previously
  103. */
  104. protected function _encodeObject(&$value)
  105. {
  106. if ($this->_cycleCheck) {
  107. if ($this->_wasVisited($value)) {
  108. if (isset($this->_options['silenceCyclicalExceptions'])
  109. && $this->_options['silenceCyclicalExceptions']===true) {
  110. return '"* RECURSION (' . get_class($value) . ') *"';
  111. } else {
  112. #require_once 'Zend/Json/Exception.php';
  113. throw new Zend_Json_Exception(
  114. 'Cycles not supported in JSON encoding, cycle introduced by '
  115. . 'class "' . get_class($value) . '"'
  116. );
  117. }
  118. }
  119. $this->_visited[] = $value;
  120. }
  121. $props = '';
  122. if ($value instanceof Iterator) {
  123. $propCollection = $value;
  124. } else {
  125. $propCollection = get_object_vars($value);
  126. }
  127. foreach ($propCollection as $name => $propValue) {
  128. if (isset($propValue)) {
  129. $props .= ','
  130. . $this->_encodeString($name)
  131. . ':'
  132. . $this->_encodeValue($propValue);
  133. }
  134. }
  135. return '{"__className":"' . get_class($value) . '"'
  136. . $props . '}';
  137. }
  138. /**
  139. * Determine if an object has been serialized already
  140. *
  141. * @param mixed $value
  142. * @return boolean
  143. */
  144. protected function _wasVisited(&$value)
  145. {
  146. if (in_array($value, $this->_visited, true)) {
  147. return true;
  148. }
  149. return false;
  150. }
  151. /**
  152. * JSON encode an array value
  153. *
  154. * Recursively encodes each value of an array and returns a JSON encoded
  155. * array string.
  156. *
  157. * Arrays are defined as integer-indexed arrays starting at index 0, where
  158. * the last index is (count($array) -1); any deviation from that is
  159. * considered an associative array, and will be encoded as such.
  160. *
  161. * @param $array array
  162. * @return string
  163. */
  164. protected function _encodeArray(&$array)
  165. {
  166. $tmpArray = array();
  167. // Check for associative array
  168. if (!empty($array) && (array_keys($array) !== range(0, count($array) - 1))) {
  169. // Associative array
  170. $result = '{';
  171. foreach ($array as $key => $value) {
  172. $key = (string) $key;
  173. $tmpArray[] = $this->_encodeString($key)
  174. . ':'
  175. . $this->_encodeValue($value);
  176. }
  177. $result .= implode(',', $tmpArray);
  178. $result .= '}';
  179. } else {
  180. // Indexed array
  181. $result = '[';
  182. $length = count($array);
  183. for ($i = 0; $i < $length; $i++) {
  184. $tmpArray[] = $this->_encodeValue($array[$i]);
  185. }
  186. $result .= implode(',', $tmpArray);
  187. $result .= ']';
  188. }
  189. return $result;
  190. }
  191. /**
  192. * JSON encode a basic data type (string, number, boolean, null)
  193. *
  194. * If value type is not a string, number, boolean, or null, the string
  195. * 'null' is returned.
  196. *
  197. * @param $value mixed
  198. * @return string
  199. */
  200. protected function _encodeDatum(&$value)
  201. {
  202. $result = 'null';
  203. if (is_int($value) || is_float($value)) {
  204. $result = (string) $value;
  205. $result = str_replace(",", ".", $result);
  206. } elseif (is_string($value)) {
  207. $result = $this->_encodeString($value);
  208. } elseif (is_bool($value)) {
  209. $result = $value ? 'true' : 'false';
  210. }
  211. return $result;
  212. }
  213. /**
  214. * JSON encode a string value by escaping characters as necessary
  215. *
  216. * @param $value string
  217. * @return string
  218. */
  219. protected function _encodeString(&$string)
  220. {
  221. // Escape these characters with a backslash:
  222. // " \ / \n \r \t \b \f
  223. $search = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '/');
  224. $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"', '\\/');
  225. $string = str_replace($search, $replace, $string);
  226. // Escape certain ASCII characters:
  227. // 0x08 => \b
  228. // 0x0c => \f
  229. $string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
  230. $string = self::encodeUnicodeString($string);
  231. return '"' . $string . '"';
  232. }
  233. /**
  234. * Encode the constants associated with the ReflectionClass
  235. * parameter. The encoding format is based on the class2 format
  236. *
  237. * @param $cls ReflectionClass
  238. * @return string Encoded constant block in class2 format
  239. */
  240. private static function _encodeConstants(ReflectionClass $cls)
  241. {
  242. $result = "constants : {";
  243. $constants = $cls->getConstants();
  244. $tmpArray = array();
  245. if (!empty($constants)) {
  246. foreach ($constants as $key => $value) {
  247. $tmpArray[] = "$key: " . self::encode($value);
  248. }
  249. $result .= implode(', ', $tmpArray);
  250. }
  251. return $result . "}";
  252. }
  253. /**
  254. * Encode the public methods of the ReflectionClass in the
  255. * class2 format
  256. *
  257. * @param $cls ReflectionClass
  258. * @return string Encoded method fragment
  259. *
  260. */
  261. private static function _encodeMethods(ReflectionClass $cls)
  262. {
  263. $methods = $cls->getMethods();
  264. $result = 'methods:{';
  265. $started = false;
  266. foreach ($methods as $method) {
  267. if (! $method->isPublic() || !$method->isUserDefined()) {
  268. continue;
  269. }
  270. if ($started) {
  271. $result .= ',';
  272. }
  273. $started = true;
  274. $result .= '' . $method->getName(). ':function(';
  275. if ('__construct' != $method->getName()) {
  276. $parameters = $method->getParameters();
  277. $paramCount = count($parameters);
  278. $argsStarted = false;
  279. $argNames = "var argNames=[";
  280. foreach ($parameters as $param) {
  281. if ($argsStarted) {
  282. $result .= ',';
  283. }
  284. $result .= $param->getName();
  285. if ($argsStarted) {
  286. $argNames .= ',';
  287. }
  288. $argNames .= '"' . $param->getName() . '"';
  289. $argsStarted = true;
  290. }
  291. $argNames .= "];";
  292. $result .= "){"
  293. . $argNames
  294. . 'var result = ZAjaxEngine.invokeRemoteMethod('
  295. . "this, '" . $method->getName()
  296. . "',argNames,arguments);"
  297. . 'return(result);}';
  298. } else {
  299. $result .= "){}";
  300. }
  301. }
  302. return $result . "}";
  303. }
  304. /**
  305. * Encode the public properties of the ReflectionClass in the class2
  306. * format.
  307. *
  308. * @param $cls ReflectionClass
  309. * @return string Encode properties list
  310. *
  311. */
  312. private static function _encodeVariables(ReflectionClass $cls)
  313. {
  314. $properties = $cls->getProperties();
  315. $propValues = get_class_vars($cls->getName());
  316. $result = "variables:{";
  317. $cnt = 0;
  318. $tmpArray = array();
  319. foreach ($properties as $prop) {
  320. if (! $prop->isPublic()) {
  321. continue;
  322. }
  323. $tmpArray[] = $prop->getName()
  324. . ':'
  325. . self::encode($propValues[$prop->getName()]);
  326. }
  327. $result .= implode(',', $tmpArray);
  328. return $result . "}";
  329. }
  330. /**
  331. * Encodes the given $className into the class2 model of encoding PHP
  332. * classes into JavaScript class2 classes.
  333. * NOTE: Currently only public methods and variables are proxied onto
  334. * the client machine
  335. *
  336. * @param $className string The name of the class, the class must be
  337. * instantiable using a null constructor
  338. * @param $package string Optional package name appended to JavaScript
  339. * proxy class name
  340. * @return string The class2 (JavaScript) encoding of the class
  341. * @throws Zend_Json_Exception
  342. */
  343. public static function encodeClass($className, $package = '')
  344. {
  345. $cls = new ReflectionClass($className);
  346. if (! $cls->isInstantiable()) {
  347. #require_once 'Zend/Json/Exception.php';
  348. throw new Zend_Json_Exception("$className must be instantiable");
  349. }
  350. return "Class.create('$package$className',{"
  351. . self::_encodeConstants($cls) .","
  352. . self::_encodeMethods($cls) .","
  353. . self::_encodeVariables($cls) .'});';
  354. }
  355. /**
  356. * Encode several classes at once
  357. *
  358. * Returns JSON encoded classes, using {@link encodeClass()}.
  359. *
  360. * @param array $classNames
  361. * @param string $package
  362. * @return string
  363. */
  364. public static function encodeClasses(array $classNames, $package = '')
  365. {
  366. $result = '';
  367. foreach ($classNames as $className) {
  368. $result .= self::encodeClass($className, $package);
  369. }
  370. return $result;
  371. }
  372. /**
  373. * Encode Unicode Characters to \u0000 ASCII syntax.
  374. *
  375. * This algorithm was originally developed for the
  376. * Solar Framework by Paul M. Jones
  377. *
  378. * @link http://solarphp.com/
  379. * @link http://svn.solarphp.com/core/trunk/Solar/Json.php
  380. * @param string $value
  381. * @return string
  382. */
  383. public static function encodeUnicodeString($value)
  384. {
  385. $strlen_var = strlen($value);
  386. $ascii = "";
  387. /**
  388. * Iterate over every character in the string,
  389. * escaping with a slash or encoding to UTF-8 where necessary
  390. */
  391. for($i = 0; $i < $strlen_var; $i++) {
  392. $ord_var_c = ord($value[$i]);
  393. switch (true) {
  394. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  395. // characters U-00000000 - U-0000007F (same as ASCII)
  396. $ascii .= $value[$i];
  397. break;
  398. case (($ord_var_c & 0xE0) == 0xC0):
  399. // characters U-00000080 - U-000007FF, mask 110XXXXX
  400. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  401. $char = pack('C*', $ord_var_c, ord($value[$i + 1]));
  402. $i += 1;
  403. $utf16 = self::_utf82utf16($char);
  404. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  405. break;
  406. case (($ord_var_c & 0xF0) == 0xE0):
  407. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  408. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  409. $char = pack('C*', $ord_var_c,
  410. ord($value[$i + 1]),
  411. ord($value[$i + 2]));
  412. $i += 2;
  413. $utf16 = self::_utf82utf16($char);
  414. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  415. break;
  416. case (($ord_var_c & 0xF8) == 0xF0):
  417. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  418. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  419. $char = pack('C*', $ord_var_c,
  420. ord($value[$i + 1]),
  421. ord($value[$i + 2]),
  422. ord($value[$i + 3]));
  423. $i += 3;
  424. $utf16 = self::_utf82utf16($char);
  425. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  426. break;
  427. case (($ord_var_c & 0xFC) == 0xF8):
  428. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  429. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  430. $char = pack('C*', $ord_var_c,
  431. ord($value[$i + 1]),
  432. ord($value[$i + 2]),
  433. ord($value[$i + 3]),
  434. ord($value[$i + 4]));
  435. $i += 4;
  436. $utf16 = self::_utf82utf16($char);
  437. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  438. break;
  439. case (($ord_var_c & 0xFE) == 0xFC):
  440. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  441. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  442. $char = pack('C*', $ord_var_c,
  443. ord($value[$i + 1]),
  444. ord($value[$i + 2]),
  445. ord($value[$i + 3]),
  446. ord($value[$i + 4]),
  447. ord($value[$i + 5]));
  448. $i += 5;
  449. $utf16 = self::_utf82utf16($char);
  450. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  451. break;
  452. }
  453. }
  454. return $ascii;
  455. }
  456. /**
  457. * Convert a string from one UTF-8 char to one UTF-16 char.
  458. *
  459. * Normally should be handled by mb_convert_encoding, but
  460. * provides a slower PHP-only method for installations
  461. * that lack the multibye string extension.
  462. *
  463. * This method is from the Solar Framework by Paul M. Jones
  464. *
  465. * @link http://solarphp.com
  466. * @param string $utf8 UTF-8 character
  467. * @return string UTF-16 character
  468. */
  469. protected static function _utf82utf16($utf8)
  470. {
  471. // Check for mb extension otherwise do by hand.
  472. if( function_exists('mb_convert_encoding') ) {
  473. return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
  474. }
  475. switch (strlen($utf8)) {
  476. case 1:
  477. // this case should never be reached, because we are in ASCII range
  478. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  479. return $utf8;
  480. case 2:
  481. // return a UTF-16 character from a 2-byte UTF-8 char
  482. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  483. return chr(0x07 & (ord($utf8{0}) >> 2))
  484. . chr((0xC0 & (ord($utf8{0}) << 6))
  485. | (0x3F & ord($utf8{1})));
  486. case 3:
  487. // return a UTF-16 character from a 3-byte UTF-8 char
  488. // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  489. return chr((0xF0 & (ord($utf8{0}) << 4))
  490. | (0x0F & (ord($utf8{1}) >> 2)))
  491. . chr((0xC0 & (ord($utf8{1}) << 6))
  492. | (0x7F & ord($utf8{2})));
  493. }
  494. // ignoring UTF-32 for now, sorry
  495. return '';
  496. }
  497. }