Completed
Pull Request — master (#37)
by
unknown
02:43
created

Persistence::restoreFromFile()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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