Passed
Push — main ( f2434b...495b04 )
by Sílvio
01:55
created

Cacheer::putCache()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 13
c 3
b 0
f 0
nc 8
nop 3
dl 0
loc 22
rs 9.8333
1
<?php
2
3
namespace Silviooosilva\CacheerPhp;
4
5
use Exception;
6
use RecursiveDirectoryIterator;
7
use RecursiveIteratorIterator;
8
9
/**
10
 * Class CacheerPHP
11
 *
12
 * @author Sílvio Silva <https://github.com/silviooosilva>
13
 * @package Silviooosilva\CacheerPhp
14
 */
15
class Cacheer
16
{
17
    /**
18
     * @var string
19
     */
20
    private string $cacheDir;
21
22
    /**
23
     * @var array
24
     */
25
    private array $options = [];
26
27
    /**
28
     * @var string
29
     */
30
    private string $message;
31
32
    /**
33
     * @var integer
34
     */
35
    private int $defaultTTL = 3600; // 1 hora por padrão
36
37
    /**
38
     * @var boolean
39
     */
40
    private bool $success;
41
42
    /**
43
     * @param array $options
44
     */
45
    public function __construct(array $options = [])
46
    {
47
        if (!empty($options)) {
48
            $this->options = $options;
49
        }
50
        if (!isset($options['cacheDir'])) {
51
            throw new Exception("The 'cacheDir' option is required.");
52
        }
53
54
55
        $this->cacheDir = realpath($options['cacheDir']) ?: "";
56
        $this->createCacheDir($options['cacheDir']);
57
        $this->defaultTTL = (isset($options['expirationTime']) ? $this->convertExpirationToSeconds($options['expirationTime']) : $this->defaultTTL);
58
    }
59
60
61
    /**
62
     * @param string $cacheKey
63
     * @return $this | string
64
     */
65
    public function getCache(string $cacheKey, string $namespace = '')
66
    {
67
        $namespace = $namespace ? md5($namespace) . '/' : '';
68
        $cacheFile = "{$this->cacheDir}/{$namespace}" . md5($cacheKey) . '.cache';
69
        if (file_exists($cacheFile) && (filemtime($cacheFile) > (time() - $this->defaultTTL))) {
70
            $this->success = true;
71
            return unserialize(file_get_contents($cacheFile));
72
        }
73
74
        $this->message = "cacheFile not found, does not exists or expired";
75
        $this->success = false;
76
        return $this;
77
    }
78
79
80
    /**
81
     * @param string $cacheKey
82
     * @param mixed $cacheData
83
     * @return $this | string
84
     */
85
    public function putCache(string $cacheKey, mixed $cacheData, string $namespace = '')
86
    {
87
        $namespace = $namespace ? md5($namespace) . '/' : '';
88
        $cacheDir = "{$this->cacheDir}/";
89
90
        if (!empty($namespace)) {
91
            $cacheDir = "{$this->cacheDir}/{$namespace}";
92
            $this->createCacheDir($cacheDir);
93
        }
94
95
        $cacheFile = $cacheDir . md5($cacheKey) . ".cache";
96
        $data = serialize($cacheData);
97
98
99
        if (!@file_put_contents($cacheFile, $data, LOCK_EX)) {
100
            throw new Exception("Could not create cache file. Check your dir permissions and try again.");
101
        } else {
102
            $this->message = "Cache file created successfully";
103
            $this->success = true;
104
        }
105
106
        return $this;
107
    }
108
109
    /**
110
     * @param string $cacheKey
111
     * @return $this | string
112
     */
113
    public function clearCache(string $cacheKey, string $namespace = '')
114
    {
115
        $namespace = $namespace ? md5($namespace) . '/' : '';
116
        $cacheFile = "{$this->cacheDir}/{$namespace}" . md5($cacheKey) . ".cache";
117
        if (file_exists($cacheFile)) {
118
            unlink($cacheFile);
119
            $this->message = "Cache file deleted successfully!";
120
            $this->success = true;
121
        } else {
122
            $this->message = "Cache file does not exists!";
123
            $this->success = false;
124
        }
125
        return $this;
126
    }
127
128
    /**
129
     * @return $this | string
130
     */
131
    public function flushCache()
132
    {
133
        $cacheDir = "{$this->cacheDir}/";
134
135
136
        $cacheFiles = new RecursiveIteratorIterator(
137
            new RecursiveDirectoryIterator($cacheDir, RecursiveDirectoryIterator::SKIP_DOTS),
138
            RecursiveIteratorIterator::CHILD_FIRST
139
        );
140
141
        if (count(scandir($cacheDir)) <= 2) {
142
            $this->message = "No CacheFiles in {$cacheDir}";
143
            $this->success = false;
144
        }
145
146
        foreach ($cacheFiles as $cacheFile) {
147
            $cachePath = $cacheFile->getPathname();
148
            if ($cacheFile->isDir()) {
149
                $this->removeCacheDir($cachePath);
150
                $this->message = "Flush finished successfully";
151
                $this->success = true;
152
            } else {
153
                unlink($cachePath);
154
                $this->message = "Flush finished successfully";
155
                $this->success = true;
156
            }
157
        }
158
159
160
161
        return $this;
162
    }
163
164
    /**
165
     * @return string
166
     */
167
    public function getMessage()
168
    {
169
        return $this->message;
170
    }
171
172
    /**
173
     * @return boolean
174
     */
175
    public function isSuccess()
176
    {
177
        return $this->success;
178
    }
179
180
    /**
181
     * @param string $dirName
182
     * @return mixed
183
     */
184
    private function createCacheDir(string $dirName)
185
    {
186
        if (!file_exists($dirName) || !is_dir($dirName)) {
187
            if (!mkdir($dirName, 0775, true)) {
188
                $this->message = "Could not create cache folder";
189
                return $this;
190
            }
191
        }
192
    }
193
194
    /**
195
     * Convert expiration time to seconds
196
     * @param string $expiration
197
     * @return int
198
     */
199
    private function convertExpirationToSeconds(string $expiration)
200
    {
201
        if (strpos($expiration, 'second') !== false) {
202
            return (int)$expiration * 1;
203
        }
204
        if (strpos($expiration, 'minute') !== false) {
205
            return (int)$expiration * 60;
206
        }
207
        if (strpos($expiration, 'hour') !== false) {
208
            return (int)$expiration * 3600;
209
        }
210
    }
211
212
213
    /**
214
     * @param string $cacheDir
215
     * @return bool
216
     */
217
    private function removeCacheDir(string $cacheDir)
218
    {
219
        return (rmdir($cacheDir) ? true : false);
220
    }
221
}
222