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

Persistence   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

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

2 Methods

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