Skip to content

Commit

Permalink
ensure write output and toString output are equal
Browse files Browse the repository at this point in the history
  • Loading branch information
mfonda committed Mar 9, 2011
1 parent 4c31b8a commit 8b40011
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 24 deletions.
47 changes: 23 additions & 24 deletions Config/Lite.php
Expand Up @@ -198,6 +198,26 @@ protected function normalizeValue($value)
* @throws Config_Lite_Exception_Runtime when write failed
*/
public function write($filename, $sectionsarray)
{
$content = $this->buildOutputString($sectionsarray);
if (false === file_put_contents($filename, $content, LOCK_EX)) {
throw new Config_Lite_Exception_Runtime(
sprintf(
'failed to write file `%s\' for writing.', $filename
)
);
}
return true;
}

/**
* Generated the output of the ini file, suitable for echo'ing or
* writing back to the ini file.
*
* @param string $sectionsarray array of ini data
* @return string
*/
protected function buildOutputString($sectionsarray)
{
$content = '';
$sections = '';
Expand Down Expand Up @@ -231,17 +251,9 @@ public function write($filename, $sectionsarray)
}
$content .= $sections;
}

if (false === file_put_contents($filename, $content, LOCK_EX)) {
throw new Config_Lite_Exception_Runtime(
sprintf(
'failed to write file `%s\' for writing.', $filename
)
);
}
return true;
return $content;
}

/**
* converts type (format) to string or representable Config Format
*
Expand Down Expand Up @@ -671,20 +683,7 @@ public function setProcessSections($processSections)
*/
public function __toString()
{
$s = "";
if ($this->sections != null) {
foreach ($this->sections as $section => $name) {
if (is_array($name)) {
$s .= sprintf("[%s]\n", $section);
foreach ($name as $key => $val) {
$s .= sprintf("\t%s = %s\n", $key, $val);
}
} else {
$s .= sprintf("%s=%s\n", $section, $name);
}
}
}
return $s;
return $this->buildOutputString($this->sections);
}

/**
Expand Down
7 changes: 7 additions & 0 deletions tests/Config_LiteTest.php
Expand Up @@ -366,4 +366,11 @@ public function testGetFilename()
$this->config->setFilename($filename);
$this->assertEquals($filename, $this->config->getFilename());
}

public function testToStringMatchesWrite()
{
$this->config->setFilename($this->filename);
$this->config->save();
$this->assertEquals($this->config->__toString(), file_get_contents($this->filename));
}
}

0 comments on commit 8b40011

Please sign in to comment.