Browse Source

Normalize json across all php versions, fixes #3226

Jordi Boggiano 10 years ago
parent
commit
109f4ffd5e

+ 9 - 1
src/Composer/Json/JsonFile.php

@@ -184,7 +184,15 @@ class JsonFile
     public static function encode($data, $options = 448)
     {
         if (version_compare(PHP_VERSION, '5.4', '>=')) {
-            return json_encode($data, $options);
+            $json = json_encode($data, $options);
+
+            //  compact brackets to follow recent php versions
+            if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512)) {
+               $json = preg_replace('/\[\s+\]/', '[]', $json);
+               $json = preg_replace('/\{\s+\}/', '{}', $json);
+            }
+
+            return $json;
         }
 
         $json = json_encode($data);

+ 1 - 1
src/Composer/Json/JsonFormatter.php

@@ -102,7 +102,7 @@ class JsonFormatter
                     }
                 } else {
                     // Collapse empty {} and []
-                    $result = rtrim($result)."\n\n".$indentStr;
+                    $result = rtrim($result);
                 }
             }
 

+ 1 - 12
tests/Composer/Test/Json/JsonFileTest.php

@@ -131,21 +131,10 @@ class JsonFileTest extends \PHPUnit_Framework_TestCase
     public function testFormatEmptyArray()
     {
         $data = array('test' => array(), 'test2' => new \stdClass);
-        if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512)) {
-            $json = '{
-    "test": [
-
-    ],
-    "test2": {
-
-    }
-}';
-        } else {
-            $json = '{
+        $json = '{
     "test": [],
     "test2": {}
 }';
-        }
         $this->assertJsonFormat($json, $data);
     }