-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAbstractCachedTable.php
295 lines (272 loc) · 8.44 KB
/
AbstractCachedTable.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
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
<?php declare(strict_types=1);
namespace Composite\DB;
use Composite\Entity\AbstractEntity;
use Psr\SimpleCache\CacheInterface;
use Ramsey\Uuid\UuidInterface;
abstract class AbstractCachedTable extends AbstractTable
{
use Helpers\SelectRawTrait;
protected const CACHE_VERSION = 1;
public function __construct(
protected CacheInterface $cache,
) {
parent::__construct();
}
/**
* @return string[]
*/
abstract protected function getFlushCacheKeys(AbstractEntity $entity): array;
/**
* @throws \Throwable
*/
public function save(AbstractEntity $entity): void
{
$cacheKeys = $this->collectCacheKeysByEntity($entity);
parent::save($entity);
if ($cacheKeys) {
$this->cache->deleteMultiple($cacheKeys);
}
}
/**
* @param AbstractEntity[] $entities
* @throws \Throwable
*/
public function saveMany(array $entities): void
{
$cacheKeys = [];
foreach ($entities as $entity) {
$cacheKeys = array_merge($cacheKeys, $this->collectCacheKeysByEntity($entity));
}
parent::saveMany($entities);
if ($cacheKeys) {
$this->cache->deleteMultiple(array_unique($cacheKeys));
}
}
/**
* @throws \Throwable
*/
public function delete(AbstractEntity $entity): void
{
$cacheKeys = $this->collectCacheKeysByEntity($entity);
parent::delete($entity);
if ($cacheKeys) {
$this->cache->deleteMultiple($cacheKeys);
}
}
/**
* @param AbstractEntity[] $entities
* @throws \Throwable
*/
public function deleteMany(array $entities): void
{
$cacheKeys = [];
foreach ($entities as $entity) {
$cacheKeys = array_merge($cacheKeys, $this->collectCacheKeysByEntity($entity));
parent::delete($entity);
}
parent::deleteMany($entities);
if ($cacheKeys) {
$this->cache->deleteMultiple($cacheKeys);
}
}
/**
* @param AbstractEntity $entity
* @return string[]
*/
private function collectCacheKeysByEntity(AbstractEntity $entity): array
{
$keys = $this->getFlushCacheKeys($entity);
if (!$entity->isNew() || !$this->getConfig()->autoIncrementKey) {
$keys[] = $this->getOneCacheKey($entity);
}
return array_unique($keys);
}
/**
* @return AbstractEntity|null
*/
protected function _findByPkCached(mixed $pk, null|int|\DateInterval $ttl = null): mixed
{
return $this->_findOneCached($this->getPkCondition($pk), $ttl);
}
/**
* @param array<string, mixed> $where
* @param int|\DateInterval|null $ttl
* @return AbstractEntity|null
*/
protected function _findOneCached(array $where, null|int|\DateInterval $ttl = null): mixed
{
$row = $this->getCached(
$this->getOneCacheKey($where),
fn() => $this->_findOneRaw($where),
$ttl,
);
return $this->createEntity($row);
}
/**
* @param array<string, mixed>|Where $where
* @param array<string, string>|string $orderBy
* @return array<AbstractEntity>|array<array-key, AbstractEntity>
*/
protected function _findAllCached(
array|Where $where = [],
array|string $orderBy = [],
?int $limit = null,
null|int|\DateInterval $ttl = null,
?string $keyColumnName = null,
): array
{
$rows = $this->getCached(
$this->getListCacheKey($where, $orderBy, $limit),
fn() => $this->_findAllRaw(where: $where, orderBy: $orderBy, limit: $limit),
$ttl,
);
return $this->createEntities($rows, $keyColumnName);
}
/**
* @param array<string, mixed>|Where $where
*/
protected function _countByAllCached(
array|Where $where = [],
null|int|\DateInterval $ttl = null,
): int
{
return (int)$this->getCached(
$this->getCountCacheKey($where),
fn() => $this->_countAll(where: $where),
$ttl,
);
}
protected function getCached(string $cacheKey, callable $dataCallback, null|int|\DateInterval $ttl = null): mixed
{
$data = $this->cache->get($cacheKey);
if ($data !== null) {
return $data;
}
$data = $dataCallback();
if ($data !== null) {
$this->cache->set($cacheKey, $data, $ttl);
}
return $data;
}
/**
* @param mixed[] $ids
* @param int|\DateInterval|null $ttl
* @return array<AbstractEntity>|array<array-key, AbstractEntity>
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
protected function _findMultiCached(
array $ids,
null|int|\DateInterval $ttl = null,
?string $keyColumnName = null,
): array
{
$result = $cacheKeys = $foundIds = [];
foreach ($ids as $id) {
$cacheKey = $this->getOneCacheKey($id);
$cacheKeys[$cacheKey] = $id;
}
$cache = $this->cache->getMultiple(array_keys($cacheKeys));
foreach ($cache as $cacheKey => $cachedRow) {
if ($cachedRow === null) {
continue;
}
if (isset($cacheKeys[$cacheKey])) {
$result[] = $cachedRow;
$foundIds[] = $cacheKeys[$cacheKey];
}
}
$ids = array_diff($ids, $foundIds);
foreach ($ids as $id) {
if ($row = $this->_findByPkCached($id, $ttl)) {
$result[] = $row;
}
}
return $this->createEntities($result, $keyColumnName);
}
/**
* @param string|int|array<string, mixed>|AbstractEntity $keyOrEntity
*/
protected function getOneCacheKey(string|int|array|AbstractEntity|UuidInterface $keyOrEntity): string
{
if (!is_array($keyOrEntity)) {
$condition = $this->getPkCondition($keyOrEntity);
} else {
$condition = $keyOrEntity;
}
return $this->buildCacheKey('o', $condition ?: 'one');
}
/**
* @param array<string, mixed>|Where $where
* @param array<string, string>|string $orderBy
*/
protected function getListCacheKey(
array|Where $where = [],
array|string $orderBy = [],
?int $limit = null
): string
{
$wherePart = is_array($where) ? $where : $this->prepareWhereKey($where);
return $this->buildCacheKey(
'l',
$wherePart ?: 'all',
$orderBy ? ['ob' => $orderBy] : null,
$limit ? ['limit' => $limit] : null,
);
}
/**
* @param array<string, mixed>|Where $where
*/
protected function getCountCacheKey(
array|Where $where = [],
): string
{
$wherePart = is_array($where) ? $where : $this->prepareWhereKey($where);
return $this->buildCacheKey(
'c',
$wherePart ?: 'all',
);
}
protected function buildCacheKey(mixed ...$parts): string
{
$parts = array_filter($parts);
if ($parts) {
$formattedParts = [];
foreach ($parts as $part) {
if (is_array($part)) {
$string = json_encode($part, JSON_THROW_ON_ERROR);
} else {
$string = strval($part);
}
$formattedParts[] = $this->formatStringForCacheKey($string);
}
$key = implode('.', $formattedParts);
} else {
$key = 'all';
}
$key = implode('.', [
$this->getConnectionName(),
$this->getTableName(),
'v' . static::CACHE_VERSION,
$key
]);
if (strlen($key) > 64) {
$key = sha1($key);
}
return $key;
}
private function formatStringForCacheKey(string $string): string
{
$string = strtolower($string);
$string = str_replace(['!=', '<>', '>', '<', '='], ['_not_', '_not_', '_gt_', '_lt_', '_eq_'], $string);
$string = (string)preg_replace('/\W/', '_', $string);
return trim((string)preg_replace('/_+/', '_', $string), '_');
}
private function prepareWhereKey(Where $where): string
{
return str_replace(
array_map(fn (string $key): string => ':' . $key, array_keys($where->params)),
array_values($where->params),
$where->condition,
);
}
}