Browse Source

Fix subkey manipulation when the main key does not exist yet

Jordi Boggiano 10 years ago
parent
commit
32a479a1e7

+ 10 - 6
src/Composer/Json/JsonManipulator.php

@@ -126,18 +126,22 @@ class JsonManipulator
     {
         $decoded = JsonFile::parseJson($this->contents);
 
+        $subName = null;
+        if (in_array($mainNode, array('config', 'repositories')) && false !== strpos($name, '.')) {
+            list($name, $subName) = explode('.', $name, 2);
+        }
+
         // no main node yet
         if (!isset($decoded[$mainNode])) {
-            $this->addMainKey($mainNode, array($name => $value));
+            if ($subName !== null) {
+                $this->addMainKey($mainNode, array($name => array($subName => $value)));
+            } else {
+                $this->addMainKey($mainNode, array($name => $value));
+            }
 
             return true;
         }
 
-        $subName = null;
-        if (in_array($mainNode, array('config', 'repositories')) && false !== strpos($name, '.')) {
-            list($name, $subName) = explode('.', $name, 2);
-        }
-
         // main node content not match-able
         $nodeRegex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
             '('.preg_quote(JsonFile::encode($mainNode)).'\s*:\s*\{)('.self::$RECURSE_BLOCKS.')(\})(.*)}s';

+ 16 - 0
tests/Composer/Test/Json/JsonManipulatorTest.php

@@ -803,6 +803,22 @@ class JsonManipulatorTest extends \PHPUnit_Framework_TestCase
 ', $manipulator->getContents());
     }
 
+    public function testAddConfigSettingWorksFromScratch()
+    {
+        $manipulator = new JsonManipulator('{
+}');
+
+        $this->assertTrue($manipulator->addConfigSetting('foo.bar', 'baz'));
+        $this->assertEquals('{
+    "config": {
+        "foo": {
+            "bar": "baz"
+        }
+    }
+}
+', $manipulator->getContents());
+    }
+
     public function testAddConfigSettingCanAdd()
     {
         $manipulator = new JsonManipulator('{