Passed
Pull Request — master (#178)
by
unknown
02:33
created

ModelManager::resetFile()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 3
Ratio 30 %

Importance

Changes 0
Metric Value
dl 3
loc 10
rs 9.2
c 0
b 0
f 0
cc 4
eloc 5
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml;
6
7
use Phpml\Exception\FileException;
8
use Phpml\Exception\SerializeException;
9
10
class ModelManager
11
{
12
    public function saveToFile(Estimator $estimator, string $filePath): void
13
    {
14
        if (!is_writable(dirname($filePath))) {
15
            throw FileException::cantSaveFile(basename($filePath));
16
        }
17
18
        $serialized = serialize($estimator);
19
        if (empty($serialized)) {
20
            throw SerializeException::cantSerialize(gettype($estimator));
21
        }
22
23
        $result = file_put_contents($filePath, $serialized, LOCK_EX);
24
        if ($result === false) {
25
            throw FileException::cantSaveFile(basename($filePath));
26
        }
27
    }
28
29
    public function restoreFromFile(string $filePath): Estimator
30
    {
31 View Code Duplication
        if (!file_exists($filePath) || !is_readable($filePath)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
            throw FileException::cantOpenFile(basename($filePath));
33
        }
34
35
        $object = unserialize(file_get_contents($filePath));
36
        if ($object === false) {
37
            throw SerializeException::cantUnserialize(basename($filePath));
38
        }
39
40
        return $object;
41
    }
42
43
    public function resetFile(string $filePath): void
44
    {
45 View Code Duplication
        if (!file_exists($filePath) || !is_readable($filePath)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
46
            throw FileException::cantOpenFile(basename($filePath));
47
        }
48
49
        if (!unlink($filePath)) {
50
            throw FileException::cantDeleteFile(basename($filePath));
51
        }
52
    }
53
}
54