PageRenderTime 61ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Zend/Json/Encoder.php

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