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
|
|
|
/** |
13
|
|
|
* @param Estimator $estimator |
14
|
|
|
* @param string $filepath |
15
|
|
|
* |
16
|
|
|
* @return void |
17
|
|
|
* |
18
|
|
|
* @throws FileException |
19
|
|
|
* @throws SerializeException |
20
|
|
|
*/ |
21
|
|
|
public function saveToFile(Estimator $estimator, string $filepath): void |
22
|
|
|
{ |
23
|
|
|
if (!is_writable(dirname($filepath))) { |
24
|
|
|
throw FileException::cantSaveFile(basename($filepath)); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
$serialized = serialize($estimator); |
28
|
|
|
if (empty($serialized)) { |
29
|
|
|
throw SerializeException::cantSerialize(gettype($estimator)); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$result = file_put_contents($filepath, $serialized, LOCK_EX); |
33
|
|
|
if ($result === false) { |
34
|
|
|
throw FileException::cantSaveFile(basename($filepath)); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param string $filePath |
40
|
|
|
* |
41
|
|
|
* @return Estimator |
42
|
|
|
* |
43
|
|
|
* @throws FileException |
44
|
|
|
* @throws SerializeException |
45
|
|
|
*/ |
46
|
|
|
public function restoreFromFile(string $filePath): Estimator |
47
|
|
|
{ |
48
|
|
View Code Duplication |
if (!file_exists($filePath) || !is_readable($filePath)) { |
|
|
|
|
49
|
|
|
throw FileException::cantOpenFile(basename($filePath)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$object = unserialize(file_get_contents($filePath)); |
53
|
|
|
if ($object === false) { |
54
|
|
|
throw SerializeException::cantUnserialize(basename($filePath)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $object; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string $filePath |
62
|
|
|
* |
63
|
|
|
* @return void |
64
|
|
|
* |
65
|
|
|
* @throws FileException |
66
|
|
|
*/ |
67
|
|
|
public function reset(string $filePath): void |
68
|
|
|
{ |
69
|
|
View Code Duplication |
if (!file_exists($filePath) || !is_readable($filePath)) { |
|
|
|
|
70
|
|
|
throw FileException::cantOpenFile(basename($filePath)); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if (!unlink($filePath)) { |
74
|
|
|
throw FileException::cantDeleteFile(basename($filePath)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
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.