From a37cd9f9db04cd814e30f36f5d683ff03a7849ec Mon Sep 17 00:00:00 2001 From: tetrode Date: Wed, 18 Jan 2017 17:59:17 +0100 Subject: [PATCH] Also propagate the comments Adding the possibility to also propagate the comments when writing the ini file. Works as follows: $ini = 'piwik.ini'; $reader = new \Piwik\Ini\IniReader(); $config = $reader->readFile($ini); $comments = $reader->readComments($ini); $writer = new \Piwik\Ini\IniWriter(); $writer->writeToFile('piwik-new.ini', $config, '', $comments); Things that do not work: 1 pre-section comments disappear: ; section comment [MySection] ; option comment myOption = 1 becomes [MySection] ; option comment myOption = 1 2 Individual array comments disappear: [MySection] ; comment a ar[] = "a" ; comment b ar[] = "b" ; comment c ar[] = "c" becomes [MySection] ; comment a ar[] = "a" ar[] = "b" ar[] = "c" --- src/IniWriter.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/IniWriter.php b/src/IniWriter.php index b18af46..685cdfe 100644 --- a/src/IniWriter.php +++ b/src/IniWriter.php @@ -92,6 +92,9 @@ public function writeToString(array $config, $header = '') $value = array($value); } + // adding comments + $ini .= $this->addComments($comments, $sectionName, $option); + if (is_array($value)) { foreach ($value as $currentValue) { $ini .= $option . '[] = ' . $this->encodeValue($currentValue) . "\n"; @@ -107,6 +110,26 @@ public function writeToString(array $config, $header = '') return $ini; } + private function addComments($comments, $sectionName, $option) { + $result = ""; + + if (isset($comments[$sectionName][$option])) { + $comment = explode("\n", $comments[$sectionName][$option]); + array_pop($comment); + $next = array_shift($comment); + while ($next !== null) { + if ($next === "") { + $result .= "\n"; + } else { + $result .= "; " . $next . "\n"; + } + $next = array_shift($comment); + } + } + + return $result; + } + private function encodeValue($value) { if (is_bool($value)) {