Completed
Push — master ( 858d13...9536a3 )
by Arkadiusz
10:30
created

ModelManager   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 2
dl 0
loc 45
rs 10
c 0
b 0
f 0

2 Methods

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