XmlEncoderTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Symfony\Tests\Component\Serializer\Encoder;
  3. require_once __DIR__.'/../Fixtures/Dummy.php';
  4. require_once __DIR__.'/../Fixtures/ScalarDummy.php';
  5. use Symfony\Tests\Component\Serializer\Fixtures\Dummy;
  6. use Symfony\Tests\Component\Serializer\Fixtures\ScalarDummy;
  7. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  8. use Symfony\Component\Serializer\Serializer;
  9. use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
  10. /*
  11. * This file is part of the Symfony framework.
  12. *
  13. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  14. *
  15. * This source file is subject to the MIT license that is bundled
  16. * with this source code in the file LICENSE.
  17. */
  18. class XmlEncoderTest extends \PHPUnit_Framework_TestCase
  19. {
  20. public function setUp()
  21. {
  22. $serializer = new Serializer;
  23. $this->encoder = new XmlEncoder;
  24. $serializer->setEncoder('xml', $this->encoder);
  25. $serializer->addNormalizer(new CustomNormalizer);
  26. }
  27. public function testEncodeScalar()
  28. {
  29. $obj = new ScalarDummy;
  30. $obj->xmlFoo = "foo";
  31. $expected = '<?xml version="1.0"?>'."\n".
  32. '<response><![CDATA[foo]]></response>'."\n";
  33. $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
  34. }
  35. public function testDecodeScalar()
  36. {
  37. $source = '<?xml version="1.0"?>'."\n".
  38. '<response>foo</response>'."\n";
  39. $this->assertEquals('foo', $this->encoder->decode($source, 'xml'));
  40. }
  41. public function testEncode()
  42. {
  43. $source = $this->getXmlSource();
  44. $obj = $this->getObject();
  45. $this->assertEquals($source, $this->encoder->encode($obj, 'xml'));
  46. }
  47. public function testDecode()
  48. {
  49. $source = $this->getXmlSource();
  50. $obj = $this->getObject();
  51. $this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml'));
  52. }
  53. protected function getXmlSource()
  54. {
  55. return '<?xml version="1.0"?>'."\n".
  56. '<response>'.
  57. '<foo><![CDATA[foo]]></foo>'.
  58. '<bar><item key="0"><![CDATA[a]]></item><item key="1"><![CDATA[b]]></item></bar>'.
  59. '<baz><key><![CDATA[val]]></key><key2><![CDATA[val]]></key2><item key="A B"><![CDATA[bar]]></item></baz>'.
  60. '<qux>1</qux>'.
  61. '</response>'."\n";
  62. }
  63. protected function getObject()
  64. {
  65. $obj = new Dummy;
  66. $obj->foo = 'foo';
  67. $obj->bar = array('a', 'b');
  68. $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar');
  69. $obj->qux = "1";
  70. return $obj;
  71. }
  72. }