Maintainer::checkBackup()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 2
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PhpCache\Storage;
4
5
use function strlen;
6
7
/**
8
 * Description of Maintainer.
9
 *
10
 * @author dude920228
11
 */
12
class Maintainer
13
{
14
    private $ttl;
15
    private $lastBackupRun;
16
    private $backupDir;
17
    private $backupTime;
18
    private $memoryLimit;
19
20
    public function __construct(
21
        int $ttl,
22
        string $backupDir,
23
        int $backupTime,
24
        int $memoryLimit
25
    ) {
26
        $this->ttl = $ttl;
27
        $this->lastBackupRun = time();
28
        $this->backupDir = $backupDir;
29
        $this->backupTime = $backupTime;
30
        $this->memoryLimit = $memoryLimit;
31
    }
32
33
    /**
34
     * @param Bucket $bucket
35
     */
36
    public function maintainBucket(Bucket $bucket): void
37
    {
38
        $entries = $bucket->getEntries();
39
        foreach ($entries as $key => $entry) {
40
            $entryElapsedTime = time() - $entry['created_time'];
41
            if ($entryElapsedTime >= $this->ttl) {
42
                $bucket->delete($key);
43
            }
44
        }
45
    }
46
47
    private function checkMemory(Bucket $bucket): int
48
    {
49
        $size = 0;
50
        foreach ($bucket->getEntries() as $entry) {
51
            $size += strlen($entry['content']);
52
        }
53
54
        return $size;
55
    }
56
57
    public function backup(Bucket $bucket): void
58
    {
59
        $this->createBackupDir();
60
        $this->backupToFile($bucket);
61
    }
62
63
    public function checkBackup(int $time, Bucket $bucket): void
64
    {
65
        if ($time - $this->lastBackupRun >= $this->backupTime ||
66
            $this->checkMemory($bucket) >= $this->memoryLimit) {
67
            $this->backup($bucket);
68
            $this->free($bucket);
69
        }
70
    }
71
72
    private function free(Bucket $bucket): void
73
    {
74
        foreach ($bucket->getEntries() as $key => $entry) {
75
            $bucket->delete($key);
76
        }
77
    }
78
79
    private function createBackupDir(): void
80
    {
81
        if (!file_exists($this->backupDir)) {
82
            mkdir($this->backupDir);
83
        }
84
    }
85
86
    private function backupToFile(Bucket $bucket): void
87
    {
88
        foreach ($bucket->getEntries() as $key => $entry) {
89
            file_put_contents(
90
                $this->backupDir.'/'.$key.'.dat',
91
                serialize($entry)
92
            );
93
        }
94
    }
95
}
96