Do not requre file to exist for model manager

This commit is contained in:
Arkadiusz Kondas 2017-02-03 17:48:15 +01:00
parent 858d13b0fa
commit b7c9983524
2 changed files with 16 additions and 26 deletions

View File

@ -4,25 +4,26 @@ declare(strict_types=1);
namespace Phpml;
use Phpml\Estimator;
use Phpml\Exception\SerializeException;
use Phpml\Exception\FileException;
class ModelManager
{
/**
* @param Estimator $object
* @param string $filepath
* @param Estimator $estimator
* @param string $filepath
* @throws FileException
* @throws SerializeException
*/
public function saveToFile(Estimator $object, string $filepath)
public function saveToFile(Estimator $estimator, string $filepath)
{
if (!file_exists($filepath) || !is_writable(dirname($filepath))) {
if (!is_writable(dirname($filepath))) {
throw FileException::cantSaveFile(basename($filepath));
}
$serialized = serialize($object);
$serialized = serialize($estimator);
if (empty($serialized)) {
throw SerializeException::cantSerialize(get_type($object));
throw SerializeException::cantSerialize(get_type($estimator));
}
$result = file_put_contents($filepath, $serialized, LOCK_EX);
@ -33,10 +34,11 @@ class ModelManager
/**
* @param string $filepath
*
* @return Estimator
* @throws FileException
* @throws SerializeException
*/
public function restoreFromFile(string $filepath)
public function restoreFromFile(string $filepath) : Estimator
{
if (!file_exists($filepath) || !is_readable($filepath)) {
throw FileException::cantOpenFile(basename($filepath));

View File

@ -12,27 +12,15 @@ class ModelManagerTest extends TestCase
{
public function testSaveAndRestore()
{
$filename = 'test-save-to-file-'.rand(100, 999).'-'.uniqid();
$filepath = tempnam(sys_get_temp_dir(), $filename);
$filename = uniqid();
$filepath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
$obj = new LeastSquares();
$estimator = new LeastSquares();
$modelManager = new ModelManager();
$modelManager->saveToFile($obj, $filepath);
$modelManager->saveToFile($estimator, $filepath);
$restored = $modelManager->restoreFromFile($filepath);
$this->assertEquals($obj, $restored);
}
/**
* @expectedException \Phpml\Exception\FileException
*/
public function testSaveToWrongFile()
{
$filepath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'unexisting';
$obj = new LeastSquares();
$modelManager = new ModelManager();
$modelManager->saveToFile($obj, $filepath);
$this->assertEquals($estimator, $restored);
}
/**