소스 검색

[Serializer] Added XmlEncoder::setRootNodeName

Jordi Boggiano 14 년 전
부모
커밋
8216a6ef3d
2개의 변경된 파일34개의 추가작업 그리고 3개의 파일을 삭제
  1. 22 3
      src/Symfony/Component/Serializer/Encoder/XmlEncoder.php
  2. 12 0
      tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php

+ 22 - 3
src/Symfony/Component/Serializer/Encoder/XmlEncoder.php

@@ -24,6 +24,7 @@ class XmlEncoder extends AbstractEncoder
 {
     protected $dom;
     protected $format;
+    protected $rootNodeName = 'response';
 
     /**
      * {@inheritdoc}
@@ -38,11 +39,11 @@ class XmlEncoder extends AbstractEncoder
         $this->format = $format;
 
         if ($this->serializer->isStructuredType($data)) {
-            $root = $this->dom->createElement('response');
+            $root = $this->dom->createElement($this->rootNodeName);
             $this->dom->appendChild($root);
             $this->buildXml($root, $data);
         } else {
-            $this->appendNode($this->dom, $data, 'response');
+            $this->appendNode($this->dom, $data, $this->rootNodeName);
         }
         return $this->dom->saveXML();
     }
@@ -59,6 +60,24 @@ class XmlEncoder extends AbstractEncoder
         return $this->parseXml($xml);
     }
 
+    /**
+     * Sets the root node name
+     * @param string $name root node name
+     */
+    public function setRootNodeName($name)
+    {
+        $this->rootNodeName = $name;
+    }
+
+    /**
+     * Returns the root node name
+     * @return string
+     */
+    public function getRootNodeName()
+    {
+        return $this->rootNodeName;
+    }
+
     /**
      * Parse the input SimpleXmlElement into an array
      *
@@ -120,7 +139,7 @@ class XmlEncoder extends AbstractEncoder
                 if (!$parentNode->parentNode->parentNode) {
                     $root = $parentNode->parentNode;
                     $root->removeChild($parentNode);
-                    return $this->appendNode($root, $data, 'response');
+                    return $this->appendNode($root, $data, $this->rootNodeName);
                 }
                 return $this->appendNode($parentNode, $data, 'data');
             }

+ 12 - 0
tests/Symfony/Tests/Component/Serializer/Encoder/XmlEncoderTest.php

@@ -41,6 +41,18 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
     }
 
+    public function testSetRootNodeName()
+    {
+        $obj = new ScalarDummy;
+        $obj->xmlFoo = "foo";
+
+        $this->encoder->setRootNodeName('test');
+        $expected = '<?xml version="1.0"?>'."\n".
+            '<test><![CDATA[foo]]></test>'."\n";
+
+        $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
+    }
+
     public function testEncodeSimpleXML()
     {
         $xml = simplexml_load_string('<firstname>Peter</firstname>');