Skip to content
This repository has been archived by the owner on Oct 3, 2023. It is now read-only.

Commit

Permalink
Allow to save unset and default values
Browse files Browse the repository at this point in the history
  • Loading branch information
Programie committed Jan 15, 2015
1 parent 9714dbd commit 0b31ae0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/php/com/selfcoders/jsonconfig/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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);
}
Expand Down
13 changes: 13 additions & 0 deletions src/test/php/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit 0b31ae0

Please sign in to comment.