-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileStorage.php
116 lines (103 loc) · 2.6 KB
/
FileStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
declare(strict_types=1);
namespace Webiik\Login\Storage;
class FileStorage implements StorageInterface
{
/**
* Storage path
* @var string
*/
private $path = './';
/**
* Permanent identifier file extension
* @var string
*/
private $ext = 'wip';
/**
* @param string $path
*/
public function setPath(string $path): void
{
$this->path = rtrim($path, '/') . '/';
}
/**
* @param string $ext
*/
public function setExt(string $ext): void
{
$this->ext = ltrim($ext, '.');
}
/**
* @param int|string $uid
* @param string $selector
* @param string $key
* @param int $expiration
*/
public function store($uid, string $selector, string $key, int $expiration): void
{
$data = serialize([
'uid' => $uid,
'selector' => $selector,
'key' => $key,
'expiration' => $expiration,
]);
file_put_contents($this->getFileName($selector), $data);
}
/**
* @param string $selector
* @return array
*/
public function get(string $selector): array
{
$data = [];
$filename = $this->getFileName($selector);
if (file_exists($filename)) {
$data = file_get_contents($filename);
if ($data) {
$data = unserialize($data);
}
}
return is_array($data) ? $data : [];
}
/**
* @param string $selector
*/
public function delete(string $selector): void
{
@unlink($this->getFileName($selector));
}
/**
* @param string $selector
* @param int $ttl
*/
public function updateExpiration(string $selector, int $ttl): void
{
$data = $this->get($selector);
if (!$data) {
return;
}
$data['expiration'] = (int)($_SERVER['REQUEST_TIME'] + $ttl);
$this->store($data['uid'], $data['selector'], $data['key'], $data['expiration']);
}
/**
* @param int $ttl
*/
public function deleteExpired(int $ttl): void
{
foreach (new \DirectoryIterator($this->path) as $item) {
if ($item->isFile() && $item->getExtension() == $this->ext) {
if ($_SERVER['REQUEST_TIME'] - $ttl > $item->getMTime()) {
@unlink($item->getPathname());
}
}
}
}
/**
* @param string $selector
* @return string
*/
private function getFileName(string $selector): string
{
return $this->path . $selector . '.' . $this->ext;
}
}