diff --git a/src/main/php/com/selfcoders/jsonconfig/Config.php b/src/main/php/com/selfcoders/jsonconfig/Config.php index 4f254b0..a21846c 100644 --- a/src/main/php/com/selfcoders/jsonconfig/Config.php +++ b/src/main/php/com/selfcoders/jsonconfig/Config.php @@ -65,8 +65,9 @@ public function load($configFile = null) * * @param null|string $configFile An optional path to a JSON file to which the data should be written instead of the $configFile defined on instance creation * @param int $jsonOptions Optional options passed to json_encode (e.g. JSON_PRETTY_PRINT) + * @param bool $saveUnset Whether to also write unset and default values */ - public function save($configFile = null, $jsonOptions = 0) + public function save($configFile = null, $jsonOptions = 0, $saveUnset = false) { if ($configFile == null) { @@ -81,8 +82,16 @@ public function save($configFile = null, $jsonOptions = 0) { ValueByPath::setValueByPath($data, $name, $itemData->value, true); } + elseif ($saveUnset and isset($itemData->defaultValue)) + { + ValueByPath::setValueByPath($data, $name, $itemData->defaultValue, true); + } + elseif ($saveUnset) + { + ValueByPath::setValueByPath($data, $name, null, true); + } - if (isset($itemData->value) and isset($itemData->defaultValue) and $itemData->value == $itemData->defaultValue) + if (!$saveUnset and isset($itemData->value) and isset($itemData->defaultValue) and $itemData->value == $itemData->defaultValue) { ValueByPath::removeValueByPath($data, $name); } diff --git a/src/test/php/ConfigTest.php b/src/test/php/ConfigTest.php index 308e8bd..f01550b 100644 --- a/src/test/php/ConfigTest.php +++ b/src/test/php/ConfigTest.php @@ -117,4 +117,17 @@ public function testIsValueSet() $this->assertTrue($this->config->isValueSet("path.to.my.otherValue")); $this->assertFalse($this->config->isValueSet("path.to.unset.value")); } + + public function testSaveUnset() + { + $filename = tempnam(sys_get_temp_dir(), "cfg"); + + $this->config->save($filename, 0, true); + $json = json_decode(file_get_contents($filename)); + + $this->assertEquals("Set by template", $json->path->to->my->defaultValue); + $this->assertNull($json->path->to->unset->value); + + unlink($filename); + } } \ No newline at end of file