XmlView: configure top level element name #934

Closed
wants to merge 5 commits into
from
@@ -64,6 +64,13 @@ public function testRenderWithoutView() {
$expected = Xml::build(array('response' => array('users' => $data)))->asXML();
$this->assertSame($expected, $output);
+
+ $Controller->set('_rootNode', 'custom_name');
@markstory

markstory Nov 2, 2012

Owner

Little nitpick, you should only have 1 newline here.

@ADmad

ADmad Nov 2, 2012

Member

Better not give the code sniffer reasons to complain 😄

+ $View = new XmlView($Controller);
+ $output = $View->render(false);
+
+ $expected = Xml::build(array('custom_name' => array('users' => $data)))->asXML();
+ $this->assertSame($expected, $output);
}
/**
@@ -79,13 +86,20 @@ public function testRenderWithoutViewMultiple() {
$Controller->set($data);
$Controller->set('_serialize', array('no', 'user'));
$View = new XmlView($Controller);
+ $this->assertSame('application/xml', $Response->type());
$output = $View->render(false);
-
$expected = array(
'response' => array('no' => $data['no'], 'user' => $data['user'])
);
$this->assertSame(Xml::build($expected)->asXML(), $output);
- $this->assertSame('application/xml', $Response->type());
+
+ $Controller->set('_rootNode', 'custom_name');
@markstory

markstory Nov 2, 2012

Owner

Little nitpick, you should only have 1 newline here.

+ $View = new XmlView($Controller);
+ $output = $View->render(false);
+ $expected = array(
+ 'custom_name' => array('no' => $data['no'], 'user' => $data['user'])
+ );
+ $this->assertSame(Xml::build($expected)->asXML(), $output);
}
/**
@@ -99,15 +99,17 @@ public function render($view = null, $layout = null) {
* @return string The serialized data
*/
protected function _serialize($serialize) {
+ $rootNode = isset($this->viewVars['_rootNode']) ? $this->viewVars['_rootNode'] : 'response';
+
if (is_array($serialize)) {
- $data = array('response' => array());
+ $data = array($rootNode => array());
foreach ($serialize as $key) {
- $data['response'][$key] = $this->viewVars[$key];
+ $data[$rootNode][$key] = $this->viewVars[$key];
}
} else {
$data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
if (is_array($data) && Set::numeric(array_keys($data))) {
- $data = array('response' => array($serialize => $data));
+ $data = array($rootNode => array($serialize => $data));
}
}
return Xml::fromArray($data)->asXML();