1: <?php
2: namespace Opencart\System\Library\Cache;
3: /**
4: * Class File
5: *
6: * @package Opencart\System\Library\Cache
7: */
8: class File {
9: /**
10: * @var int
11: */
12: private int $expire;
13:
14: /**
15: * Constructor
16: *
17: * @param int $expire
18: */
19: public function __construct(int $expire = 3600) {
20: $this->expire = $expire;
21: }
22:
23: /**
24: * Get
25: *
26: * @param string $key
27: *
28: * @return mixed
29: */
30: public function get(string $key) {
31: //$key = md5($key);
32: //sprintf();
33:
34: $files = glob(DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*');
35:
36: if ($files) {
37: return json_decode(file_get_contents($files[0]), true);
38: } else {
39: return [];
40: }
41: }
42:
43: /**
44: * Set
45: *
46: * @param string $key
47: * @param mixed $value
48: * @param int $expire
49: *
50: * @return void
51: */
52: public function set(string $key, $value, int $expire = 0): void {
53: $this->delete($key);
54:
55: if (!$expire) {
56: $expire = $this->expire;
57: }
58:
59: file_put_contents(DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.' . (time() + $expire), json_encode($value));
60: }
61:
62: /**
63: * Delete
64: *
65: * @param string $key
66: *
67: * @return void
68: */
69: public function delete(string $key): void {
70: $files = glob(DIR_CACHE . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*');
71:
72: if ($files) {
73: foreach ($files as $file) {
74: if (!@unlink($file)) {
75: clearstatcache(false, $file);
76: }
77: }
78: }
79: }
80:
81: /**
82: * Destructor
83: */
84: public function __destruct() {
85: $files = glob(DIR_CACHE . 'cache.*');
86:
87: if ($files && mt_rand(1, 100) == 1) {
88: foreach ($files as $file) {
89: $time = substr(strrchr($file, '.'), 1);
90:
91: if ($time < time()) {
92: if (!@unlink($file)) {
93: clearstatcache(false, $file);
94: }
95: }
96: }
97: }
98: }
99: }
100: