-
Notifications
You must be signed in to change notification settings - Fork 1
/
NetteDatabaseStorage.php
99 lines (79 loc) · 1.8 KB
/
NetteDatabaseStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Nette\Caching\Storages;
use Nette\Database\Context;
use Nette\Caching\Cache;
/**
* Nette database storage.
* Database table must contain columns `key` BIGINT, `value` BLOB. See cache.sql file.
*/
class DatabaseStorage extends \Nette\Object implements \Nette\Caching\IStorage
{
/** @var Context */
private $db;
/** @var string */
private $table;
/**
* @param Context $db
* @param string $table
* @throws \Nette\MemberAccessException
*/
public function __construct(Context $db, $table = 'cache')
{
$this->db = $db;
$this->table = $table;
}
/**
* @param string $key
* @return mixed
*/
public function read($key)
{
$key = $this->encodeKey($key);
$data = $this->db->table($this->table)->where('key', $key)->fetch('value');
if (isset($data['value'])) {
return unserialize($data['value']);
}
}
/**
* @param string $key
* @param mixed $data
* @param array $dependencies
*/
public function write($key, $data, array $dependencies)
{
$key = $this->encodeKey($key);
$exists = $this->db->table($this->table)->where('key', $key)->update(['value' => serialize($data)]);
if (!$exists) {
$this->db->table($this->table)->insert([
'key' => $key,
'value' => serialize($data),
]);
}
}
/**
* @param string $key
*/
public function remove($key)
{
$key = $this->encodeKey($key);
$this->db->table($this->table)->where('key', $key)->delete();
}
/**
* @param array $conditions
*/
public function clean(array $conditions)
{
if (!empty($conditions[Cache::ALL])) {
$this->db->table($this->table)->delete();
}
}
public function lock($key)
{
$key = $this->encodeKey($key);
}
protected function encodeKey($key)
{
// converts key into 8 bytes SIGNED integer
return base_convert(substr(md5($key), 0, 16), 16, 10) - pow(2,63);
}
}