1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace pjpawel\LightApi\Component; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
|
7
|
|
|
/** @deprecated */ |
8
|
|
|
class Serializer |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
private string $serializedDir; |
12
|
|
|
public bool $serializeOnDestruct = false; |
13
|
|
|
/** |
14
|
|
|
* @var array<string,object> |
15
|
|
|
*/ |
16
|
|
|
public array $serializedObjects = []; |
17
|
|
|
|
18
|
|
|
public function __construct(string $serializedDir) |
19
|
|
|
{ |
20
|
|
|
$this->serializedDir = $serializedDir; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function loadSerialized(): bool |
24
|
|
|
{ |
25
|
|
|
if (!is_dir($this->serializedDir)) { |
26
|
|
|
$this->serializeOnDestruct = true; |
27
|
|
|
return false; |
28
|
|
|
} |
29
|
|
|
try { |
30
|
|
|
$ini = ini_get('error_reporting'); |
31
|
|
|
if ($ini === false) { |
32
|
|
|
$ini = -1; |
33
|
|
|
} |
34
|
|
|
error_reporting(E_ERROR); |
35
|
|
|
foreach (array_diff(scandir($this->serializedDir), ['.', '..']) as $file) { |
36
|
|
|
$fileName = $this->serializedDir . DIRECTORY_SEPARATOR . $file; |
37
|
|
|
if (!is_file($fileName)) { |
38
|
|
|
continue; |
39
|
|
|
} |
40
|
|
|
$serialized = file_get_contents($fileName); |
41
|
|
|
if ($serialized === false) { |
42
|
|
|
throw new Exception('Cannot load serialized object in ' . $fileName); |
43
|
|
|
} |
44
|
|
|
$this->serializedObjects[$this->makeClassNameFromFileName($file)] = unserialize($serialized); |
45
|
|
|
} |
46
|
|
|
error_reporting((int) $ini); |
47
|
|
|
return true; |
48
|
|
|
} catch (Exception $e) { |
49
|
|
|
error_reporting((int) $ini); |
50
|
|
|
error_log($e->getMessage()); |
51
|
|
|
$this->serializeOnDestruct = true; |
52
|
|
|
return false; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param array<string,object> $objects |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
|
|
public function makeSerialization(array $objects): void |
61
|
|
|
{ |
62
|
|
|
if (!is_dir($this->serializedDir)) { |
63
|
|
|
mkdir($this->serializedDir, 0777, true); |
64
|
|
|
} |
65
|
|
|
foreach ($objects as $name => $object) { |
66
|
|
|
file_put_contents($this->makeFileNameFromClassName($name), serialize($object)); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
private function makeFileNameFromClassName(string $className): string |
71
|
|
|
{ |
72
|
|
|
return $this->serializedDir . DIRECTORY_SEPARATOR . str_replace('\\', '--', $className); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function makeClassNameFromFileName(string $fileName): string |
76
|
|
|
{ |
77
|
|
|
return str_replace('--', '\\', $fileName); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
|
82
|
|
|
|
83
|
|
|
|
84
|
|
|
|
85
|
|
|
|
86
|
|
|
|
87
|
|
|
|
88
|
|
|
|
89
|
|
|
|
90
|
|
|
} |