Passed
Push — master ( a4a58e...30c82e )
by Krisztián
02:29
created

Maintainer::free()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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