From 80751105b59881bb7b5742569fff2da68e7f7920 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Mon, 16 Nov 2026 12:07:34 +0000 Subject: [PATCH] Avoid unnecessary quotes when writing INI values --- composer.json | 3 +- composer.lock | 55 +------------------- src/FileWriter.php | 64 ++++++++++++++++++------ test/phpunit/FileWriterConfigTest.php | 72 ++++++++++++++++++++++++++- test/phpunit/GeneratorConfigTest.php | 2 +- 5 files changed, 123 insertions(+), 73 deletions(-) diff --git a/composer.json b/composer.json index eb94cf8..7314b06 100644 --- a/composer.json +++ b/composer.json @@ -5,8 +5,7 @@ "require": { "php": ">=8.3", - "phpgt/typesafegetter": "^1.3", - "magicalex/write-ini-file": "v1.2.4" + "phpgt/typesafegetter": "^1.3" }, "require-dev": { "phpstan/phpstan": "^2.1", diff --git a/composer.lock b/composer.lock index d6c0de9..e70705c 100644 --- a/composer.lock +++ b/composer.lock @@ -4,59 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "f586bf5aa84291803b3f1e9b77c0faf1", + "content-hash": "f6968fcd0ea3b252ed03c4da4992132a", "packages": [ - { - "name": "magicalex/write-ini-file", - "version": "v1.2.4", - "source": { - "type": "git", - "url": "https://github.com/Magicalex/WriteiniFile.git", - "reference": "3a933e8222ed2b0ff724c2d4278666fa257e42ac" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Magicalex/WriteiniFile/zipball/3a933e8222ed2b0ff724c2d4278666fa257e42ac", - "reference": "3a933e8222ed2b0ff724c2d4278666fa257e42ac", - "shasum": "" - }, - "require": { - "php": ">=5.6.0" - }, - "require-dev": { - "php-coveralls/php-coveralls": "2.1.0", - "phpunit/phpunit": "5.7.*" - }, - "type": "library", - "autoload": { - "psr-4": { - "WriteiniFile\\": "src" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "GPL-3.0" - ], - "authors": [ - { - "name": "magicalex", - "email": "magicalex@mondedie.fr" - } - ], - "description": "Write-ini-file php library for create, remove, erase, add, and update ini file", - "homepage": "https://github.com/Magicalex/WriteIniFile", - "keywords": [ - "file", - "ini", - "write", - "write_ini_file" - ], - "support": { - "issues": "https://github.com/Magicalex/WriteiniFile/issues", - "source": "https://github.com/Magicalex/WriteiniFile/tree/master" - }, - "time": "2018-09-09T12:40:38+00:00" - }, { "name": "phpgt/typesafegetter", "version": "v1.3.4", @@ -3808,5 +3757,5 @@ "platform-overrides": { "php": "8.3.0" }, - "plugin-api-version": "2.9.0" + "plugin-api-version": "2.11.0" } diff --git a/src/FileWriter.php b/src/FileWriter.php index f25429f..7d530cc 100644 --- a/src/FileWriter.php +++ b/src/FileWriter.php @@ -1,9 +1,6 @@ config->getSectionNames() as $sectionName) { - foreach($this->config->getSection($sectionName) - as $key => $value) { - $writer->update([ - $sectionName => [ - $key => $value, - ] - ]); - } + $data[$sectionName] = array_replace_recursive( + $data[$sectionName] ?? [], + $this->config->getSection($sectionName)->asArray() + ); } - try { - $writer->write(); + $contents = []; + foreach($data as $sectionName => $section) { + $contents []= $this->encodeSection($sectionName, $section); } - catch(Exception $exception) { + + if(file_put_contents($filePath, implode("\n\n", $contents) . "\n") === false) { throw new ConfigException("Unable to write to file: $filePath"); } } + + + /** @param array $section */ + private function encodeSection(string $name, array $section):string { + $lines = ["[$name]"]; + foreach($section as $key => $value) { + if(is_array($value)) { + foreach($value as $index => $item) { + $lines []= "$key" . "[$index] = " . $this->encode($item); + } + } + else { + $lines []= "$key = " . $this->encode($value); + } + } + return implode("\n", $lines); + } + + private function encode(mixed $value):string { + if(!is_string($value)) { + return json_encode($value, JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR); + } + + // Only leave a string bare if the INI parser preserves its value and type. + if($value === trim($value) + && preg_match('/\A[\pL\pN_ .\/:@,\-]+\z/u', $value) + && (parse_ini_string("value = $value", false, INI_SCANNER_TYPED)["value"] ?? null) + === $value) { + return $value; + } + + return '"' . strtr($value, ['\\' => '\\\\', '"' => '\\"', '$' => '\\$']) . '"'; + } } diff --git a/test/phpunit/FileWriterConfigTest.php b/test/phpunit/FileWriterConfigTest.php index 8d16fe9..ef09d46 100644 --- a/test/phpunit/FileWriterConfigTest.php +++ b/test/phpunit/FileWriterConfigTest.php @@ -40,14 +40,82 @@ public function testWrite():void { $tmpFilePath = Helper::getTmpDir("output.ini"); $writer->writeIni($tmpFilePath); - $parsedData = parse_ini_file($tmpFilePath, true); + $parsedData = parse_ini_file($tmpFilePath, true, INI_SCANNER_TYPED); foreach($sectionValues as $sectionName => $section) { foreach($section as $key => $value) { - self::assertEquals( + self::assertSame( $value, $parsedData[$sectionName][$key] ); } } } + + public function testSelectiveQuotingPreservesValues():void { + $values = [ + 'host' => 'localhost', + 'path' => '/var/www/app', + 'words' => 'hello world', + 'url' => 'https://example.com:8080/path', + 'empty' => '', + 'spaces' => ' padded ', + 'comment' => 'before;after', + 'quotes' => 'say "hello"', + 'backslashes' => 'C:\\path\\', + 'environment' => '${HOME}', + 'newline' => "first\nsecond", + 'operators' => 'foo | bar & baz', + 'numeric' => '00123', + 'integerString' => '123', + 'floatString' => '1.5', + 'trueString' => 'true', + 'falseString' => 'false', + 'nullString' => 'null', + 'onString' => 'on', + 'offString' => 'off', + 'constant' => 'PHP_VERSION', + 'integer' => 123, + 'float' => 1.5, + 'wholeFloat' => 1.0, + 'enabled' => true, + 'disabled' => false, + 'nullValue' => null, + ]; + $config = new Config(new ConfigSection('example', $values)); + $path = Helper::getTmpDir('nested', 'output.ini'); + (new FileWriter($config))->writeIni($path); + + self::assertSame($values, parse_ini_file($path, true, INI_SCANNER_TYPED)['example']); + $contents = file_get_contents($path); + foreach(['host = localhost', 'path = /var/www/app', 'words = hello world', + 'url = https://example.com:8080/path'] as $line) { + self::assertStringContainsString("$line\n", $contents); + } + self::assertStringContainsString('numeric = "00123"', $contents); + self::assertStringContainsString('comment = "before;after"', $contents); + } + + public function testExistingEntriesArePreserved():void { + $path = Helper::getTmpDir('output.ini'); + mkdir(dirname($path), 0775, true); + file_put_contents($path, "[existing]\nkeep = value\nchange = old\n" + . "items[first] = one\nitems[second] = two\n\n[other]\nnumber = 42\n"); + $config = new Config(new ConfigSection('existing', ['change' => 'new'])); + (new FileWriter($config))->writeIni($path); + + self::assertSame([ + 'existing' => [ + 'keep' => 'value', + 'change' => 'new', + 'items' => ['first' => 'one', 'second' => 'two'], + ], + 'other' => ['number' => 42], + ], parse_ini_file($path, true, INI_SCANNER_TYPED)); + } + + public function testEmptyConfig():void { + $path = Helper::getTmpDir('output.ini'); + (new FileWriter(new Config()))->writeIni($path); + self::assertSame([], parse_ini_file($path, true, INI_SCANNER_TYPED)); + } } diff --git a/test/phpunit/GeneratorConfigTest.php b/test/phpunit/GeneratorConfigTest.php index 9346a88..df1fa28 100644 --- a/test/phpunit/GeneratorConfigTest.php +++ b/test/phpunit/GeneratorConfigTest.php @@ -52,6 +52,6 @@ public function testGenerate() { self::assertFileExists($filePath); $contents = file_get_contents($filePath); self::assertStringContainsString("[testsection]", $contents); - self::assertStringContainsString("testkey = \"testvalue\"", $contents); + self::assertStringContainsString("testkey = testvalue", $contents); } }