Add readPHPData() and writePHPData() to Storage class

This commit is contained in:
Kijin Sung 2016-03-20 19:22:59 +09:00
parent 820e29b5ba
commit 4fa3bf8cfb
2 changed files with 45 additions and 0 deletions

View file

@ -166,6 +166,27 @@ class Storage
}
}
/**
* Read PHP data from a file, formatted for easy retrieval.
*
* This method returns the data on success and false on failure.
*
* @param string $filename
* @return mixed
*/
public static function readPHPData($filename)
{
$filename = rtrim($filename, '/\\');
if (@is_file($filename) && @is_readable($filename))
{
return @include $filename;
}
else
{
return false;
}
}
/**
* Write $content to a file.
*
@ -201,6 +222,21 @@ class Storage
return $result;
}
/**
* Write PHP data to a file, formatted for easy retrieval.
*
* This method returns true on success and false on failure.
* Resources and anonymous functions cannot be saved.
*
* @param string $filename
* @param mixed $data
* @return string|false
*/
public static function writePHPData($filename, $data)
{
return self::write($filename, '<' . '?php return unserialize(' . var_export(serialize($data), true) . ');');
}
/**
* Copy $source to $destination.
*

View file

@ -132,6 +132,15 @@ class StorageTest extends \Codeception\TestCase\Test
$this->assertEquals('foobarbazzjazz', file_get_contents($testfile));
}
public function testReadWritePHPData()
{
$testfile = \RX_BASEDIR . 'tests/_output/test.php';
$data = array('foo' => 'bar', 'baz' => array('rhymix' => '\'"special\\chars' . chr(0) . chr(255), 'test' => 'wow'));
$this->assertTrue(Rhymix\Framework\Storage::writePHPData($testfile, $data));
$this->assertEquals($data, Rhymix\Framework\Storage::readPHPData($testfile));
}
public function testCopy()
{
$source = \RX_BASEDIR . 'tests/_output/copy.source.txt';