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))) {
|
2019-10-28 06:49:47 +00:00
|
|
|
throw new FileException(sprintf('File "%s" cannot be saved.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
2017-02-03 16:48:15 +00:00
|
|
|
$serialized = serialize($estimator);
|
2018-10-28 06:44:52 +00:00
|
|
|
if (!isset($serialized[0])) {
|
2019-10-28 06:49:47 +00:00
|
|
|
throw new SerializeException(sprintf('Class "%s" cannot be serialized.', gettype($estimator)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$result = file_put_contents($filepath, $serialized, LOCK_EX);
|
|
|
|
if ($result === false) {
|
2019-10-28 06:49:47 +00:00
|
|
|
throw new FileException(sprintf('File "%s" cannot 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)) {
|
2019-10-28 06:49:47 +00:00
|
|
|
throw new FileException(sprintf('File "%s" cannot be opened.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
2019-11-08 14:28:42 +00:00
|
|
|
$object = unserialize((string) file_get_contents($filepath));
|
|
|
|
if ($object === false || !$object instanceof Estimator) {
|
2019-10-28 06:49:47 +00:00
|
|
|
throw new SerializeException(sprintf('"%s" cannot be unserialized.', basename($filepath)));
|
2017-02-02 08:03:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return $object;
|
|
|
|
}
|
|
|
|
}
|