From eff8ed0dbc7262cdecded3f06b08c3b364fbb201 Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Sat, 6 Aug 2011 13:28:28 -0400 Subject: [PATCH] Add OutputFilter::_EncodeXML and create a test --- http/output_filter.php | 22 ++++++++ testing/tests/http/output_filter_test.php | 67 +++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 testing/tests/http/output_filter_test.php diff --git a/http/output_filter.php b/http/output_filter.php index 2eeb0e5..f634b2b 100644 --- a/http/output_filter.php +++ b/http/output_filter.php @@ -81,4 +81,26 @@ class OutputFilter protected function _CreateBodyForResponse(Request $request, Response $response) {} + + /*! + Creates an XML tree from an array. Equivalent to json_encode. + */ + protected function _EncodeXML($data) + { + $response = new \SimpleXMLElement(''); + + $writer = function($elm, $parent) use (&$writer) { + foreach ($elm as $key => $value) { + if (is_scalar($value)) { + $parent->AddChild($key, $value); + } else { + $new_parent = $parent->AddChild($key); + $writer($value, $new_parent); + } + } + }; + + $writer($data, $response); + return $response->AsXML(); + } } diff --git a/testing/tests/http/output_filter_test.php b/testing/tests/http/output_filter_test.php new file mode 100644 index 0000000..b101e24 --- /dev/null +++ b/testing/tests/http/output_filter_test.php @@ -0,0 +1,67 @@ +. + +namespace hoplite\test; +use hoplite\http as http; + +require_once HOPLITE_ROOT . '/http/output_filter.php'; + +class TestOutputFilter extends http\OutputFilter +{ + public function T_EncodeXML($d) + { + return $this->_EncodeXML($d); + } +} + +class OutputFilterTest extends \PHPUnit_Framework_TestCase +{ + public function setUp() + { + $this->fixture = new TestOutputFilter(new http\RootController(array())); + } + + public function testEncodeXML() + { + $array = array( + 'test' => 1, + 'foo' => 'bar', + 'bar' => 'baz', + 'baz' => array( + 'poo' => 'moo', + 'moo' => 'baa' + ) + ); + $expected = << +1bar<strong>baz</strong>moobaa + +XML; + + $this->assertEquals($expected, $this->fixture->T_EncodeXML($array)); + + $obj = new \stdClass(); + $obj->int = 2; + $obj->obj = new \stdClass(); + $obj->obj->string = 'Foo'; + $expected = << +2Foo + +XML; + $this->assertEquals($expected, $this->fixture->T_EncodeXML($obj)); + } +} -- 2.43.5