JsonEncoderTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Tests\Encoder;
  11. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  12. use Symfony\Component\Serializer\Serializer;
  13. use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
  14. class JsonEncoderTest extends \PHPUnit_Framework_TestCase
  15. {
  16. private $encoder;
  17. private $serializer;
  18. protected function setUp()
  19. {
  20. $this->encoder = new JsonEncoder();
  21. $this->serializer = new Serializer(array(new CustomNormalizer()), array('json' => new JsonEncoder()));
  22. }
  23. public function testEncodeScalar()
  24. {
  25. $obj = new \stdClass();
  26. $obj->foo = 'foo';
  27. $expected = '{"foo":"foo"}';
  28. $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
  29. }
  30. public function testComplexObject()
  31. {
  32. $obj = $this->getObject();
  33. $expected = $this->getJsonSource();
  34. $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
  35. }
  36. public function testOptions()
  37. {
  38. $context = array('json_encode_options' => JSON_NUMERIC_CHECK);
  39. $arr = array();
  40. $arr['foo'] = '3';
  41. $expected = '{"foo":3}';
  42. $this->assertEquals($expected, $this->serializer->serialize($arr, 'json', $context));
  43. $arr = array();
  44. $arr['foo'] = '3';
  45. $expected = '{"foo":"3"}';
  46. $this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent');
  47. }
  48. protected function getJsonSource()
  49. {
  50. return '{"foo":"foo","bar":["a","b"],"baz":{"key":"val","key2":"val","A B":"bar","item":[{"title":"title1"},{"title":"title2"}],"Barry":{"FooBar":{"Baz":"Ed","@id":1}}},"qux":"1"}';
  51. }
  52. protected function getObject()
  53. {
  54. $obj = new \stdClass();
  55. $obj->foo = 'foo';
  56. $obj->bar = array('a', 'b');
  57. $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => array(array('title' => 'title1'), array('title' => 'title2')), 'Barry' => array('FooBar' => array('Baz' => 'Ed', '@id' => 1)));
  58. $obj->qux = '1';
  59. return $obj;
  60. }
  61. }