Repository navigation
Expand file tree
/
Copy pathMemoryCache.php
More file actions
139 lines (119 loc) · 2.88 KB
/
Copy pathMemoryCache.php
File metadata and controls
139 lines (119 loc) · 2.88 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php namespace October\Rain\Database;
/**
* Query memory cache class.
*
* Stores query results in memory to avoid running duplicate queries
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
class MemoryCache
{
use \October\Rain\Support\Traits\Singleton;
/**
* Cached results.
*
* @var array
*/
protected $cache = [];
/**
* The mapper between hashed keys and table names.
*
* @var array
*/
protected $tableMap = [];
/**
* @var bool Store enabled state.
*/
protected $enabled = true;
/**
* Check if the memory cache is enabled.
*
* @return bool
*/
public function enabled($switch = null)
{
if ($switch !== null) {
$this->enabled = $switch;
}
return $this->enabled;
}
/**
* Check if the given query is cached.
*
* @param QueryBuilder $query
* @return bool
*/
public function has(QueryBuilder $query)
{
return $this->enabled && isset($this->cache[$this->hash($query)]);
}
/**
* Get the cached results for the given query.
*
* @param QueryBuilder $query
* @return array|null
*/
public function get(QueryBuilder $query)
{
if ($this->has($query)) {
return $this->cache[$this->hash($query)];
}
return null;
}
/**
* Store the results for the given query.
*
* @param QueryBuilder $query
* @param array $results
* @return void
*/
public function put(QueryBuilder $query, array $results)
{
if (!$this->enabled) {
return;
}
$hash = $this->hash($query);
$this->cache[$hash] = $results;
$this->tableMap[(string) $query->from][] = $hash;
}
/**
* Delete the cache for the given table.
*
* @param $table
*/
public function forget($table)
{
if (!isset($this->tableMap[$table])) {
return;
}
foreach ($this->tableMap[$table] as $hash) {
unset($this->cache[$hash]);
}
unset($this->tableMap[$table]);
}
/**
* Clear the memory cache.
*/
public function flush()
{
$this->cache = [];
$this->tableMap = [];
}
/**
* Calculate a hash key for the given query.
*
* @param QueryBuilder $query
* @return string
*/
protected function hash(QueryBuilder $query)
{
// First we will cast all bindings to string, so we can ensure the same
// hash format regardless of the binding type provided by the user.
$bindings = array_map(function($binding) {
return (string) $binding;
}, $query->getBindings());
$name = $query->getConnection()->getName();
return md5($name . $query->toSql() . serialize($bindings));
}
}