Skip to content

Commit

Permalink
Do not requre file to exist for model manager
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas committed Feb 3, 2017
1 parent 858d13b commit b7c9983
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 26 deletions.
20 changes: 11 additions & 9 deletions src/Phpml/ModelManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,26 @@

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);
Expand All @@ -33,10 +34,11 @@ public function saveToFile(Estimator $object, string $filepath)

/**
* @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));
Expand Down
22 changes: 5 additions & 17 deletions tests/Phpml/ModelManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down

0 comments on commit b7c9983

Please sign in to comment.