diff --git a/src/Spyc.php b/src/Spyc.php index d1a065e..19d57d7 100644 --- a/src/Spyc.php +++ b/src/Spyc.php @@ -211,7 +211,11 @@ public function dump($array,$indent = false,$wordwrap = false, $no_opening_dashe if (!$no_opening_dashes) $string = "---\n"; // Start at the base of the array and move through it. - if ($array) { + // Note: We avoid a loose `if ($array)` check because it would treat falsey scalars + // (e.g., 0, "0", false) as empty input and skip dumping them, even though they are + // valid values. Non-empty arrays are always truthy in PHP regardless of contents, + // so this guard is about distinguishing "no data" (null, "", empty array) from real values. + if ($array !== null && $array !== '' && (!is_array($array) || count($array) > 0)) { $array = (array)$array; $previous_key = -1; foreach ($array as $key => $value) { @@ -234,7 +238,9 @@ public function dump($array,$indent = false,$wordwrap = false, $no_opening_dashe private function _yamlize($key,$value,$indent, $previous_key = -1, $first_key = 0, $source_array = null) { if(is_object($value)) $value = (array)$value; if (is_array($value)) { - if (empty ($value)) + // Since $value is already an array, empty($value) and count($value) === 0 are equivalent. + // We use count($value) === 0 here for explicitness and consistency with the logic in dump(). + if (count($value) === 0) return $this->_dumpNode($key, array(), $indent, $previous_key, $first_key, $source_array); // It has children. What to do? // Make it the right kind of item diff --git a/tests/DumpTest.php b/tests/DumpTest.php index ac7774f..febbb71 100644 --- a/tests/DumpTest.php +++ b/tests/DumpTest.php @@ -193,4 +193,43 @@ public function testPerCentAndDoubleQuote() { $this->assertEquals ($awaiting, $dump); } + /** + * Test that integer zero values are correctly dumped. + * This is a regression test for the issue where empty(0) returns true in PHP, + * causing zero values to be incorrectly treated as empty. + */ + public function testDumpIntegerZero() { + $dump = Spyc::YAMLDump(array(0)); + $awaiting = "---\n- 0\n"; + $this->assertEquals($awaiting, $dump); + } + + /** + * Test that string zero values are correctly dumped. + * This is a regression test for the issue where empty("0") returns true in PHP. + */ + public function testDumpStringZero() { + $dump = Spyc::YAMLDump(array('0')); + $awaiting = "---\n- \"0\"\n"; + $this->assertEquals($awaiting, $dump); + } + + /** + * Test that associative arrays with zero values are correctly dumped. + */ + public function testDumpAssociativeZero() { + $dump = Spyc::YAMLDump(array('key' => 0)); + $awaiting = "---\nkey: 0\n"; + $this->assertEquals($awaiting, $dump); + } + + /** + * Test that mixed arrays containing zero values are correctly dumped. + */ + public function testDumpMixedWithZero() { + $dump = Spyc::YAMLDump(array(1, 0, 2)); + $awaiting = "---\n- 1\n- 0\n- 2\n"; + $this->assertEquals($awaiting, $dump); + } + }