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

/library/Zend/Json/Encoder.php

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