[Serializer] Added XmlEncoder::setRootNodeName
This commit is contained in:
parent
cf5cfb0b51
commit
8216a6ef3d
|
@ -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');
|
||||
}
|
||||
|
|
|
@ -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>');
|
||||
|
|
Reference in New Issue