1 | <?php |
||
2 | |||
3 | namespace PhpCache\Storage; |
||
4 | |||
5 | /** |
||
6 | * Description of MessageBucket. |
||
7 | * |
||
8 | * @author dude920228 |
||
9 | */ |
||
10 | class Bucket implements StorageInterface |
||
11 | { |
||
12 | private $entries; |
||
13 | private $backupDir; |
||
14 | |||
15 | public function __construct(string $backupDir) |
||
16 | { |
||
17 | $this->backupDir = $backupDir; |
||
18 | $this->entries = []; |
||
19 | } |
||
20 | |||
21 | public function get(string $key): string |
||
22 | { |
||
23 | if (!array_key_exists($key, $this->entries) && !$this->existsInBackup($key)) { |
||
24 | return false; |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
25 | } |
||
26 | if ($this->existsInBackup($key)) { |
||
27 | $entry = unserialize($this->getFromBackup($key)); |
||
28 | |||
29 | return gzuncompress($entry['content']); |
||
30 | } |
||
31 | |||
32 | return gzuncompress($this->entries[$key]['content']); |
||
33 | } |
||
34 | |||
35 | private function existsInBackup($key): bool |
||
36 | { |
||
37 | if (file_exists($this->backupDir.'/'.$key.'.dat')) { |
||
38 | return true; |
||
39 | } |
||
40 | |||
41 | return false; |
||
42 | } |
||
43 | |||
44 | private function getFromBackup($key): string |
||
45 | { |
||
46 | $contents = ''; |
||
47 | $handle = fopen($this->backupDir.'/'.$key.'.dat', 'r+'); |
||
48 | if (is_resource($handle)) { |
||
49 | while (!feof($handle)) { |
||
50 | $contents .= fread($handle, 32); |
||
51 | } |
||
52 | } |
||
53 | |||
54 | return $contents; |
||
55 | } |
||
56 | |||
57 | public function store(string $key, string $entry, $time = null): bool |
||
58 | { |
||
59 | $compressed = gzcompress($entry, 9); |
||
60 | $this->entries[$key]['content'] = $compressed; |
||
61 | $this->entries[$key]['created_time'] = is_null($time) ? time() : $time; |
||
62 | if (!$compressed) { |
||
63 | return false; |
||
64 | } |
||
65 | |||
66 | return true; |
||
67 | } |
||
68 | |||
69 | public function getEntries(): array |
||
70 | { |
||
71 | return $this->entries; |
||
72 | } |
||
73 | |||
74 | public function delete($key): bool |
||
75 | { |
||
76 | if (array_key_exists($key, $this->entries)) { |
||
77 | unset($this->entries[$key]); |
||
78 | |||
79 | return true; |
||
80 | } |
||
81 | |||
82 | return false; |
||
83 | } |
||
84 | } |
||
85 |