Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
55 changes: 2 additions & 53 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 49 additions & 15 deletions src/FileWriter.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
<?php
namespace GT\Config;

use Exception;
use WriteiniFile\WriteiniFile;

class FileWriter {
public function __construct(
private Config $config
Expand All @@ -15,24 +12,61 @@ public function writeIni(string $filePath):void {
mkdir(dirname($filePath), 0775, true);
}

$writer = new WriteiniFile($filePath);
$data = [];
if(is_file($filePath)) {
$data = parse_ini_file($filePath, true, INI_SCANNER_TYPED);
if($data === false) {
throw new ConfigException("Unable to parse file: $filePath");
}
}

foreach($this->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<string, mixed> $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, ['\\' => '\\\\', '"' => '\\"', '$' => '\\$']) . '"';
}
}
72 changes: 70 additions & 2 deletions test/phpunit/FileWriterConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
2 changes: 1 addition & 1 deletion test/phpunit/GeneratorConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Loading