[Serializer] Added XML attributes support for DomDocument in XmlEncoder.

This is a combination of 2 commits.

- [Serializer] Added encoding support for DomDocument in XmlEncoder

- [Serializer] Refactor code to allow setting <?xml standalone ?>

This commit refactors the createDomDocument(..) method in XmlEncoder
so
it can set the 'version', 'encoding' and 'standalone' attributes on
the
DOM document.

Code coverage of new code: 100%. Tests: pass.
This commit is contained in:
raul782 2013-07-05 03:06:42 -05:00 committed by Stan Angeloff
parent 76b6449c16
commit 21218cca44
2 changed files with 46 additions and 1 deletions

View File

@ -47,7 +47,7 @@ class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, Dec
$xmlRootNodeName = $this->resolveXmlRootName($context);
$this->dom = new \DOMDocument();
$this->dom = $this->createDomDocument($context);
$this->format = $format;
if (null !== $data && !is_scalar($data)) {
@ -426,4 +426,32 @@ class XmlEncoder extends SerializerAwareEncoder implements EncoderInterface, Dec
: $this->rootNodeName;
}
/**
* Create a DOM document, taking serializer options into account.
*
* @param array $context options that the encoder has access to.
*
* @return \DOMDocument
*/
private function createDomDocument(array $context)
{
$document = new \DOMDocument();
// Set an attribute on the DOM document specifying, as part of the XML declaration,
$xmlOptions = array(
// the version number of the document
'xml_version' => 'xmlVersion',
// the encoding of the document
'xml_encoding' => 'encoding',
// whether the document is standalone
'xml_standalone' => 'xmlStandalone',
);
foreach ($xmlOptions as $xmlOption => $documentProperty) {
if (isset($context[$xmlOption])) {
$document->$documentProperty = $context[$xmlOption];
}
}
return $document;
}
}

View File

@ -118,6 +118,23 @@ class XmlEncoderTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testEncodeXmlAttributes()
{
$xml = simplexml_load_string('<firstname>Peter</firstname>');
$array = array('person' => $xml);
$expected = '<?xml version="1.1" encoding="utf-8" standalone="yes"?>'."\n".
'<response><person><firstname>Peter</firstname></person></response>'."\n";
$context = array(
'xml_version' => '1.1',
'xml_encoding' => 'utf-8',
'xml_standalone' => true,
);
$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}
public function testEncodeScalarRootAttributes()
{
$array = array(