1 | <?php |
||
16 | class FileStorage extends Storage |
||
17 | { |
||
18 | /** |
||
19 | * @var string |
||
20 | */ |
||
21 | protected $dir; |
||
22 | |||
23 | /** |
||
24 | * @var int |
||
25 | */ |
||
26 | protected $gcProbability; |
||
27 | |||
28 | /** |
||
29 | * @const string |
||
30 | */ |
||
31 | const FILE_SUFFIX = '.phpsst'; |
||
32 | |||
33 | /** |
||
34 | * FileStorage constructor. |
||
35 | * @param string $dir |
||
36 | * @param int $gcProbability |
||
37 | */ |
||
38 | 10 | public function __construct($dir, $gcProbability) |
|
52 | |||
53 | /** |
||
54 | * @param Password $password |
||
55 | * @param bool $allowOverwrite |
||
56 | */ |
||
57 | 8 | public function store(Password $password, $allowOverwrite = false) |
|
58 | { |
||
59 | 8 | if (!$allowOverwrite && file_exists($this->getFileName($password))) { |
|
60 | throw new PhPsstException('The ID already exists', PhPsstException::ID_IS_ALREADY_TAKEN); |
||
61 | } |
||
62 | |||
63 | 8 | $this->writeFile($password); |
|
64 | 3 | } |
|
65 | |||
66 | /** |
||
67 | * @param $key |
||
68 | * @return Password|null |
||
69 | */ |
||
70 | 3 | public function get($key) |
|
80 | |||
81 | /** |
||
82 | * @param Password $password |
||
83 | */ |
||
84 | 2 | public function delete(Password $password) |
|
88 | |||
89 | /** |
||
90 | */ |
||
91 | 3 | protected function garbageCollection() |
|
92 | { |
||
93 | 3 | if (!$this->gcProbability || rand(1, $this->gcProbability) !== 1) { |
|
94 | return; |
||
95 | } |
||
96 | |||
97 | 3 | $files = array_diff(scandir($this->dir), array('.', '..')); |
|
98 | 3 | foreach ($files as $file) { |
|
99 | 3 | if (($jsonData = json_decode(file_get_contents($this->dir . $file)))) { |
|
100 | 3 | if ($jsonData->ttlTime < time()) { |
|
101 | unlink($this->dir . $file); |
||
102 | } |
||
103 | 3 | } |
|
104 | 3 | } |
|
105 | 3 | } |
|
106 | |||
107 | /** |
||
108 | * @param Password $password |
||
109 | */ |
||
110 | 7 | protected function writeFile(Password $password) |
|
121 | |||
122 | /** |
||
123 | * @param Password $password |
||
124 | * @return string |
||
125 | */ |
||
126 | 4 | protected function getFileName(Password $password) |
|
130 | |||
131 | /** |
||
132 | * @param string $key |
||
133 | * @return string |
||
134 | */ |
||
135 | 4 | protected function getFileNameFromKey($key) |
|
139 | } |
||
140 |