Completed
Push — master ( c1b1a5...8f122f )
by Arkadiusz
02:53
created

ModelManager::saveToFile()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
rs 8.8571
cc 5
eloc 9
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml;
6
7
use Phpml\Estimator;
8
use Phpml\Exception\SerializeException;
9
use Phpml\Exception\FileException;
10
11
class ModelManager
12
{
13
    /**
14
     * @param Estimator     $object
15
     * @param string        $filepath
16
     */
17
    public function saveToFile(Estimator $object, string $filepath)
18
    {
19
        if (!file_exists($filepath) || !is_writable(dirname($filepath))) {
20
            throw FileException::cantSaveFile(basename($filepath));
21
        }
22
23
        $serialized = serialize($object);
24
        if (empty($serialized)) {
25
            throw SerializeException::cantSerialize(get_type($object));
26
        }
27
28
        $result = file_put_contents($filepath, $serialized, LOCK_EX);
29
        if ($result === false) {
30
            throw FileException::cantSaveFile(basename($filepath));
31
        }
32
    }
33
34
    /**
35
     * @param string $filepath
36
     *
37
     * @return Estimator
38
     */
39
    public function restoreFromFile(string $filepath)
40
    {
41
        if (!file_exists($filepath) || !is_readable($filepath)) {
42
            throw FileException::cantOpenFile(basename($filepath));
43
        }
44
45
        $object = unserialize(file_get_contents($filepath));
46
        if ($object === false) {
47
            throw SerializeException::cantUnserialize(basename($filepath));
48
        }
49
50
        return $object;
51
    }
52
}
53