2017-02-02 08:03:09 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Phpml;
|
|
|
|
|
|
|
|
use Phpml\Exception\FileException;
|
2017-11-06 07:56:37 +00:00
|
|
|
use Phpml\Exception\SerializeException;
|
2017-02-02 08:03:09 +00:00
|
|
|
|
|
|
|
class ModelManager
|
|
|
|
{
|
2017-11-14 20:21:23 +00:00
|
|
|
public function saveToFile(Estimator $estimator, string $filepath): void
|
2017-02-02 08:03:09 +00:00
|
|
|
{
|
2017-02-03 16:48:15 +00:00
|
|
|
if (!is_writable(dirname($filepath))) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new FileException(sprintf('File "%s" can\'t be saved.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
2017-02-03 16:48:15 +00:00
|
|
|
$serialized = serialize($estimator);
|
2017-02-02 08:03:09 +00:00
|
|
|
if (empty($serialized)) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new SerializeException(sprintf('Class "%s" can not be serialized.', gettype($estimator)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$result = file_put_contents($filepath, $serialized, LOCK_EX);
|
|
|
|
if ($result === false) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new FileException(sprintf('File "%s" can\'t be saved.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-22 21:16:10 +00:00
|
|
|
public function restoreFromFile(string $filepath): Estimator
|
2017-02-02 08:03:09 +00:00
|
|
|
{
|
|
|
|
if (!file_exists($filepath) || !is_readable($filepath)) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new FileException(sprintf('File "%s" can\'t be open.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$object = unserialize(file_get_contents($filepath));
|
|
|
|
if ($object === false) {
|
2018-03-03 15:03:53 +00:00
|
|
|
throw new SerializeException(sprintf('"%s" can not be unserialized.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return $object;
|
|
|
|
}
|
|
|
|
}
|