Repository navigation
Expand file tree
/
Copy pathManager.php
More file actions
260 lines (221 loc) · 7.64 KB
/
Copy pathManager.php
File metadata and controls
260 lines (221 loc) · 7.64 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
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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\ModelCache;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Database\Model\Collection;
use Hyperf\DbConnection\Collector\TableCollector;
use Hyperf\DbConnection\Model\Model;
use Hyperf\ModelCache\Handler\HandlerInterface;
use Hyperf\ModelCache\Handler\RedisHandler;
use Psr\Container\ContainerInterface;
class Manager
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var HandlerInterface[]
*/
protected $handlers = [];
/**
* @var StdoutLoggerInterface
*/
protected $logger;
/**
* @var TableCollector
*/
protected $collector;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->logger = $container->get(StdoutLoggerInterface::class);
$this->collector = $container->get(TableCollector::class);
$config = $container->get(ConfigInterface::class);
if (! $config->has('databases')) {
throw new \InvalidArgumentException('config databases is not exist!');
}
foreach ($config->get('databases') as $key => $item) {
$handlerClass = $item['cache']['handler'] ?? RedisHandler::class;
$config = new Config($item['cache'] ?? [], $key);
/** @var HandlerInterface $handler */
$handler = make($handlerClass, ['config' => $config]);
$this->handlers[$key] = $handler;
}
}
/**
* Fetch a model from cache.
* @param mixed $id
*/
public function findFromCache($id, string $class): ?Model
{
/** @var Model $instance */
$instance = new $class();
$name = $instance->getConnectionName();
$primaryKey = $instance->getKeyName();
if ($handler = $this->handlers[$name] ?? null) {
$key = $this->getCacheKey($id, $instance, $handler->getConfig());
$data = $handler->get($key);
if ($data) {
return $instance->newFromBuilder(
$this->getAttributes($handler->getConfig(), $instance, $data)
);
}
// Fetch it from database, because it not exist in cache handler.
if (is_null($data)) {
$model = $instance->newQuery()->where($primaryKey, '=', $id)->first();
if ($model) {
$ttl = $handler->getConfig()->getTtl();
$handler->set($key, $this->formatModel($model), $ttl);
} else {
$ttl = $handler->getConfig()->getEmptyModelTtl();
$handler->set($key, [], $ttl);
}
return $model;
}
// It not exist in cache handler and database.
return null;
}
$this->logger->alert('Cache handler not exist, fetch data from database.');
return $instance->newQuery()->where($primaryKey, '=', $id)->first();
}
/**
* Fetch many models from cache.
*/
public function findManyFromCache(array $ids, string $class): Collection
{
if (count($ids) === 0) {
return new Collection([]);
}
/** @var Model $instance */
$instance = new $class();
$name = $instance->getConnectionName();
$primaryKey = $instance->getKeyName();
if ($handler = $this->handlers[$name] ?? null) {
$keys = [];
foreach ($ids as $id) {
$keys[] = $this->getCacheKey($id, $instance, $handler->getConfig());
}
$data = $handler->getMultiple($keys);
$items = [];
$fetchIds = [];
foreach ($data ?? [] as $item) {
if (isset($item[$primaryKey])) {
$items[] = $item;
$fetchIds[] = $item[$primaryKey];
}
}
// Get ids that not exist in cache handler.
$targetIds = array_diff($ids, $fetchIds);
if ($targetIds) {
$models = $instance->newQuery()->whereIn($primaryKey, $targetIds)->get();
$ttl = $handler->getConfig()->getTtl();
/** @var Model $model */
foreach ($models as $model) {
$id = $model->getKey();
$key = $this->getCacheKey($id, $instance, $handler->getConfig());
$handler->set($key, $this->formatModel($model), $ttl);
}
$items = array_merge($items, $this->formatModels($models));
}
$map = [];
foreach ($items as $item) {
$map[$item[$primaryKey]] = $this->getAttributes($handler->getConfig(), $instance, $item);
}
$result = [];
foreach ($ids as $id) {
if (isset($map[$id])) {
$result[] = $map[$id];
}
}
return $instance->hydrate($result);
}
$this->logger->alert('Cache handler not exist, fetch data from database.');
return $instance->newQuery()->whereIn($primaryKey, $ids)->get();
}
/**
* Destroy the models for the given IDs from cache.
* @param mixed $ids
*/
public function destroy($ids, string $class): bool
{
/** @var Model $instance */
$instance = new $class();
$name = $instance->getConnectionName();
if ($handler = $this->handlers[$name] ?? null) {
$keys = [];
foreach ($ids as $id) {
$keys[] = $this->getCacheKey($id, $instance, $handler->getConfig());
}
return $handler->deleteMultiple($keys);
}
return false;
}
/**
* Increment a column's value by a given amount.
* @param mixed $id
* @param mixed $column
* @param mixed $amount
*/
public function increment($id, $column, $amount, string $class): bool
{
/** @var Model $instance */
$instance = new $class();
$name = $instance->getConnectionName();
if ($handler = $this->handlers[$name] ?? null) {
$key = $this->getCacheKey($id, $instance, $handler->getConfig());
if ($handler->has($key)) {
return $handler->incr($key, $column, $amount);
}
return false;
}
$this->logger->alert('Cache handler not exist, increment failed.');
return false;
}
/**
* @param $id
*/
protected function getCacheKey($id, Model $model, Config $config): string
{
// mc:$prefix:m:$model:$pk:$id
return sprintf(
$config->getCacheKey(),
$config->getPrefix(),
$model->getTable(),
$model->getKeyName(),
$id
);
}
protected function formatModel(Model $model): array
{
return $model->getAttributes();
}
protected function formatModels($models): array
{
$result = [];
foreach ($models as $model) {
$result[] = $this->formatModel($model);
}
return $result;
}
protected function getAttributes(Config $config, Model $model, array $data)
{
if (! $config->isUseDefaultValue()) {
return $data;
}
$defaultData = $this->collector->getDefaultValue(
$model->getConnectionName(),
$model->getTable()
);
return array_replace($defaultData, $data);
}
}