/
ArSyncBehavior.php
391 lines (363 loc) · 9.64 KB
/
ArSyncBehavior.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
/**
* Created by insolita [10.05.16 23:18]
*/
namespace insolita\arsync;
use Yii;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\db\ActiveRecordInterface;
use yii\db\Connection;
use yii\helpers\ArrayHelper;
/**
* This behavior for automatic or manual sync data between two models, without declaration relation
* This behavior must be attached on master model
* Support two-way binding (You can attach this on both model with correct fieldMap. ATTENTION! Behavior name must be
* exactly 'ArSyncBehavior' in both models!)
* This behavior provide syncAll() method for manual use (clear all data from slave model and refill with data
* from master model accordingly fieldMap rules)
*
* Main purposes - for sync rarely modified data from more reliable database storage to redis storage for
* frequently access; Support actual data state in some development cases;
*
* Suggest - @see http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html#transactions%28%29-detail
**/
class ArSyncBehavior extends Behavior
{
/**
* @var string $slaveModel modelClass which will be sync with owner
**/
public $slaveModel;
/**
* @var array $fieldMap - map between master and slave models; must be set as flat array
*
* if all models has equal field names and not need data modification
* @example
* 'fieldMap'=>['id','name','somevar']
* ----------------------------------------
* if fields not with equal name, configure map as hash, where keys - fieldNames of Slave model
* and values -> fieldNames of Master model
* @example
* 'fieldMap'=>[
* 'name' => 'orgname',
* 'created' => 'time'
* 'foo' => 'foo'
* ]
* -----------------------------------------
* if data need modification - use closure with argument - master model
* @example
* 'fieldMap'=>[
* 'foo' => 'foo',
* 'name' => function($master){ return strtolower($master->orgname); },
* 'delta' => function($master){ return $master->updated - $master->started; }
* 'bar' => 'baz'
* ]
*
**/
public $fieldMap = [];
/**
* scenario for operations with $slaveModel
*
* @var string $slaveScenario
*/
public $slaveScenario;
/**
* @var array $saveScenarios - list scenarios, when record must be sync (set empty for only manual
* synchronization)
**/
public $saveScenarios = ['default'];
/**
* @var array $deleteScenarios - list scenarios, when record must delete record from slave model (set empty for only
* manual synchronization)
**/
public $deleteScenarios = ['default'];
/**
* callback triggered if $slave model can`t saved with $slaveModel argument
*
* @example
* 'errorSaveCallback'=>function($slave){
* Yii::error(VarDumper::export($slave->errors));
* throw new InvalidConfigException('fail save ');
* }
* @var callable|\Closure $errorSaveCallback
**/
public $errorSaveCallback;
/**
* callback triggered if $slave model can`t deleted with slave model as argument? or null if slave not found by pk
*
* @see $errorSaveCallback comment
* @var callable|\Closure $errorDeleteCallback
**/
public $errorDeleteCallback;
/**
* Prepare fieldMap
*
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
$this->fieldMap = $this->prepareFieldMap($this->fieldMap);
}
/**
* @param $fieldMap
*
* @return mixed
* @throws InvalidConfigException
*/
protected function prepareFieldMap($fieldMap)
{
if (ArrayHelper::isIndexed($fieldMap))
{
return array_combine($fieldMap, $fieldMap);
}
if (!ArrayHelper::isAssociative($fieldMap))
{
throw new InvalidConfigException('Incorrect configuration for fieldMap property');
}
return $fieldMap;
}
/**
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_AFTER_INSERT => 'sync',
ActiveRecord::EVENT_AFTER_UPDATE => 'sync',
ActiveRecord::EVENT_AFTER_DELETE => 'syncDelete',
];
}
/**
* Sync current record
*/
public function sync()
{
if (!$this->checkIsAutoSyncEnabled())
{
return;
}
$master = $this->getOwner();
$this->syncRecord($master);
}
/**
* @return bool
**/
protected function checkIsAutoSyncEnabled()
{
return in_array($this->getOwner()->scenario, $this->saveScenarios);
}
/**
* @return ActiveRecord|ActiveRecordInterface
**/
public function getOwner()
{
return $this->owner;
}
/**
* @param ActiveRecordInterface|Model $master
*/
protected function syncRecord(ActiveRecordInterface $master)
{
/**@var ActiveRecordInterface|Model $slave * */
$slave = null;
if (!$master->getIsNewRecord())
{
$slave = $this->findSlaveByPk($master->getPrimaryKey());
}
if ($master->getIsNewRecord() or !$slave)
{
//if related slave not exists - create new slave too
$slave = $this->createNewSlave();
}
$hasArsync = $slave->getBehavior('ArSyncBehavior');
if ($hasArsync)
{
$slave->detachBehavior('ArSyncBehavior'); //prevent conflict if sync with two-way binding
}
if ($this->slaveScenario)
{
$slave->setScenario($this->slaveScenario);
}
$slave = $this->populateSlave($master, $slave, $this->fieldMap);
$this->saveSlave($slave);
if ($hasArsync)
{
$slave->attachBehavior('ArSyncBehavior', $hasArsync);
}
}
/**
* @param int|string $pk
*
* @return ActiveRecordInterface|Model|null
**/
protected function findSlaveByPk($pk)
{
return call_user_func([$this->slaveModel, 'findOne'], $pk);
}
/**
* @return ActiveRecordInterface|Model
*/
protected function createNewSlave()
{
return new $this->slaveModel;
}
/**
* @param ActiveRecordInterface $master
* @param ActiveRecordInterface $slave
* @param $fieldMap
*
* @return ActiveRecordInterface|Model $slave
*/
protected function populateSlave(ActiveRecordInterface $master, ActiveRecordInterface $slave, $fieldMap)
{
foreach ($fieldMap as $slaveKey => $masterKey)
{
if (is_callable($masterKey))
{
$slave->$slaveKey = call_user_func($masterKey, $master);
}
else
{
$slave->$slaveKey = $master->$masterKey;
}
}
return $slave;
}
/**
* @param ActiveRecordInterface $slave
*/
protected function saveSlave(ActiveRecordInterface $slave)
{
if (!$slave->save())
{
if ($this->errorSaveCallback !== null && is_callable([$this, 'errorSaveCallback']))
{
call_user_func($this->errorSaveCallback, $slave);
}
}
}
/**
* Remove slave record
*/
public function syncDelete()
{
if (!$this->checkIsAutoDeleteEnabled())
{
return;
}
$masterPk = $this->getOwner()->getPrimaryKey();
$slave = $this->findSlaveByPk($masterPk);
if ($slave)
{
$hasArsync = $slave->getBehavior('ArSyncBehavior');
if ($hasArsync)
{
$slave->detachBehavior('ArSyncBehavior'); //prevent conflict if sync with two-way binding
}
if ($this->slaveScenario and $slave->hasMethod('setScenario'))
{
$slave->setScenario($this->slaveScenario);
}
$this->deleteSlave($slave);
if ($hasArsync)
{
$slave->attachBehavior('ArSyncBehavior', $hasArsync);
}
}
elseif ($this->errorDeleteCallback !== null && is_callable($this->errorDeleteCallback))
{
\Yii::error('slave record not found by PK ' . $masterPk, get_called_class());
call_user_func($this->errorDeleteCallback, $slave);
}
}
/**
* @return bool
**/
protected function checkIsAutoDeleteEnabled()
{
return in_array($this->getOwner()->scenario, $this->deleteScenarios);
}
/**
* Delete slave record
*
* @param ActiveRecordInterface $slave
*/
protected function deleteSlave(ActiveRecordInterface $slave)
{
if ($slave->delete() == false)
{
if (is_callable($this->errorDeleteCallback))
{
call_user_func($this->errorDeleteCallback, $slave);
}
}
}
/**
* It`s manual method for fill slaveModel with data from Master model accordingly @see $fieldMap method
* It get each master record, check exists of slave record with same primary key and update existed, or create
* new slave
* It can be hard for database, if master model has many records
* Suggest use it with maintenance mode or in development
*
* @param int $batchRows - number of rows in batch mode (only if batch find supported by model storage)
* @param bool $clearSlave - if true - all slave records will deleted and table will be truncated if it`s possible
*/
public function syncAll($clearSlave = false, $batchRows = 50)
{
if ($clearSlave)
{
$this->clearSlave();
}
/**@var ActiveRecordInterface|Model $master * */
$master = $this->getOwner();
$finder = $master::find();
$masterIds = [];
if ($finder->hasMethod('batch'))
{
foreach ($finder->batch($batchRows) as $items)
{
foreach ($items as $item)
{
$masterIds[] = $item->getPrimaryKey();
$this->syncRecord($item);
}
}
}
else
{
foreach ($finder->all() as $item)
{
$masterIds[] = $item->getPrimaryKey();
$this->syncRecord($item);
}
}
if ($clearSlave == false && count($masterIds))
{
/**@var ActiveRecordInterface|Model $slave * */
$slave = new $this->slaveModel;
//Delete unexpected Slaves, not presented in master
$slave::deleteAll(['not in',$slave->primaryKey()[0], $masterIds]);
}
}
/**
* clear all data from slave and truncate table if it possible
**/
public function clearSlave()
{
/**@var ActiveRecordInterface|Model $slave */
$slave = new $this->slaveModel;
$slave::deleteAll();
$db = $slave::getDb();
if ($db instanceof Connection and $slave->hasMethod('tableName', false))
{
$db->createCommand()->truncateTable($slave::tableName());
if ($db->getDriverName() == 'pgsql')
{
$db->createCommand()->resetSequence($slave::tableName(), 1);
}
}
}
}