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

ModelManager   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
c 0
b 0
f 0
lcom 0
cbo 2
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B saveToFile() 0 16 5
A restoreFromFile() 0 13 4
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