/
RelationBehavior.php
776 lines (688 loc) · 25.7 KB
/
RelationBehavior.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
<?php
/**
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace notamedia\relation;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\base\ModelEvent;
use yii\db\ActiveQuery;
use yii\db\ActiveQueryInterface;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use Yii;
/**
* Behavior for support relational data management.
*
* - Insert related models from POST array.
* - Pre-processing for new models via callback function.
* - Delete related models from database which not exist in POST array.
* - Skip related models which already exist in database with same attributes.
* - Rollback database changes, if relational model save/delete error occurred.
* - Support one-to-one, one-to-many and many-to-many relations.
*
* With pre-processing you can set additional logic before create related models.
* For example, to add additional columns data to the junction table in a many-to-many relationship.
*
* This behavior uses getters for relational attribute in owner model, such getters must return `ActiveQuery` object.
* If you use string values in ON condition in `ActiveQuery` object, then this behavior will throw exception.
*
* For support transactions method transactions() in owner model must be defined:
* ```php
* <?php
*
* public function transactions()
* {
* return [
* 'default' => static::OP_ALL
* ];
* }
* ```
*
* @property ActiveRecord $owner
* @property array $relations
*/
class RelationBehavior extends Behavior
{
/**
* ```php
* 'relations' => [
* 'categories' => function (EntityHasCategory $model, $modelId) use (&$index) {
* $model->sort = ++$index;
* return $model;
* },
* 'industry' => function (EntityHasIndustry $model, $modelId) {
* $model->industry_code = 'prefix_' . $modelId;
* return $model;
* },
* 'users',
* ]
* ```
*
* @var array Array of relation fields with callback-functions for new models pre-processing.
*/
public $relations;
/**
* @var array Relation attributes list.
*/
protected $relationalFields = [];
/**
* @var bool Indices finish of all saving operations.
*/
protected $relationalFinished = false;
/**
* @var array Relation attributes data.
*/
protected $relationalData = [];
/**
* @throws InvalidConfigException
*/
public function init()
{
parent::init();
if ($this->relations) {
$keys = array_keys($this->relations);
$values = array_values($this->relations);
foreach ($values as $index => $value) {
if (is_string($value)) {
$this->relationalFields[$value] = [];
} else if (is_callable($value)) {
$this->relationalFields[$keys[$index]] = $value;
} else {
throw new InvalidConfigException(
sprintf(
'Element at index "%s", must be string or callable, %s given.', $index, gettype($value)
)
);
}
}
}
}
/**
* Process owner-model before save event.
*
* @param ModelEvent $event object of event called by model
*/
public function beforeSave($event)
{
$this->loadData();
$event->isValid = $this->validateData();
}
/**
* Return relation data of attribute
* @param $attribute string
* @return mixed|null
*/
public function getRelationData($attribute)
{
return isset($this->relationalData[$attribute]) ? $this->relationalData[$attribute]['data'] : null;
}
/**
* Return saving state of relation data finished or not. It's will finished after all relations models will saved.
* @return bool
*/
public function isRelationalFinished()
{
return $this->relationalFinished;
}
/**
* Process owner-model after save event. Save models.
*/
public function afterSave()
{
$this->saveData();
}
/**
* Permission for this behavior to set relational attributes.
*
* {@inheritdoc}
*/
public function canSetProperty($name, $checkVars = true)
{
return array_key_exists($name, $this->relationalFields) || parent::canSetProperty($name, $checkVars);
}
/**
* Setter for relational attributes. Called only if attribute is exist in POST array. Method check value format
* and put it to $this->relationalData array.
*
* {@inheritdoc}
*/
public function __set($name, $value)
{
if (array_key_exists($name, $this->relationalFields)) {
if (!is_array($value) && !empty($value)) {
$this->owner->addError($name,
Yii::$app->getI18n()->format(
Yii::t('yii', '{attribute} is invalid.'),
['attribute' => $this->owner->getAttributeLabel($name)],
Yii::$app->language
)
);
} else {
$this->relationalData[$name] = ['data' => $value];
}
} else {
parent::__set($name, $value);
}
}
/**
* Load relational data from owner-model getter.
*
* - Create related ActiveRecord objects from POST array data.
* - Load existing related ActiveRecord objects from database.
* - Check ON condition format.
* - Get ActiveQuery object from attribute getter method.
*
* Fill $this->relationalData array for each relational attribute:
*
* ```php
* $this->relationalData[$attribute] = [
* 'newModels' => ActiveRecord[],
* 'oldModels' => ActiveRecord[],
* 'activeQuery' => ActiveQuery,
* ];
* ```
*
* @throws RelationException
*/
protected function loadData()
{
/** @var ActiveQuery $activeQuery */
foreach ($this->relationalData as $attribute => &$data) {
$getter = 'get' . ucfirst($attribute);
$data['activeQuery'] = $activeQuery = $this->owner->$getter();
$data['newModels'] = [];
$data['oldModels'] = [];
$data['newRows'] = [];
$data['oldRows'] = [];
if (!$this->validateOnCondition($activeQuery)) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('ON condition for attribute ' . $attribute . ' must be associative array');
}
if ($activeQuery->multiple) {
if (empty($activeQuery->via)) { // one-to-many
$this->loadModelsOneToMany($attribute);
} else { // many-to-many
if ($activeQuery->via instanceof ActiveQueryInterface) { // viaTable
$this->loadModelsManyToManyViaTable($attribute);
} else { // via
$this->loadModelsManyToManyVia($attribute);
}
}
} elseif (!empty($data['data'])) {
// one-to-one
$this->loadModelsOneToOne($attribute);
}
if (empty($activeQuery->via)) {
$data['oldModels'] = $activeQuery->all();
}
unset($data['data']);
foreach ($data['newModels'] as $i => $model) {
$data['newModels'][$i] = $this->replaceExistingModel($model, $attribute);
}
}
}
/**
* Validate relational models, return true only if all models successfully validated. Skip errors for foreign
* columns.
*
* @return bool
*/
protected function validateData()
{
foreach ($this->relationalData as $attribute => &$data) {
/** @var ActiveRecord $model */
/** @var ActiveQuery $activeQuery */
$activeQuery = $data['activeQuery'];
foreach ($data['newModels'] as &$model) {
if (!$model->validate()) {
$_errors = $model->getErrors();
$errors = [];
foreach ($_errors as $relatedAttribute => $error) {
if (!$activeQuery->multiple || !isset($activeQuery->link[$relatedAttribute])) {
$errors[$relatedAttribute] = $error;
}
}
if (count($errors)) {
$this->owner->addError($attribute, $errors);
return false;
}
}
}
}
return true;
}
/**
* Save changed related models.
*
* - Delete old related models, which not exist in POST array.
* - Create new related models, which not exist in database.
* - Update owner models for one-to-one relation.
*/
public function saveData()
{
$needSaveOwner = false;
foreach ($this->relationalData as $attribute => $data) {
// delete models
$this->deleteModels($attribute);
// save models
$this->saveModels($attribute);
if (!$data['activeQuery']->multiple && (count($data['newModels']) == 0 || !$data['newModels'][0]->isNewRecord)) {
$needSaveOwner = true;
foreach ($data['activeQuery']->link as $childAttribute => $parentAttribute) {
$this->owner->$parentAttribute = count($data['newModels']) ? $data['newModels'][0]->$childAttribute : null;
}
}
}
$this->relationalFinished = true;
if ($needSaveOwner) {
$model = $this->owner;
$this->detach();
if (!$model->save()) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('Owner-model ' . $model::className() . ' not saved due to unknown error');
}
}
}
/**
* Execute callback for each relation
*
* - if error occurred throws exception
*
* @param array $relations
* @param callable $callback
* @throws RelationException
*/
protected function relationsMap($relations, $callback)
{
try {
if (is_callable($callback)) {
array_map($callback, $relations);
}
} catch (\Exception $e) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('Owner-model not saved due to unknown error');
}
}
/**
* Return existing model if it found in old models
*
* @param ActiveRecord $model
* @param $attribute
*
* @return ActiveRecord
*/
protected function replaceExistingModel($model, $attribute)
{
$modelAttributes = $model->attributes;
unset($modelAttributes[$model->primaryKey()[0]]);
foreach ($this->relationalData[$attribute]['oldModels'] as $oldModel) {
/** @var ActiveRecord $oldModel */
$oldModelAttributes = $oldModel->attributes;
unset($oldModelAttributes[$oldModel->primaryKey()[0]]);
if ($oldModelAttributes == $modelAttributes) {
return $oldModel;
}
}
return $model;
}
/**
* Check existing row if it found in old rows
*
* @param $row
* @param $attribute
* @return mixed
*/
protected function isExistingRow($row, $attribute)
{
$rowAttributes = $row;
unset($rowAttributes[$this->relationalData[$attribute]['junctionColumn']]);
foreach ($this->relationalData[$attribute]['oldRows'] as $oldRow) {
$oldModelAttributes = $oldRow;
unset($oldModelAttributes[$this->relationalData[$attribute]['junctionColumn']]);
if ($oldModelAttributes == $rowAttributes) {
return true;
}
}
return false;
}
/**
* Check if model was deleted (not found in new models).
*
* @param ActiveRecord $model
* @param $attribute
*
* @return bool
*/
protected function isDeletedModel($model, $attribute)
{
$modelAttributes = $model->attributes;
unset($modelAttributes[$model->primaryKey()[0]]);
foreach ($this->relationalData[$attribute]['newModels'] as $newModel) {
/** @var ActiveRecord $newModel */
$newModelAttributes = $newModel->attributes;
unset($newModelAttributes[$newModel->primaryKey()[0]]);
if ($newModelAttributes == $modelAttributes) {
return false;
}
}
return true;
}
/**
* Check if row was deleted (not found in new rows).
*
* @param $row
* @param $attribute
* @return bool
*/
protected function isDeletedRow($row, $attribute)
{
$rowAttribute = $row;
unset($rowAttribute[$this->relationalData[$attribute]['junctionColumn']]);
foreach ($this->relationalData[$attribute]['newRows'] as $newRow) {
$newRowAttributes = $newRow;
unset($newRowAttributes[$this->relationalData[$attribute]['junctionColumn']]);
if ($newRowAttributes == $rowAttribute) {
return false;
}
}
return true;
}
/**
* Delete related models. Rollback transaction and throw RelationException, if error occurred while deleting.
*/
public function afterDelete()
{
foreach ($this->relationalFields as $attribute => $value) {
$getter = 'get' . ucfirst($attribute);
/** @var ActiveQuery $activeQuery */
$activeQuery = $this->owner->$getter();
$models = [];
if (empty($activeQuery->via)) {
$models = $activeQuery->all();
} else {
if ($activeQuery->via instanceof ActiveQueryInterface) { // viaTable
$junctionTable = $activeQuery->via->from[0];
list($junctionColumn) = array_keys($activeQuery->via->link);
list($relatedColumn) = array_values($activeQuery->link);
$rows = (new Query())
->from($junctionTable)
->select([
$junctionColumn,
$relatedColumn
])
->where([
$junctionColumn => $this->owner->getPrimaryKey(),
])->all();
$this->relationsMap($rows, function($row) use ($junctionTable) {
Yii::$app->db->createCommand()
->delete($junctionTable, $row)
->execute();
});
} else { // via
$junctionGetter = 'get' . ucfirst($activeQuery->via[0]);
$models = $this->owner->$junctionGetter()->all();
}
}
foreach ($models as $model) {
if (!$model->delete()) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('Model ' . $model::className() . ' not deleted due to unknown error');
}
}
}
}
/**
* Validate ON condition in ActiveQuery
*
* @param ActiveQuery $activeQuery
* @return bool
*/
protected function validateOnCondition($activeQuery)
{
if (
!ArrayHelper::isAssociative($activeQuery->on) &&
!empty($activeQuery->on)
) {
return false;
}
if (
$activeQuery->multiple &&
!empty($activeQuery->via) &&
is_array($activeQuery->via) &&
is_object($activeQuery->via[1]) &&
!ArrayHelper::isAssociative($activeQuery->via[1]->on) &&
!empty($activeQuery->via[1]->on)
) {
return false;
}
return true;
}
/**
* Load new model from POST for one-to-one relation
*
* @param $attribute
*/
protected function loadModelsOneToOne($attribute)
{
$data = $this->relationalData[$attribute];
$activeQuery = $data['activeQuery'];
$class = $activeQuery->modelClass;
$model = new $class($data['data']);
if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
$model = call_user_func($this->relations[$attribute], $model, $data['data']);
}
$data['newModels'][] = $model;
$this->relationalData[$attribute] = $data;
}
/**
* Load new models from POST for one-to-many relation
*
* @param $attribute
*/
protected function loadModelsOneToMany($attribute)
{
$data = $this->relationalData[$attribute];
$activeQuery = $data['activeQuery'];
$class = $activeQuery->modelClass;
// default query conditions
$params = !ArrayHelper::isAssociative($activeQuery->on) ? [] : $activeQuery->on;
// one-to-many
foreach ($activeQuery->link as $childAttribute => $parentAttribute) {
$params[$childAttribute] = $this->owner->$parentAttribute;
}
if (!empty($data['data'])) {
foreach ($data['data'] as $attributes) {
$model = new $class(
array_merge(
$params,
ArrayHelper::isAssociative($attributes) ? $attributes : []
)
);
if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
$model = call_user_func($this->relations[$attribute], $model, $attributes);
}
$data['newModels'][] = $model;
}
}
$this->relationalData[$attribute] = $data;
}
/**
* Load new models from POST for many-to-many relation with viaTable
*
* @param $attribute
* @throws RelationException
*/
protected function loadModelsManyToManyViaTable($attribute)
{
$data = $this->relationalData[$attribute];
$activeQuery = $data['activeQuery'];
/** @var ActiveRecord $class */
$class = $activeQuery->modelClass;
$via = $activeQuery->via;
$data['junctionTable'] = $via->from[0];
list($data['junctionColumn']) = array_keys($via->link);
list($data['relatedColumn']) = array_values($activeQuery->link);
$junctionColumn = $data['junctionColumn'];
$relatedColumn = $data['relatedColumn'];
if (!empty($data['data'])) {
// make sure what all row's ids from POST exists in database
$countManyToManyModels = $class::find()->where([$class::primaryKey()[0] => $data['data']])->count();
if ($countManyToManyModels != count($data['data'])) {
throw new RelationException('Related records for attribute ' . $attribute . ' not found');
}
// create new junction rows
foreach ($data['data'] as $relatedModelId) {
$junctionModel = array_merge(
!ArrayHelper::isAssociative($via->on) ? [] : $via->on,
[$junctionColumn => $this->owner->getPrimaryKey()]
);
$junctionModel[$relatedColumn] = $relatedModelId;
if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
$junctionModel = call_user_func($this->relations[$attribute], $junctionModel, $relatedModelId);
}
$data['newRows'][] = $junctionModel;
}
}
if (!empty($this->owner->getPrimaryKey())) {
$data['oldRows'] = (new Query())
->from($data['junctionTable'])
->select(array_merge(
[$junctionColumn, $relatedColumn],
!ArrayHelper::isAssociative($via->on) ? [] : array_keys($via->on))
)->where(array_merge(
!ArrayHelper::isAssociative($via->on) ? [] : $via->on,
[$junctionColumn => $this->owner->getPrimaryKey()]
))->all();
}
$this->relationalData[$attribute] = $data;
}
/**
* Load new models from POST for many-to-many relation with via
*
* @param $attribute
* @throws RelationException
*/
protected function loadModelsManyToManyVia($attribute)
{
$data = $this->relationalData[$attribute];
$activeQuery = $data['activeQuery'];
/** @var ActiveRecord $class */
$class = $activeQuery->modelClass;
if (!is_object($activeQuery->via[1])) {
throw new RelationException('via condition for attribute ' . $attribute . ' cannot must be object');
}
$via = $activeQuery->via[1];
$junctionGetter = 'get' . ucfirst($activeQuery->via[0]);
/** @var ActiveRecord $junctionModelClass */
$data['junctionModelClass'] = $junctionModelClass = $via->modelClass;
$data['junctionTable'] = $junctionModelClass::tableName();
list($data['junctionColumn']) = array_keys($via->link);
list($data['relatedColumn']) = array_values($activeQuery->link);
$junctionColumn = $data['junctionColumn'];
$relatedColumn = $data['relatedColumn'];
if (!empty($data['data'])) {
// make sure what all model's ids from POST exists in database
$countManyToManyModels = $class::find()->where([$class::primaryKey()[0] => $data['data']])->count();
if ($countManyToManyModels != count($data['data'])) {
throw new RelationException('Related records for attribute ' . $attribute . ' not found');
}
// create new junction models
foreach ($data['data'] as $relatedModelId) {
$junctionModel = new $junctionModelClass(
array_merge(
!ArrayHelper::isAssociative($via->on) ? [] : $via->on,
[$junctionColumn => $this->owner->getPrimaryKey()]
)
);
$junctionModel->$relatedColumn = $relatedModelId;
if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
$junctionModel = call_user_func($this->relations[$attribute], $junctionModel, $relatedModelId);
}
$data['newModels'][] = $junctionModel;
}
}
$data['oldModels'] = $this->owner->$junctionGetter()->all();
$this->relationalData[$attribute] = $data;
}
/**
* Save all new models for attribute
*
* @param $attribute
* @throws RelationException
*/
protected function saveModels($attribute)
{
$data = $this->relationalData[$attribute];
/** @var ActiveRecord $model */
foreach ($data['newModels'] as $model) {
if ($model->isNewRecord) {
if (!empty($data['activeQuery']->via)) {
// only for many-to-many
$junctionColumn = $data['junctionColumn'];
$model->$junctionColumn = $this->owner->getPrimaryKey();
} elseif ($data['activeQuery']->multiple) {
// only one-to-many
foreach ($data['activeQuery']->link as $childAttribute => $parentAttribute) {
$model->$childAttribute = $this->owner->$parentAttribute;
}
}
if (!$model->save()) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('Model ' . $model::className() . ' not saved due to unknown error');
}
}
}
// only for many-to-many
$this->relationsMap($data['newRows'], function($row) use ($attribute, $data) {
$junctionColumn = $data['junctionColumn'];
$row[$junctionColumn] = $this->owner->getPrimaryKey();
if (!$this->isExistingRow($row, $attribute)) {
Yii::$app->db->createCommand()
->insert($data['junctionTable'], $row)
->execute();
}
});
}
/**
* Delete all old models for attribute if it needed
*
* @param $attribute
* @throws RelationException
*/
protected function deleteModels($attribute)
{
$data = $this->relationalData[$attribute];
/** @var ActiveRecord $model */
foreach ($data['oldModels'] as $model) {
if ($this->isDeletedModel($model, $attribute)) {
if (!$model->delete()) {
Yii::$app->getDb()->getTransaction()->rollBack();
throw new RelationException('Model ' . $model::className() . ' not deleted due to unknown error');
}
}
}
$this->relationsMap($data['oldRows'], function($row) use ($attribute, $data) {
if ($this->isDeletedRow($row, $attribute)) {
Yii::$app->db->createCommand()
->delete($data['junctionTable'], $row)
->execute();
}
});
}
/**
* {@inheritdoc}
*/
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
];
}
}