Skip to content

Commit e3dbac2

Browse files
author
Nathan Macnamara
committed
Merge pull request #9 from nathanmac/fix/xml-empty-values
Fix for xml empty values, should return null.
2 parents b8f225c + 569cf2e commit e3dbac2

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Formats/XML.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,12 @@ public function parse($payload)
2828
{
2929
try {
3030
$xml = simplexml_load_string($payload, 'SimpleXMLElement', LIBXML_NOCDATA);
31-
return json_decode(json_encode((array) $xml), 1); // Work around to accept xml input
31+
32+
// Fix for empty values in XML
33+
$json = json_encode((array) $xml);
34+
$json = str_replace(':{}',':null', $json);
35+
$json = str_replace(':[]',':null', $json);
36+
return json_decode($json, 1); // Work around to accept xml input
3237
} catch (\Exception $ex) {
3338
throw new ParserException('Failed To Parse XML');
3439
}

tests/XMLTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,20 @@ protected function tearDown()
1515
m::close();
1616
}
1717

18+
/** @test */
19+
public function null_values_for_empty_values()
20+
{
21+
$parser = m::mock('Nathanmac\Utilities\Parser\Parser')
22+
->shouldDeferMissing()
23+
->shouldAllowMockingProtectedMethods();
24+
25+
$parser->shouldReceive('getPayload')
26+
->once()
27+
->andReturn('<xml><comments><title></title><message>hello world</message></comments><comments><title>world</title><message></message></comments></xml>');
28+
29+
$this->assertEquals(array("comments" => array(array("title" => null, "message" => "hello world"), array("title" => "world", "message" => null))), $parser->payload('application/xml'));
30+
}
31+
1832
/** @test */
1933
public function array_structured_getPayload_xml()
2034
{

0 commit comments

Comments
 (0)