1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace lhs\Yii2SaveRelationsBehavior; |
4
|
|
|
|
5
|
|
|
use RuntimeException; |
6
|
|
|
use Yii; |
7
|
|
|
use yii\base\Behavior; |
8
|
|
|
use yii\base\Exception; |
9
|
|
|
use yii\base\ModelEvent; |
10
|
|
|
use yii\base\UnknownPropertyException; |
11
|
|
|
use yii\db\ActiveQueryInterface; |
12
|
|
|
use yii\db\BaseActiveRecord; |
13
|
|
|
use yii\db\Exception as DbException; |
14
|
|
|
use yii\db\Transaction; |
15
|
|
|
use yii\helpers\ArrayHelper; |
16
|
|
|
use yii\helpers\Inflector; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* This Active Record Behavior allows to validate and save the Model relations when the save() method is invoked. |
20
|
|
|
* List of handled relations should be declared using the $relations parameter via an array of relation names. |
21
|
|
|
* @author albanjubert |
22
|
|
|
*/ |
23
|
|
|
class SaveRelationsBehavior extends Behavior |
24
|
|
|
{ |
25
|
|
|
|
26
|
|
|
public $relations = []; |
27
|
|
|
private $_relations = []; |
28
|
|
|
private $_oldRelationValue = []; // Store initial relations value |
29
|
|
|
private $_newRelationValue = []; // Store update relations value |
30
|
|
|
private $_relationsSaveStarted = false; |
31
|
|
|
private $_transaction; |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
private $_relationsScenario = []; |
35
|
|
|
private $_relationsExtraColumns = []; |
36
|
|
|
|
37
|
|
|
//private $_relationsCascadeDelete = []; //TODO |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @inheritdoc |
41
|
|
|
*/ |
42
|
35 |
|
public function init() |
43
|
|
|
{ |
44
|
35 |
|
parent::init(); |
45
|
35 |
|
$allowedProperties = ['scenario', 'extraColumns']; |
46
|
35 |
|
foreach ($this->relations as $key => $value) { |
47
|
34 |
|
if (is_int($key)) { |
48
|
34 |
|
$this->_relations[] = $value; |
49
|
|
|
} else { |
50
|
28 |
|
$this->_relations[] = $key; |
51
|
28 |
|
if (is_array($value)) { |
52
|
28 |
|
foreach ($value as $propertyKey => $propertyValue) { |
53
|
28 |
|
if (in_array($propertyKey, $allowedProperties)) { |
54
|
28 |
|
$this->{'_relations' . ucfirst($propertyKey)}[$key] = $propertyValue; |
55
|
|
|
} else { |
56
|
28 |
|
throw new UnknownPropertyException('The relation property named ' . $propertyKey . ' is not supported'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
} |
62
|
35 |
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @inheritdoc |
66
|
|
|
*/ |
67
|
34 |
|
public function events() |
68
|
|
|
{ |
69
|
|
|
return [ |
70
|
34 |
|
BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate', |
71
|
34 |
|
BaseActiveRecord::EVENT_AFTER_INSERT => 'afterSave', |
72
|
34 |
|
BaseActiveRecord::EVENT_AFTER_UPDATE => 'afterSave', |
73
|
|
|
]; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Check if the behavior is attached to an Active Record |
78
|
|
|
* @param BaseActiveRecord $owner |
79
|
|
|
* @throws RuntimeException |
80
|
|
|
*/ |
81
|
35 |
|
public function attach($owner) |
82
|
|
|
{ |
83
|
35 |
|
if (!($owner instanceof BaseActiveRecord)) { |
|
|
|
|
84
|
1 |
|
throw new RuntimeException('Owner must be instance of yii\db\BaseActiveRecord'); |
85
|
|
|
} |
86
|
34 |
|
parent::attach($owner); |
87
|
34 |
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* Override canSetProperty method to be able to detect if a relation setter is allowed. |
91
|
|
|
* Setter is allowed if the relation is declared in the `relations` parameter |
92
|
|
|
* @param string $name |
93
|
|
|
* @param boolean $checkVars |
94
|
|
|
* @return boolean |
95
|
|
|
*/ |
96
|
33 |
|
public function canSetProperty($name, $checkVars = true) |
97
|
|
|
{ |
98
|
33 |
|
if (in_array($name, $this->_relations) && $this->owner->getRelation($name, false)) { |
|
|
|
|
99
|
32 |
|
return true; |
100
|
|
|
} |
101
|
1 |
|
return parent::canSetProperty($name, $checkVars); |
102
|
|
|
} |
103
|
|
|
|
104
|
|
|
/** |
105
|
|
|
* Override __set method to be able to set relations values either by providing a model instance, |
106
|
|
|
* a primary key value or an associative array |
107
|
|
|
* @param string $name |
108
|
|
|
* @param mixed $value |
109
|
|
|
*/ |
110
|
32 |
|
public function __set($name, $value) |
111
|
|
|
{ |
112
|
32 |
|
if (in_array($name, $this->_relations)) { |
113
|
32 |
|
Yii::debug("Setting {$name} relation value", __METHOD__); |
114
|
32 |
|
if (!isset($this->_oldRelationValue[$name])) { |
115
|
32 |
|
if ($this->owner->isNewRecord) { |
116
|
15 |
|
if ($this->owner->getRelation($name)->multiple === true) { |
117
|
7 |
|
$this->_oldRelationValue[$name] = []; |
118
|
|
|
} else { |
119
|
13 |
|
$this->_oldRelationValue[$name] = null; |
120
|
|
|
} |
121
|
|
|
} else { |
122
|
18 |
|
$this->_oldRelationValue[$name] = $this->owner->{$name}; |
123
|
|
|
} |
124
|
|
|
} |
125
|
32 |
|
if ($this->owner->getRelation($name)->multiple === true) { |
126
|
21 |
|
$this->setMultipleRelation($name, $value); |
127
|
|
|
} else { |
128
|
19 |
|
$this->setSingleRelation($name, $value); |
129
|
|
|
} |
130
|
|
|
} |
131
|
32 |
|
} |
132
|
|
|
|
133
|
|
|
/** |
134
|
|
|
* Set the named multiple relation with the given value |
135
|
|
|
* @param $name |
136
|
|
|
* @param $value |
137
|
|
|
*/ |
138
|
21 |
|
protected function setMultipleRelation($name, $value) |
139
|
|
|
{ |
140
|
21 |
|
$relation = $this->owner->getRelation($name); |
141
|
21 |
|
$newRelations = []; |
142
|
21 |
|
if (!is_array($value)) { |
143
|
3 |
|
if (!empty($value)) { |
144
|
2 |
|
$value = [$value]; |
145
|
|
|
} else { |
146
|
1 |
|
$value = []; |
147
|
|
|
} |
148
|
|
|
} |
149
|
21 |
|
foreach ($value as $entry) { |
150
|
20 |
|
if ($entry instanceof $relation->modelClass) { |
151
|
15 |
|
$newRelations[] = $entry; |
152
|
|
|
} else { |
153
|
|
|
// TODO handle this with one DB request to retrieve all models |
154
|
9 |
|
$newRelations[] = $this->processModelAsArray($entry, $relation); |
155
|
|
|
} |
156
|
|
|
} |
157
|
21 |
|
$this->_newRelationValue[$name] = $newRelations; |
158
|
21 |
|
$this->owner->populateRelation($name, $newRelations); |
159
|
21 |
|
} |
160
|
|
|
|
161
|
|
|
/** |
162
|
|
|
* Get a BaseActiveRecord model using the given $data parameter. |
163
|
|
|
* $data could either be a model ID or an associative array representing model attributes => values |
164
|
|
|
* @param mixed $data |
165
|
|
|
* @param \yii\db\ActiveQuery $relation |
166
|
|
|
* @return BaseActiveRecord |
167
|
|
|
*/ |
168
|
13 |
|
protected function processModelAsArray($data, $relation) |
169
|
|
|
{ |
170
|
|
|
/** @var BaseActiveRecord $modelClass */ |
171
|
13 |
|
$modelClass = $relation->modelClass; |
172
|
|
|
// Get the related model foreign keys |
173
|
13 |
|
if (is_array($data)) { |
174
|
9 |
|
$fks = []; |
175
|
|
|
|
176
|
|
|
// search PK |
177
|
9 |
|
foreach ($modelClass::primaryKey() as $modelAttribute) { |
178
|
9 |
|
if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { |
179
|
7 |
|
$fks[$modelAttribute] = $data[$modelAttribute]; |
180
|
|
|
} else { |
181
|
7 |
|
$fks = []; |
182
|
7 |
|
break; |
183
|
|
|
} |
184
|
|
|
} |
185
|
9 |
|
if (empty($fks)) { |
186
|
|
|
// Get the right link definition |
187
|
7 |
|
if ($relation->via instanceof BaseActiveRecord) { |
188
|
|
|
$viaQuery = $relation->via; |
|
|
|
|
189
|
|
|
$link = $viaQuery->link; |
190
|
7 |
|
} elseif (is_array($relation->via)) { |
191
|
2 |
|
list($viaName, $viaQuery) = $relation->via; |
192
|
2 |
|
$link = $viaQuery->link; |
193
|
|
|
} else { |
194
|
5 |
|
$link = $relation->link; |
195
|
|
|
} |
196
|
7 |
|
foreach ($link as $relatedAttribute => $modelAttribute) { |
197
|
7 |
|
if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { |
198
|
7 |
|
$fks[$modelAttribute] = $data[$modelAttribute]; |
199
|
|
|
} |
200
|
|
|
} |
201
|
|
|
} |
202
|
|
|
} else { |
203
|
4 |
|
$fks = $data; |
204
|
|
|
} |
205
|
|
|
// Load existing model or create one if no key was provided and data is not empty |
206
|
|
|
/** @var BaseActiveRecord $relationModel */ |
207
|
13 |
|
$relationModel = null; |
208
|
13 |
|
if (!empty($fks)) { |
209
|
8 |
|
$relationModel = $modelClass::findOne($fks); |
210
|
|
|
} |
211
|
13 |
|
if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) { |
212
|
8 |
|
$relationModel = new $modelClass; |
213
|
|
|
} |
214
|
13 |
|
if (($relationModel instanceof BaseActiveRecord) && is_array($data)) { |
215
|
9 |
|
$relationModel->setAttributes($data); |
216
|
|
|
} |
217
|
13 |
|
return $relationModel; |
218
|
|
|
} |
219
|
|
|
|
220
|
|
|
/** |
221
|
|
|
* Set the named single relation with the given value |
222
|
|
|
* @param $name |
223
|
|
|
* @param $value |
224
|
|
|
*/ |
225
|
19 |
|
protected function setSingleRelation($name, $value) |
226
|
|
|
{ |
227
|
19 |
|
$relation = $this->owner->getRelation($name); |
228
|
19 |
|
if (!($value instanceof $relation->modelClass)) { |
229
|
8 |
|
$value = $this->processModelAsArray($value, $relation); |
230
|
|
|
} |
231
|
19 |
|
$this->_newRelationValue[$name] = $value; |
232
|
19 |
|
$this->owner->populateRelation($name, $value); |
233
|
19 |
|
} |
234
|
|
|
|
235
|
|
|
/** |
236
|
|
|
* Before the owner model validation, save related models. |
237
|
|
|
* For `hasOne()` relations, set the according foreign keys of the owner model to be able to validate it |
238
|
|
|
* @param ModelEvent $event |
239
|
|
|
*/ |
240
|
29 |
|
public function beforeValidate(ModelEvent $event) |
241
|
|
|
{ |
242
|
29 |
|
if ($this->_relationsSaveStarted == false && !empty($this->_oldRelationValue)) { |
|
|
|
|
243
|
|
|
/* @var $model BaseActiveRecord */ |
244
|
29 |
|
$model = $this->owner; |
245
|
29 |
|
if ($this->saveRelatedRecords($model, $event)) { |
246
|
|
|
// If relation is has_one, try to set related model attributes |
247
|
27 |
|
foreach ($this->_relations as $relationName) { |
248
|
27 |
|
if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
249
|
27 |
|
$relation = $model->getRelation($relationName); |
250
|
27 |
|
if ($relation instanceof ActiveQueryInterface) { |
251
|
27 |
|
if ($relation->multiple === false && !empty($model->{$relationName})) { |
|
|
|
|
252
|
15 |
|
Yii::debug("Setting foreign keys for {$relationName}", __METHOD__); |
253
|
15 |
|
foreach ($relation->link as $relatedAttribute => $modelAttribute) { |
|
|
|
|
254
|
15 |
|
if ($model->{$modelAttribute} !== $model->{$relationName}->{$relatedAttribute}) { |
255
|
15 |
|
$model->{$modelAttribute} = $model->{$relationName}->{$relatedAttribute}; |
256
|
|
|
} |
257
|
|
|
} |
258
|
|
|
} |
259
|
|
|
} |
260
|
|
|
} |
261
|
|
|
} |
262
|
|
|
} |
263
|
|
|
} |
264
|
29 |
|
} |
265
|
|
|
|
266
|
|
|
/** |
267
|
|
|
* For each related model, try to save it first. |
268
|
|
|
* If set in the owner model, operation is done in a transactional way so if one of the models should not validate |
269
|
|
|
* or be saved, a rollback will occur., |
270
|
|
|
* This is done during the before validation process to be able to set the related foreign keys. |
271
|
|
|
* @param BaseActiveRecord $model |
272
|
|
|
* @param ModelEvent $event |
273
|
|
|
* @return bool |
274
|
|
|
*/ |
275
|
29 |
|
protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event) |
276
|
|
|
{ |
277
|
|
|
if ( |
278
|
29 |
|
method_exists($model, 'isTransactional') |
279
|
29 |
|
&& is_null($model->getDb()->transaction) |
280
|
|
|
&& ( |
281
|
29 |
|
($model->isNewRecord && $model->isTransactional($model::OP_INSERT)) |
282
|
21 |
|
|| (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE)) |
283
|
6 |
|
|| $model->isTransactional($model::OP_ALL) |
284
|
|
|
) |
285
|
|
|
) { |
286
|
23 |
|
$this->_transaction = $model->getDb()->beginTransaction(); |
287
|
|
|
} |
288
|
|
|
try { |
289
|
29 |
|
foreach ($this->_relations as $relationName) { |
290
|
29 |
|
if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
291
|
29 |
|
$relation = $model->getRelation($relationName); |
292
|
29 |
|
if (!empty($model->{$relationName})) { |
293
|
27 |
|
if ($relation->multiple === false) { |
|
|
|
|
294
|
17 |
|
$relationModel = $model->{$relationName}; |
295
|
17 |
|
$p1 = $model->isPrimaryKey(array_keys($relation->link)); |
|
|
|
|
296
|
17 |
|
$p2 = $relationModel::isPrimaryKey(array_values($relation->link)); |
297
|
17 |
|
$pettyRelationName = Inflector::camel2words($relationName, true); |
298
|
17 |
|
if ($relationModel->getIsNewRecord() && $p1 && !$p2) { |
299
|
|
|
// Save Has one relation new record |
300
|
10 |
|
$this->saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName); |
301
|
|
|
} else { |
302
|
10 |
|
$this->validateRelationModel($pettyRelationName, $relationName, $relationModel, $event); |
|
|
|
|
303
|
|
|
} |
304
|
|
|
} else { |
305
|
|
|
// Save Has many relations new records |
306
|
|
|
/** @var BaseActiveRecord $relationModel */ |
307
|
18 |
|
foreach ($model->{$relationName} as $i => $relationModel) { |
308
|
18 |
|
$pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
309
|
18 |
|
$this->validateRelationModel($pettyRelationName, $relationName, $relationModel, $event); |
310
|
|
|
} |
311
|
|
|
} |
312
|
|
|
} |
313
|
|
|
} |
314
|
|
|
} |
315
|
27 |
|
if (!$event->isValid) { |
316
|
|
|
throw new Exception("One of the related model could not be validated"); |
317
|
|
|
} |
318
|
2 |
|
} catch (Exception $e) { |
319
|
2 |
|
Yii::warning(get_class($e) . " was thrown while saving related records during beforeValidate event: " . $e->getMessage(), __METHOD__); |
320
|
2 |
|
$this->_rollback(); |
321
|
2 |
|
$model->addError($model->formName(), $e->getMessage()); |
322
|
2 |
|
$event->isValid = false; // Stop saving, something went wrong |
323
|
2 |
|
return false; |
324
|
|
|
} |
325
|
27 |
|
return true; |
326
|
|
|
} |
327
|
|
|
|
328
|
|
|
/** |
329
|
|
|
* Validate and save the model if it is new or changed |
330
|
|
|
* @param BaseActiveRecord $model |
331
|
|
|
* @param ModelEvent $event |
332
|
|
|
* @param $pettyRelationName |
333
|
|
|
* @param $relationName |
334
|
|
|
*/ |
335
|
10 |
|
protected function saveModelRecord(BaseActiveRecord $model, ModelEvent $event, $pettyRelationName, $relationName) |
336
|
|
|
{ |
337
|
10 |
|
$this->validateRelationModel($pettyRelationName, $relationName, $model, $event); |
|
|
|
|
338
|
10 |
|
if ($event->isValid && (count($model->dirtyAttributes) || $model->isNewRecord)) { |
339
|
10 |
|
Yii::debug("Saving {$pettyRelationName} relation model", __METHOD__); |
340
|
10 |
|
$model->save(false); |
341
|
|
|
} |
342
|
8 |
|
} |
343
|
|
|
|
344
|
|
|
/** |
345
|
|
|
* Validate a relation model and add an error message to owner model attribute if needed |
346
|
|
|
* @param string $pettyRelationName |
347
|
|
|
* @param string $relationName |
348
|
|
|
* @param BaseActiveRecord $relationModel |
349
|
|
|
* @param ModelEvent $event |
350
|
|
|
*/ |
351
|
27 |
|
protected function validateRelationModel($pettyRelationName, $relationName, BaseActiveRecord $relationModel) |
352
|
|
|
{ |
353
|
|
|
/** @var BaseActiveRecord $model */ |
354
|
27 |
|
$model = $this->owner; |
355
|
27 |
|
if (!is_null($relationModel) && ($relationModel->isNewRecord || count($relationModel->getDirtyAttributes()))) { |
356
|
19 |
|
if (array_key_exists($relationName, $this->_relationsScenario)) { |
357
|
7 |
|
$relationModel->setScenario($this->_relationsScenario[$relationName]); |
358
|
|
|
} |
359
|
19 |
|
Yii::debug("Validating {$pettyRelationName} relation model using " . $relationModel->scenario . ' scenario', __METHOD__); |
360
|
19 |
|
if (!$relationModel->validate()) { |
361
|
4 |
|
$this->_addError($relationModel, $model, $relationName, $pettyRelationName); |
362
|
|
|
} |
363
|
|
|
} |
364
|
27 |
|
} |
365
|
|
|
|
366
|
|
|
/** |
367
|
|
|
* Attach errors to owner relational attributes |
368
|
|
|
* @param $relationModel |
369
|
|
|
* @param $owner |
370
|
|
|
* @param $relationName |
371
|
|
|
* @param $pettyRelationName |
372
|
|
|
*/ |
373
|
5 |
|
private function _addError($relationModel, $owner, $relationName, $pettyRelationName) |
374
|
|
|
{ |
375
|
5 |
|
foreach ($relationModel->errors as $attributeErrors) { |
376
|
5 |
|
foreach ($attributeErrors as $error) { |
377
|
5 |
|
$owner->addError($relationName, "{$pettyRelationName}: {$error}"); |
378
|
|
|
} |
379
|
|
|
} |
380
|
5 |
|
} |
381
|
|
|
|
382
|
|
|
/** |
383
|
|
|
* Rollback transaction if any |
384
|
|
|
* @throws DbException |
385
|
|
|
*/ |
386
|
3 |
|
private function _rollback() |
387
|
|
|
{ |
388
|
3 |
|
if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
389
|
2 |
|
$this->_transaction->rollBack(); // If anything goes wrong, transaction will be rolled back |
390
|
2 |
|
Yii::info("Rolling back", __METHOD__); |
391
|
|
|
} |
392
|
3 |
|
} |
393
|
|
|
|
394
|
|
|
/** |
395
|
|
|
* Link the related models. |
396
|
|
|
* If the models have not been changed, nothing will be done. |
397
|
|
|
* Related records will be linked to the owner model using the BaseActiveRecord `link()` method. |
398
|
|
|
*/ |
399
|
27 |
|
public function afterSave() |
400
|
|
|
{ |
401
|
27 |
|
if ($this->_relationsSaveStarted === false) { |
402
|
|
|
/** @var BaseActiveRecord $model */ |
403
|
27 |
|
$model = $this->owner; |
404
|
27 |
|
$this->_relationsSaveStarted = true; |
405
|
|
|
// Populate relations with updated values |
406
|
27 |
|
foreach ($this->_newRelationValue as $name => $value) { |
407
|
27 |
|
$this->owner->populateRelation($name, $value); |
408
|
|
|
} |
409
|
|
|
try { |
410
|
27 |
|
foreach ($this->_relations as $relationName) { |
411
|
27 |
|
if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
412
|
27 |
|
Yii::debug("Linking {$relationName} relation", __METHOD__); |
413
|
27 |
|
$relation = $model->getRelation($relationName); |
414
|
27 |
|
if ($relation->multiple === true) { // Has many relation |
|
|
|
|
415
|
18 |
|
$this->_afterSaveHasManyRelation($model, $relationName); |
416
|
|
|
} else { // Has one relation |
417
|
17 |
|
$this->_afterSaveHasOneRelation($model, $relationName); |
418
|
|
|
} |
419
|
27 |
|
unset($this->_oldRelationValue[$relationName]); |
420
|
|
|
} |
421
|
|
|
} |
422
|
1 |
|
} catch (Exception $e) { |
423
|
1 |
|
Yii::warning(get_class($e) . " was thrown while saving related records during afterSave event: " . $e->getMessage(), __METHOD__); |
424
|
1 |
|
$this->_rollback(); |
425
|
|
|
/*** |
426
|
|
|
* Sadly mandatory because the error occurred during afterSave event |
427
|
|
|
* and we don't want the user/developper not to be aware of the issue. |
428
|
|
|
***/ |
429
|
1 |
|
throw $e; |
430
|
|
|
} |
431
|
27 |
|
$model->refresh(); |
432
|
27 |
|
$this->_relationsSaveStarted = false; |
433
|
27 |
|
if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
434
|
21 |
|
$this->_transaction->commit(); |
435
|
|
|
} |
436
|
|
|
} |
437
|
27 |
|
} |
438
|
|
|
|
439
|
|
|
/** |
440
|
|
|
* Return array of columns to save to the junction table for a related model having a many-to-many relation. |
441
|
|
|
* @param string $relationName |
442
|
|
|
* @param BaseActiveRecord $model |
443
|
|
|
* @return array |
444
|
|
|
*/ |
445
|
14 |
|
private function _getJunctionTableColumns($relationName, $model) |
446
|
|
|
{ |
447
|
14 |
|
$junctionTableColumns = []; |
448
|
14 |
|
if (array_key_exists($relationName, $this->_relationsExtraColumns)) { |
449
|
1 |
|
if (is_callable($this->_relationsExtraColumns[$relationName])) { |
450
|
1 |
|
$junctionTableColumns = $this->_relationsExtraColumns[$relationName]($model); |
451
|
|
|
} elseif (is_array($this->_relationsExtraColumns[$relationName])) { |
452
|
|
|
$junctionTableColumns = $this->_relationsExtraColumns[$relationName]; |
453
|
|
|
} |
454
|
1 |
|
if (!is_array($junctionTableColumns)) { |
455
|
|
|
throw new RuntimeException( |
456
|
|
|
'Junction table columns definition must return an array, got ' . gettype($junctionTableColumns) |
457
|
|
|
); |
458
|
|
|
} |
459
|
|
|
} |
460
|
14 |
|
return $junctionTableColumns; |
461
|
|
|
} |
462
|
|
|
|
463
|
|
|
/** |
464
|
|
|
* Compute the difference between two set of records using primary keys "tokens" |
465
|
|
|
* If third parameter is set to true all initial related records will be marked for removal even if their |
466
|
|
|
* properties did not change. This can be handy in a many-to-many relation involving a junction table. |
467
|
|
|
* @param BaseActiveRecord[] $initialRelations |
468
|
|
|
* @param BaseActiveRecord[] $updatedRelations |
469
|
|
|
* @param bool $forceSave |
470
|
|
|
* @return array |
471
|
|
|
*/ |
472
|
17 |
|
private function _computePkDiff($initialRelations, $updatedRelations, $forceSave = false) |
473
|
|
|
{ |
474
|
|
|
// Compute differences between initial relations and the current ones |
475
|
|
|
$oldPks = ArrayHelper::getColumn($initialRelations, function (BaseActiveRecord $model) { |
476
|
13 |
|
return implode("-", $model->getPrimaryKey(true)); |
477
|
17 |
|
}); |
478
|
|
|
$newPks = ArrayHelper::getColumn($updatedRelations, function (BaseActiveRecord $model) { |
479
|
13 |
|
return implode("-", $model->getPrimaryKey(true)); |
480
|
17 |
|
}); |
481
|
17 |
|
if ($forceSave) { |
482
|
1 |
|
$addedPks = $newPks; |
483
|
1 |
|
$deletedPks = $oldPks; |
484
|
|
|
} else { |
485
|
16 |
|
$identicalPks = array_intersect($oldPks, $newPks); |
486
|
16 |
|
$addedPks = array_values(array_diff($newPks, $identicalPks)); |
487
|
16 |
|
$deletedPks = array_values(array_diff($oldPks, $identicalPks)); |
488
|
|
|
} |
489
|
17 |
|
return [$addedPks, $deletedPks]; |
490
|
|
|
} |
491
|
|
|
|
492
|
|
|
/** |
493
|
|
|
* Populates relations with input data |
494
|
|
|
* @param array $data |
495
|
|
|
* @throws \yii\base\InvalidConfigException |
496
|
|
|
*/ |
497
|
4 |
|
public function loadRelations($data) |
498
|
|
|
{ |
499
|
|
|
/** @var BaseActiveRecord $model */ |
500
|
4 |
|
$model = $this->owner; |
501
|
4 |
|
foreach ($this->_relations as $relationName) { |
502
|
4 |
|
$relation = $model->getRelation($relationName); |
503
|
4 |
|
$modelClass = $relation->modelClass; |
|
|
|
|
504
|
|
|
/** @var BaseActiveRecord $relationalModel */ |
505
|
4 |
|
$relationalModel = new $modelClass; |
506
|
4 |
|
$formName = $relationalModel->formName(); |
507
|
4 |
|
if (array_key_exists($formName, $data)) { |
508
|
4 |
|
$model->{$relationName} = $data[$formName]; |
509
|
|
|
} |
510
|
|
|
} |
511
|
4 |
|
} |
512
|
|
|
|
513
|
|
|
/** |
514
|
|
|
* @param $owner |
515
|
|
|
* @param $relationName |
516
|
|
|
* @throws DbException |
517
|
|
|
*/ |
518
|
18 |
|
public function _afterSaveHasManyRelation($owner, $relationName) |
519
|
|
|
{ |
520
|
18 |
|
$relation = $owner->getRelation($relationName); |
521
|
|
|
|
522
|
|
|
// Process new relations |
523
|
18 |
|
$existingRecords = []; |
524
|
|
|
/** @var BaseActiveRecord $relationModel */ |
525
|
18 |
|
foreach ($owner->{$relationName} as $i => $relationModel) { |
526
|
18 |
|
if ($relationModel->isNewRecord) { |
527
|
10 |
|
if ($relation->via !== null) { |
528
|
9 |
|
if ($relationModel->validate()) { |
529
|
9 |
|
$relationModel->save(); |
530
|
|
|
} else { |
531
|
1 |
|
$pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
532
|
1 |
|
$this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
533
|
1 |
|
throw new DbException("Related record {$pettyRelationName} could not be saved."); |
534
|
|
|
} |
535
|
|
|
} |
536
|
10 |
|
$junctionTableColumns = $this->_getJunctionTableColumns($relationName, $relationModel); |
537
|
10 |
|
$owner->link($relationName, $relationModel, $junctionTableColumns); |
538
|
|
|
} else { |
539
|
13 |
|
$existingRecords[] = $relationModel; |
540
|
|
|
} |
541
|
18 |
|
if (count($relationModel->dirtyAttributes)) { |
542
|
4 |
|
if ($relationModel->validate()) { |
543
|
4 |
|
$relationModel->save(); |
544
|
|
|
} else { |
545
|
|
|
$pettyRelationName = Inflector::camel2words($relationName, true); |
546
|
|
|
$this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
547
|
|
|
throw new DbException("Related record {$pettyRelationName} could not be saved."); |
548
|
|
|
} |
549
|
|
|
} |
550
|
|
|
} |
551
|
17 |
|
$junctionTablePropertiesUsed = array_key_exists($relationName, $this->_relationsExtraColumns); |
552
|
|
|
|
553
|
|
|
// Process existing added and deleted relations |
554
|
17 |
|
list($addedPks, $deletedPks) = $this->_computePkDiff( |
555
|
17 |
|
$this->_oldRelationValue[$relationName], |
556
|
17 |
|
$existingRecords, |
557
|
17 |
|
$junctionTablePropertiesUsed |
558
|
|
|
); |
559
|
|
|
|
560
|
|
|
// Deleted relations |
561
|
|
|
$initialModels = ArrayHelper::index($this->_oldRelationValue[$relationName], function (BaseActiveRecord $model) { |
562
|
13 |
|
return implode('-', $model->getPrimaryKey(true)); |
563
|
17 |
|
}); |
564
|
17 |
|
$initialRelations = $owner->{$relationName}; |
565
|
17 |
|
foreach ($deletedPks as $key) { |
566
|
2 |
|
$owner->unlink($relationName, $initialModels[$key], true); |
567
|
|
|
} |
568
|
|
|
|
569
|
|
|
// Added relations |
570
|
17 |
|
$actualModels = ArrayHelper::index( |
571
|
17 |
|
$junctionTablePropertiesUsed ? $initialRelations : $owner->{$relationName}, |
572
|
17 |
|
function (BaseActiveRecord $model) { |
573
|
17 |
|
return implode('-', $model->getPrimaryKey(true)); |
574
|
17 |
|
} |
575
|
|
|
); |
576
|
17 |
|
foreach ($addedPks as $key) { |
577
|
4 |
|
$junctionTableColumns = $this->_getJunctionTableColumns($relationName, $actualModels[$key]); |
578
|
4 |
|
$owner->link($relationName, $actualModels[$key], $junctionTableColumns); |
579
|
|
|
} |
580
|
17 |
|
} |
581
|
|
|
|
582
|
|
|
/** |
583
|
|
|
* @param $owner |
584
|
|
|
* @param $relationName |
585
|
|
|
*/ |
586
|
17 |
|
private function _afterSaveHasOneRelation($owner, $relationName) |
587
|
|
|
{ |
588
|
17 |
|
if ($this->_oldRelationValue[$relationName] !== $owner->{$relationName}) { |
589
|
14 |
|
if ($owner->{$relationName} instanceof BaseActiveRecord) { |
590
|
13 |
|
$owner->link($relationName, $owner->{$relationName}); |
591
|
|
|
} else { |
592
|
1 |
|
if ($this->_oldRelationValue[$relationName] instanceof BaseActiveRecord) { |
593
|
1 |
|
$owner->unlink($relationName, $this->_oldRelationValue[$relationName]); |
594
|
|
|
} |
595
|
|
|
} |
596
|
|
|
} |
597
|
17 |
|
if ($owner->{$relationName} instanceof BaseActiveRecord) { |
598
|
15 |
|
$owner->{$relationName}->save(); |
599
|
|
|
} |
600
|
17 |
|
} |
601
|
|
|
} |
602
|
|
|
|