* @since 2.0
*
* @group web
*/
class XmlResponseFormatterTest extends FormatterTest
{
/**
* @param array $options
* @return XmlResponseFormatter
*/
protected function getFormatterInstance($options = [])
{
return new XmlResponseFormatter($options);
}
private $xmlHead = "\n";
private function addXmlHead(array $data)
{
foreach ($data as &$item) {
$item[1] = $this->xmlHead . $item[1];
}
return $data;
}
public function formatScalarDataProvider()
{
return $this->addXmlHead([
[1, "1\n"],
['abc', "abc\n"],
[true, "true\n"],
[false, "false\n"],
["<>", "<>\n"],
]);
}
public function formatArrayDataProvider()
{
return $this->addXmlHead([
[[], "\n"],
[[1, 'abc'], "- 1
- abc
\n"],
[[
'a' => 1,
'b' => 'abc',
], "1abc\n"],
[[
1,
'abc',
[2, 'def'],
true,
], "- 1
- abc
- 2
- def
- true
\n"],
[[
'a' => 1,
'b' => 'abc',
'c' => [2, '<>'],
false,
], "1abc- 2
- <>
- false
\n"],
// Checks if empty keys and keys not valid in XML are processed.
// See https://github.com/yiisoft/yii2/pull/10346/
[[
'' => 1,
'2015-06-18' => '2015-06-18',
'b:c' => 'b:c',
'a b c' => 'a b c',
'äøñ' => 'äøñ'
], "- 1
- 2015-06-18
- b:c
- a b c
<äøñ>äøñäøñ>\n"],
]);
}
public function formatTraversableObjectDataProvider()
{
$expectedXmlForStack = '';
$postsStack = new \SplStack();
$postsStack->push(new Post(915, 'record1'));
$expectedXmlForStack = '915record1' .
$expectedXmlForStack;
$postsStack->push(new Post(456, 'record2'));
$expectedXmlForStack = '456record2' .
$expectedXmlForStack;
$data = [
[$postsStack, "$expectedXmlForStack\n"]
];
return $this->addXmlHead($data);
}
public function formatObjectDataProvider()
{
return $this->addXmlHead([
[new Post(123, 'abc'), "123abc\n"],
[[
new Post(123, 'abc'),
new Post(456, 'def'),
], "123abc456def\n"],
[[
new Post(123, '<>'),
'a' => new Post(456, 'def'),
], "123<>456def\n"],
]);
}
public function formatModelDataProvider()
{
return $this->addXmlHead([
[
new ModelStub(['id' => 123, 'title' => 'abc', 'hidden' => 'hidden']),
"123abc\n"
]
]);
}
public function testCustomRootTag()
{
$rootTag = 'custom';
$formatter = $this->getFormatterInstance([
'rootTag' => $rootTag,
]);
$this->response->data = 1;
$formatter->format($this->response);
$this->assertEquals($this->xmlHead . "<$rootTag>1$rootTag>\n", $this->response->content);
}
public function testRootTagRemoval()
{
$formatter = $this->getFormatterInstance([
'rootTag' => null,
]);
$this->response->data = 1;
$formatter->format($this->response);
$this->assertEquals($this->xmlHead . "1\n", $this->response->content);
}
public function testNoObjectTags()
{
$formatter = $this->getFormatterInstance([
'useObjectTags' => false,
]);
$this->response->data = new Post(123, 'abc');
$formatter->format($this->response);
$this->assertEquals($this->xmlHead . "123abc\n", $this->response->content);
}
}