JsonTest.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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. * @subpackage UnitTests
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Json
  24. */
  25. require_once 'Zend/Json.php';
  26. /**
  27. * @see Zend_Json_Expr
  28. */
  29. require_once 'Zend/Json/Expr.php';
  30. /**
  31. * @see Zend_Json_Encoder
  32. */
  33. require_once 'Zend/Json/Encoder.php';
  34. /**
  35. * @see Zend_Json_Decoder
  36. */
  37. require_once 'Zend/Json/Decoder.php';
  38. /**
  39. * @category Zend
  40. * @package Zend_Json
  41. * @subpackage UnitTests
  42. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  43. * @license http://framework.zend.com/license/new-bsd New BSD License
  44. * @group Zend_Json
  45. */
  46. class Zend_JsonTest extends PHPUnit_Framework_TestCase
  47. {
  48. private $_originalUseBuiltinEncoderDecoderValue;
  49. public function setUp()
  50. {
  51. $this->_originalUseBuiltinEncoderDecoderValue = Zend_Json::$useBuiltinEncoderDecoder;
  52. }
  53. public function tearDown()
  54. {
  55. Zend_Json::$useBuiltinEncoderDecoder = $this->_originalUseBuiltinEncoderDecoderValue;
  56. }
  57. public function testJsonWithPhpJsonExtension()
  58. {
  59. if (!extension_loaded('json')) {
  60. $this->markTestSkipped('JSON extension is not loaded');
  61. }
  62. Zend_Json::$useBuiltinEncoderDecoder = false;
  63. $this->_testJson(array('string', 327, true, null));
  64. }
  65. public function testJsonWithBuiltins()
  66. {
  67. Zend_Json::$useBuiltinEncoderDecoder = true;
  68. $this->_testJson(array('string', 327, true, null));
  69. }
  70. /**
  71. * Test encoding and decoding in a single step
  72. * @param array $values array of values to test against encode/decode
  73. */
  74. protected function _testJson($values)
  75. {
  76. $encoded = Zend_Json::encode($values);
  77. $this->assertEquals($values, Zend_Json::decode($encoded));
  78. }
  79. /**
  80. * test null encoding/decoding
  81. */
  82. public function testNull()
  83. {
  84. $this->_testEncodeDecode(array(null));
  85. }
  86. /**
  87. * test boolean encoding/decoding
  88. */
  89. public function testBoolean()
  90. {
  91. $this->assertTrue(Zend_Json_Decoder::decode(Zend_Json_Encoder::encode(true)));
  92. $this->assertFalse(Zend_Json_Decoder::decode(Zend_Json_Encoder::encode(false)));
  93. }
  94. /**
  95. * test integer encoding/decoding
  96. */
  97. public function testInteger()
  98. {
  99. $this->_testEncodeDecode(array(-2));
  100. $this->_testEncodeDecode(array(-1));
  101. $zero = Zend_Json_Decoder::decode(Zend_Json_Encoder::encode(0));
  102. $this->assertEquals(0, $zero, 'Failed 0 integer test. Encoded: ' . serialize(Zend_Json_Encoder::encode(0)));
  103. }
  104. /**
  105. * test float encoding/decoding
  106. */
  107. public function testFloat()
  108. {
  109. $this->_testEncodeDecode(array(-2.1, 1.2));
  110. }
  111. /**
  112. * test string encoding/decoding
  113. */
  114. public function testString()
  115. {
  116. $this->_testEncodeDecode(array('string'));
  117. $this->assertEquals('', Zend_Json_Decoder::decode(Zend_Json_Encoder::encode('')), 'Empty string encoded: ' . serialize(Zend_Json_Encoder::encode('')));
  118. }
  119. /**
  120. * Test backslash escaping of string
  121. */
  122. public function testString2()
  123. {
  124. $string = 'INFO: Path \\\\test\\123\\abc';
  125. $expected = '"INFO: Path \\\\\\\\test\\\\123\\\\abc"';
  126. $encoded = Zend_Json_Encoder::encode($string);
  127. $this->assertEquals($expected, $encoded, 'Backslash encoding incorrect: expected: ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n");
  128. $this->assertEquals($string, Zend_Json_Decoder::decode($encoded));
  129. }
  130. /**
  131. * Test newline escaping of string
  132. */
  133. public function testString3()
  134. {
  135. $expected = '"INFO: Path\nSome more"';
  136. $string = "INFO: Path\nSome more";
  137. $encoded = Zend_Json_Encoder::encode($string);
  138. $this->assertEquals($expected, $encoded, 'Newline encoding incorrect: expected ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n");
  139. $this->assertEquals($string, Zend_Json_Decoder::decode($encoded));
  140. }
  141. /**
  142. * Test tab/non-tab escaping of string
  143. */
  144. public function testString4()
  145. {
  146. $expected = '"INFO: Path\\t\\\\tSome more"';
  147. $string = "INFO: Path\t\\tSome more";
  148. $encoded = Zend_Json_Encoder::encode($string);
  149. $this->assertEquals($expected, $encoded, 'Tab encoding incorrect: expected ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n");
  150. $this->assertEquals($string, Zend_Json_Decoder::decode($encoded));
  151. }
  152. /**
  153. * Test double-quote escaping of string
  154. */
  155. public function testString5()
  156. {
  157. $expected = '"INFO: Path \"Some more\""';
  158. $string = 'INFO: Path "Some more"';
  159. $encoded = Zend_Json_Encoder::encode($string);
  160. $this->assertEquals($expected, $encoded, 'Quote encoding incorrect: expected ' . serialize($expected) . '; received: ' . serialize($encoded) . "\n");
  161. $this->assertEquals($string, Zend_Json_Decoder::decode($encoded));
  162. }
  163. /**
  164. * test indexed array encoding/decoding
  165. */
  166. public function testArray()
  167. {
  168. $array = array(1, 'one', 2, 'two');
  169. $encoded = Zend_Json_Encoder::encode($array);
  170. $this->assertSame($array, Zend_Json_Decoder::decode($encoded), 'Decoded array does not match: ' . serialize($encoded));
  171. }
  172. /**
  173. * test associative array encoding/decoding
  174. */
  175. public function testAssocArray()
  176. {
  177. $this->_testEncodeDecode(array(array('one' => 1, 'two' => 2)));
  178. }
  179. /**
  180. * test associative array encoding/decoding, with mixed key types
  181. */
  182. public function testAssocArray2()
  183. {
  184. $this->_testEncodeDecode(array(array('one' => 1, 2 => 2)));
  185. }
  186. /**
  187. * test associative array encoding/decoding, with integer keys not starting at 0
  188. */
  189. public function testAssocArray3()
  190. {
  191. $this->_testEncodeDecode(array(array(1 => 'one', 2 => 'two')));
  192. }
  193. /**
  194. * test object encoding/decoding (decoding to array)
  195. */
  196. public function testObject()
  197. {
  198. $value = new stdClass();
  199. $value->one = 1;
  200. $value->two = 2;
  201. $array = array('__className' => 'stdClass', 'one' => 1, 'two' => 2);
  202. $encoded = Zend_Json_Encoder::encode($value);
  203. $this->assertSame($array, Zend_Json_Decoder::decode($encoded));
  204. }
  205. /**
  206. * test object encoding/decoding (decoding to stdClass)
  207. */
  208. public function testObjectAsObject()
  209. {
  210. $value = new stdClass();
  211. $value->one = 1;
  212. $value->two = 2;
  213. $encoded = Zend_Json_Encoder::encode($value);
  214. $decoded = Zend_Json_Decoder::decode($encoded, Zend_Json::TYPE_OBJECT);
  215. $this->assertTrue(is_object($decoded), 'Not decoded as an object');
  216. $this->assertTrue($decoded instanceof StdClass, 'Not a StdClass object');
  217. $this->assertTrue(isset($decoded->one), 'Expected property not set');
  218. $this->assertEquals($value->one, $decoded->one, 'Unexpected value');
  219. }
  220. /**
  221. * Test that arrays of objects decode properly; see issue #144
  222. */
  223. public function testDecodeArrayOfObjects()
  224. {
  225. $value = '[{"id":1},{"foo":2}]';
  226. $expect = array(array('id' => 1), array('foo' => 2));
  227. $this->assertEquals($expect, Zend_Json_Decoder::decode($value));
  228. }
  229. /**
  230. * Test that objects of arrays decode properly; see issue #107
  231. */
  232. public function testDecodeObjectOfArrays()
  233. {
  234. $value = '{"codeDbVar" : {"age" : ["int", 5], "prenom" : ["varchar", 50]}, "234" : [22, "jb"], "346" : [64, "francois"], "21" : [12, "paul"]}';
  235. $expect = array(
  236. 'codeDbVar' => array(
  237. 'age' => array('int', 5),
  238. 'prenom' => array('varchar', 50),
  239. ),
  240. 234 => array(22, 'jb'),
  241. 346 => array(64, 'francois'),
  242. 21 => array(12, 'paul')
  243. );
  244. $this->assertEquals($expect, Zend_Json_Decoder::decode($value));
  245. }
  246. /**
  247. * Test encoding and decoding in a single step
  248. * @param array $values array of values to test against encode/decode
  249. */
  250. protected function _testEncodeDecode($values)
  251. {
  252. foreach ($values as $value) {
  253. $encoded = Zend_Json_Encoder::encode($value);
  254. $this->assertEquals($value, Zend_Json_Decoder::decode($encoded));
  255. }
  256. }
  257. /**
  258. * Test that version numbers such as 4.10 are encoded and decoded properly;
  259. * See ZF-377
  260. */
  261. public function testEncodeReleaseNumber()
  262. {
  263. $value = '4.10';
  264. $this->_testEncodeDecode(array($value));
  265. }
  266. /**
  267. * Tests that spaces/linebreaks prior to a closing right bracket don't throw
  268. * exceptions. See ZF-283.
  269. */
  270. public function testEarlyLineBreak()
  271. {
  272. $expected = array('data' => array(1, 2, 3, 4));
  273. $json = '{"data":[1,2,3,4' . "\n]}";
  274. $this->assertEquals($expected, Zend_Json_Decoder::decode($json));
  275. $json = '{"data":[1,2,3,4 ]}';
  276. $this->assertEquals($expected, Zend_Json_Decoder::decode($json));
  277. }
  278. /**
  279. * Tests for ZF-504
  280. *
  281. * Three confirmed issues reported:
  282. * - encoder improperly encoding empty arrays as structs
  283. * - decoder happily decoding clearly borked JSON
  284. * - decoder decoding octal values improperly (shouldn't decode them at all, as JSON does not support them)
  285. */
  286. public function testZf504()
  287. {
  288. $test = array();
  289. $this->assertSame('[]', Zend_Json_Encoder::encode($test));
  290. try {
  291. $json = '[a"],["a],[][]';
  292. $test = Zend_Json_Decoder::decode($json);
  293. $this->fail("Should not be able to decode '$json'");
  294. $json = '[a"],["a]';
  295. $test = Zend_Json_Decoder::decode($json);
  296. $this->fail("Should not be able to decode '$json'");
  297. } catch (Exception $e) {
  298. // success
  299. }
  300. try {
  301. $expected = 010;
  302. $test = Zend_Json_Decoder::decode('010');
  303. $this->fail('Octal values are not supported in JSON notation');
  304. } catch (Exception $e) {
  305. // sucess
  306. }
  307. }
  308. /**
  309. * Tests for ZF-461
  310. *
  311. * Check to see that cycling detection works properly
  312. */
  313. public function testZf461()
  314. {
  315. $item1 = new Zend_JsonTest_Item() ;
  316. $item2 = new Zend_JsonTest_Item() ;
  317. $everything = array() ;
  318. $everything['allItems'] = array($item1, $item2) ;
  319. $everything['currentItem'] = $item1 ;
  320. try {
  321. $encoded = Zend_Json_Encoder::encode($everything);
  322. } catch (Exception $e) {
  323. $this->fail('Object cycling checks should check for recursion, not duplicate usage of an item');
  324. }
  325. try {
  326. $encoded = Zend_Json_Encoder::encode($everything, true);
  327. $this->fail('Object cycling not allowed when cycleCheck parameter is true');
  328. } catch (Exception $e) {
  329. // success
  330. }
  331. }
  332. /**
  333. * Test for ZF-4053
  334. *
  335. * Check to see that cyclical exceptions are silenced when
  336. * $option['silenceCyclicalExceptions'] = true is used
  337. */
  338. public function testZf4053()
  339. {
  340. $item1 = new Zend_JsonTest_Item() ;
  341. $item2 = new Zend_JsonTest_Item() ;
  342. $everything = array() ;
  343. $everything['allItems'] = array($item1, $item2) ;
  344. $everything['currentItem'] = $item1 ;
  345. $options = array('silenceCyclicalExceptions'=>true);
  346. Zend_Json::$useBuiltinEncoderDecoder = true;
  347. $encoded = Zend_Json::encode($everything, true, $options);
  348. $json = '{"allItems":[{"__className":"Zend_JsonTest_Item"},{"__className":"Zend_JsonTest_Item"}],"currentItem":"* RECURSION (Zend_JsonTest_Item) *"}';
  349. $this->assertEquals($encoded,$json);
  350. }
  351. public function testEncodeObject()
  352. {
  353. $actual = new Zend_JsonTest_Object();
  354. $encoded = Zend_Json_Encoder::encode($actual);
  355. $decoded = Zend_Json_Decoder::decode($encoded, Zend_Json::TYPE_OBJECT);
  356. $this->assertTrue(isset($decoded->__className));
  357. $this->assertEquals('Zend_JsonTest_Object', $decoded->__className);
  358. $this->assertTrue(isset($decoded->foo));
  359. $this->assertEquals('bar', $decoded->foo);
  360. $this->assertTrue(isset($decoded->bar));
  361. $this->assertEquals('baz', $decoded->bar);
  362. $this->assertFalse(isset($decoded->_foo));
  363. }
  364. public function testEncodeClass()
  365. {
  366. $encoded = Zend_Json_Encoder::encodeClass('Zend_JsonTest_Object');
  367. $this->assertContains("Class.create('Zend_JsonTest_Object'", $encoded);
  368. $this->assertContains("ZAjaxEngine.invokeRemoteMethod(this, 'foo'", $encoded);
  369. $this->assertContains("ZAjaxEngine.invokeRemoteMethod(this, 'bar'", $encoded);
  370. $this->assertNotContains("ZAjaxEngine.invokeRemoteMethod(this, 'baz'", $encoded);
  371. $this->assertContains('variables:{foo:"bar",bar:"baz"}', $encoded);
  372. $this->assertContains('constants : {FOO: "bar"}', $encoded);
  373. }
  374. public function testEncodeClasses()
  375. {
  376. $encoded = Zend_Json_Encoder::encodeClasses(array('Zend_JsonTest_Object', 'Zend_JsonTest'));
  377. $this->assertContains("Class.create('Zend_JsonTest_Object'", $encoded);
  378. $this->assertContains("Class.create('Zend_JsonTest'", $encoded);
  379. }
  380. public function testToJsonSerialization()
  381. {
  382. $toJsonObject = new ToJsonClass();
  383. $result = Zend_Json::encode($toJsonObject);
  384. $this->assertEquals('{"firstName":"John","lastName":"Doe","email":"john@doe.com"}', $result);
  385. }
  386. /**
  387. * test encoding array with Zend_Json_Expr
  388. *
  389. * @group ZF-4946
  390. */
  391. public function testEncodingArrayWithExpr()
  392. {
  393. $expr = new Zend_Json_Expr('window.alert("Zend Json Expr")');
  394. $array = array('expr'=>$expr, 'int'=>9, 'string'=>'text');
  395. $result = Zend_Json::encode($array, false, array('enableJsonExprFinder' => true));
  396. $expected = '{"expr":window.alert("Zend Json Expr"),"int":9,"string":"text"}';
  397. $this->assertEquals($expected, $result);
  398. }
  399. /**
  400. * test encoding object with Zend_Json_Expr
  401. *
  402. * @group ZF-4946
  403. */
  404. public function testEncodingObjectWithExprAndInternalEncoder()
  405. {
  406. Zend_Json::$useBuiltinEncoderDecoder = true;
  407. $expr = new Zend_Json_Expr('window.alert("Zend Json Expr")');
  408. $obj = new stdClass();
  409. $obj->expr = $expr;
  410. $obj->int = 9;
  411. $obj->string = 'text';
  412. $result = Zend_Json::encode($obj, false, array('enableJsonExprFinder' => true));
  413. $expected = '{"__className":"stdClass","expr":window.alert("Zend Json Expr"),"int":9,"string":"text"}';
  414. $this->assertEquals($expected, $result);
  415. }
  416. /**
  417. * test encoding object with Zend_Json_Expr
  418. *
  419. * @group ZF-4946
  420. */
  421. public function testEncodingObjectWithExprAndExtJson()
  422. {
  423. if(!function_exists('json_encode')) {
  424. $this->markTestSkipped('Test only works with ext/json enabled!');
  425. }
  426. Zend_Json::$useBuiltinEncoderDecoder = false;
  427. $expr = new Zend_Json_Expr('window.alert("Zend Json Expr")');
  428. $obj = new stdClass();
  429. $obj->expr = $expr;
  430. $obj->int = 9;
  431. $obj->string = 'text';
  432. $result = Zend_Json::encode($obj, false, array('enableJsonExprFinder' => true));
  433. $expected = '{"expr":window.alert("Zend Json Expr"),"int":9,"string":"text"}';
  434. $this->assertEquals($expected, $result);
  435. }
  436. /**
  437. * test encoding object with ToJson and Zend_Json_Expr
  438. *
  439. * @group ZF-4946
  440. */
  441. public function testToJsonWithExpr()
  442. {
  443. Zend_Json::$useBuiltinEncoderDecoder = true;
  444. $obj = new Zend_Json_ToJsonWithExpr();
  445. $result = Zend_Json::encode($obj, false, array('enableJsonExprFinder' => true));
  446. $expected = '{"expr":window.alert("Zend Json Expr"),"int":9,"string":"text"}';
  447. $this->assertEquals($expected, $result);
  448. }
  449. /**
  450. * Regression tests for Zend_Json_Expr and mutliple keys with the same name.
  451. *
  452. * @group ZF-4946
  453. */
  454. public function testEncodingMultipleNestedSwitchingSameNameKeysWithDifferentJsonExprSettings()
  455. {
  456. $data = array(
  457. 0 => array(
  458. "alpha" => new Zend_Json_Expr("function(){}"),
  459. "beta" => "gamma",
  460. ),
  461. 1 => array(
  462. "alpha" => "gamma",
  463. "beta" => new Zend_Json_Expr("function(){}"),
  464. ),
  465. 2 => array(
  466. "alpha" => "gamma",
  467. "beta" => "gamma",
  468. )
  469. );
  470. $result = Zend_Json::encode($data, false, array('enableJsonExprFinder' => true));
  471. $this->assertEquals(
  472. '[{"alpha":function(){},"beta":"gamma"},{"alpha":"gamma","beta":function(){}},{"alpha":"gamma","beta":"gamma"}]',
  473. $result
  474. );
  475. }
  476. /**
  477. * Regression tests for Zend_Json_Expr and mutliple keys with the same name.
  478. *
  479. * @group ZF-4946
  480. */
  481. public function testEncodingMultipleNestedIteratedSameNameKeysWithDifferentJsonExprSettings()
  482. {
  483. $data = array(
  484. 0 => array(
  485. "alpha" => "alpha"
  486. ),
  487. 1 => array(
  488. "alpha" => "beta",
  489. ),
  490. 2 => array(
  491. "alpha" => new Zend_Json_Expr("gamma"),
  492. ),
  493. 3 => array(
  494. "alpha" => "delta",
  495. ),
  496. 4 => array(
  497. "alpha" => new Zend_Json_Expr("epsilon"),
  498. )
  499. );
  500. $result = Zend_Json::encode($data, false, array('enableJsonExprFinder' => true));
  501. $this->assertEquals('[{"alpha":"alpha"},{"alpha":"beta"},{"alpha":gamma},{"alpha":"delta"},{"alpha":epsilon}]', $result);
  502. }
  503. public function testDisabledJsonExprFinder()
  504. {
  505. Zend_Json::$useBuiltinEncoderDecoder = true;
  506. $data = array(
  507. 0 => array(
  508. "alpha" => new Zend_Json_Expr("function(){}"),
  509. "beta" => "gamma",
  510. ),
  511. );
  512. $result = Zend_Json::encode($data);
  513. $this->assertEquals(
  514. '[{"alpha":{"__className":"Zend_Json_Expr"},"beta":"gamma"}]',
  515. $result
  516. );
  517. }
  518. /**
  519. * @group ZF-4054
  520. */
  521. public function testEncodeWithUtf8IsTransformedToPackedSyntax()
  522. {
  523. $data = array("Отмена");
  524. $result = Zend_Json_Encoder::encode($data);
  525. $this->assertEquals('["\u041e\u0442\u043c\u0435\u043d\u0430"]', $result);
  526. }
  527. /**
  528. * @group ZF-4054
  529. *
  530. * This test contains assertions from the Solar Framework by Paul M. Jones
  531. * @link http://solarphp.com
  532. */
  533. public function testEncodeWithUtf8IsTransformedSolarRegression()
  534. {
  535. $expect = '"h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad"';
  536. $this->assertEquals($expect, Zend_Json_Encoder::encode('héllö wørłd'));
  537. $this->assertEquals('héllö wørłd', Zend_Json_Decoder::decode($expect));
  538. $expect = '"\u0440\u0443\u0441\u0441\u0438\u0448"';
  539. $this->assertEquals($expect, Zend_Json_Encoder::encode("руссиш"));
  540. $this->assertEquals("руссиш", Zend_Json_Decoder::decode($expect));
  541. }
  542. /**
  543. * @group ZF-4054
  544. */
  545. public function testEncodeUnicodeStringSolarRegression()
  546. {
  547. $value = 'héllö wørłd';
  548. $expected = 'h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad';
  549. $this->assertEquals($expected, Zend_Json_Encoder::encodeUnicodeString($value));
  550. $value = "\xC3\xA4";
  551. $expected = '\u00e4';
  552. $this->assertEquals($expected, Zend_Json_Encoder::encodeUnicodeString($value));
  553. $value = "\xE1\x82\xA0\xE1\x82\xA8";
  554. $expected = '\u10a0\u10a8';
  555. $this->assertEquals($expected, Zend_Json_Encoder::encodeUnicodeString($value));
  556. }
  557. /**
  558. * @group ZF-4054
  559. */
  560. public function testDecodeUnicodeStringSolarRegression()
  561. {
  562. $expected = 'héllö wørłd';
  563. $value = 'h\u00c3\u00a9ll\u00c3\u00b6 w\u00c3\u00b8r\u00c5\u201ad';
  564. $this->assertEquals($expected, Zend_Json_Decoder::decodeUnicodeString($value));
  565. $expected = "\xC3\xA4";
  566. $value = '\u00e4';
  567. $this->assertEquals($expected, Zend_Json_Decoder::decodeUnicodeString($value));
  568. $value = '\u10a0';
  569. $expected = "\xE1\x82\xA0";
  570. $this->assertEquals($expected, Zend_Json_Decoder::decodeUnicodeString($value));
  571. }
  572. /**
  573. * @group ZF-4054
  574. *
  575. * This test contains assertions from the Solar Framework by Paul M. Jones
  576. * @link http://solarphp.com
  577. */
  578. public function testEncodeWithUtf8IsTransformedSolarRegressionEqualsJsonExt()
  579. {
  580. if(function_exists('json_encode') == false) {
  581. $this->markTestSkipped('Test can only be run, when ext/json is installed.');
  582. }
  583. $this->assertEquals(
  584. json_encode('héllö wørłd'),
  585. Zend_Json_Encoder::encode('héllö wørłd')
  586. );
  587. $this->assertEquals(
  588. json_encode("руссиш"),
  589. Zend_Json_Encoder::encode("руссиш")
  590. );
  591. }
  592. /**
  593. * @group ZF-4946
  594. */
  595. public function testUtf8JsonExprFinder()
  596. {
  597. $data = array("Отмена" => new Zend_Json_Expr("foo"));
  598. Zend_Json::$useBuiltinEncoderDecoder = true;
  599. $result = Zend_Json::encode($data, false, array('enableJsonExprFinder' => true));
  600. $this->assertEquals('{"\u041e\u0442\u043c\u0435\u043d\u0430":foo}', $result);
  601. Zend_Json::$useBuiltinEncoderDecoder = false;
  602. $result = Zend_Json::encode($data, false, array('enableJsonExprFinder' => true));
  603. $this->assertEquals('{"\u041e\u0442\u043c\u0435\u043d\u0430":foo}', $result);
  604. }
  605. /**
  606. * @group ZF-4437
  607. */
  608. public function testKommaDecimalIsConvertedToCorrectJsonWithDot()
  609. {
  610. $localeInfo = localeconv();
  611. if($localeInfo['decimal_point'] != ",") {
  612. $this->markTestSkipped("This test only works for platforms where , is the decimal point separator.");
  613. }
  614. Zend_Json::$useBuiltinEncoderDecoder = true;
  615. $this->assertEquals("[1.20, 1.68]", Zend_Json_Encoder::encode(array(
  616. (float)"1,20", (float)"1,68"
  617. )));
  618. }
  619. public function testEncodeObjectImplementingIterator()
  620. {
  621. $this->markTestIncomplete('Test is not yet finished.');
  622. }
  623. /**
  624. * @group ZF-8663
  625. */
  626. public function testNativeJsonEncoderWillProperlyEncodeSolidusInStringValues()
  627. {
  628. $source = "</foo><foo>bar</foo>";
  629. $target = '"<\\/foo><foo>bar<\\/foo>"';
  630. // first test ext/json
  631. Zend_Json::$useBuiltinEncoderDecoder = false;
  632. $this->assertEquals($target, Zend_Json::encode($source));
  633. }
  634. /**
  635. * @group ZF-8663
  636. */
  637. public function testBuiltinJsonEncoderWillProperlyEncodeSolidusInStringValues()
  638. {
  639. $source = "</foo><foo>bar</foo>";
  640. $target = '"<\\/foo><foo>bar<\\/foo>"';
  641. // first test ext/json
  642. Zend_Json::$useBuiltinEncoderDecoder = true;
  643. $this->assertEquals($target, Zend_Json::encode($source));
  644. }
  645. /**
  646. * @group ZF-8918
  647. * @expectedException Zend_Json_Exception
  648. */
  649. public function testDecodingInvalidJsonShouldRaiseAnException()
  650. {
  651. Zend_Json::decode(' some string ');
  652. }
  653. /**
  654. * @group ZF-9416
  655. * Encoding an iterator using the internal encoder should handle undefined keys
  656. */
  657. public function testIteratorWithoutDefinedKey()
  658. {
  659. $inputValue = new ArrayIterator(array('foo'));
  660. $encoded = Zend_Json_Encoder::encode($inputValue);
  661. $expectedDecoding = '{"__className":"ArrayIterator","0":"foo"}';
  662. $this->assertEquals($encoded, $expectedDecoding);
  663. }
  664. /**
  665. * @group ZF-11356
  666. */
  667. public function testEncoderEscapesNamespacedClassNamesProperly()
  668. {
  669. if (version_compare(PHP_VERSION, '5.3.0') === -1) {
  670. $this->markTestSkipped('Namespaces not available in PHP < 5.3.0');
  671. }
  672. require_once dirname(__FILE__ ) . "/Json/_files/ZF11356-NamespacedClass.php";
  673. $inputValue = new \Zend\JsonTest\ZF11356\NamespacedClass(array('foo'));
  674. $encoded = Zend_Json_Encoder::encode($inputValue);
  675. $this->assertEquals(
  676. '{"__className":"Zend\\\\JsonTest\\\\ZF11356\\\\NamespacedClass","0":"foo"}',
  677. $encoded
  678. );
  679. }
  680. }
  681. /**
  682. * Zend_JsonTest_Item: test item for use with testZf461()
  683. */
  684. class Zend_JsonTest_Item
  685. {
  686. }
  687. /**
  688. * Zend_JsonTest_Object: test class for encoding classes
  689. */
  690. class Zend_JsonTest_Object
  691. {
  692. const FOO = 'bar';
  693. public $foo = 'bar';
  694. public $bar = 'baz';
  695. protected $_foo = 'fooled you';
  696. public function foo($bar, $baz)
  697. {
  698. }
  699. public function bar($baz)
  700. {
  701. }
  702. protected function baz()
  703. {
  704. }
  705. }
  706. class ToJsonClass
  707. {
  708. private $_firstName = 'John';
  709. private $_lastName = 'Doe';
  710. private $_email = 'john@doe.com';
  711. public function toJson()
  712. {
  713. $data = array(
  714. 'firstName' => $this->_firstName,
  715. 'lastName' => $this->_lastName,
  716. 'email' => $this->_email
  717. );
  718. return Zend_Json::encode($data);
  719. }
  720. }
  721. /**
  722. * ISSUE ZF-4946
  723. *
  724. */
  725. class Zend_Json_ToJsonWithExpr
  726. {
  727. private $_string = 'text';
  728. private $_int = 9;
  729. private $_expr = 'window.alert("Zend Json Expr")';
  730. public function toJson()
  731. {
  732. $data = array(
  733. 'expr' => new Zend_Json_Expr($this->_expr),
  734. 'int' => $this->_int,
  735. 'string' => $this->_string
  736. );
  737. return Zend_Json::encode($data, false, array('enableJsonExprFinder' => true));
  738. }
  739. }