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

Commit 0b31ae0

Browse files
committed
Allow to save unset and default values
1 parent 9714dbd commit 0b31ae0

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

src/main/php/com/selfcoders/jsonconfig/Config.php

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,9 @@ public function load($configFile = null)
6565
*
6666
* @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
6767
* @param int $jsonOptions Optional options passed to json_encode (e.g. JSON_PRETTY_PRINT)
68+
* @param bool $saveUnset Whether to also write unset and default values
6869
*/
69-
public function save($configFile = null, $jsonOptions = 0)
70+
public function save($configFile = null, $jsonOptions = 0, $saveUnset = false)
7071
{
7172
if ($configFile == null)
7273
{
@@ -81,8 +82,16 @@ public function save($configFile = null, $jsonOptions = 0)
8182
{
8283
ValueByPath::setValueByPath($data, $name, $itemData->value, true);
8384
}
85+
elseif ($saveUnset and isset($itemData->defaultValue))
86+
{
87+
ValueByPath::setValueByPath($data, $name, $itemData->defaultValue, true);
88+
}
89+
elseif ($saveUnset)
90+
{
91+
ValueByPath::setValueByPath($data, $name, null, true);
92+
}
8493

85-
if (isset($itemData->value) and isset($itemData->defaultValue) and $itemData->value == $itemData->defaultValue)
94+
if (!$saveUnset and isset($itemData->value) and isset($itemData->defaultValue) and $itemData->value == $itemData->defaultValue)
8695
{
8796
ValueByPath::removeValueByPath($data, $name);
8897
}

src/test/php/ConfigTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,17 @@ public function testIsValueSet()
117117
$this->assertTrue($this->config->isValueSet("path.to.my.otherValue"));
118118
$this->assertFalse($this->config->isValueSet("path.to.unset.value"));
119119
}
120+
121+
public function testSaveUnset()
122+
{
123+
$filename = tempnam(sys_get_temp_dir(), "cfg");
124+
125+
$this->config->save($filename, 0, true);
126+
$json = json_decode(file_get_contents($filename));
127+
128+
$this->assertEquals("Set by template", $json->path->to->my->defaultValue);
129+
$this->assertNull($json->path->to->unset->value);
130+
131+
unlink($filename);
132+
}
120133
}

0 commit comments

Comments
 (0)