Passed
Push — master ( 279fdf...aef5f4 )
by Alban
02:10
created

SaveRelationsBehavior::_hasActiveRelationTrait()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\ActiveQuery;
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)) {
0 ignored issues
show
introduced by
$owner is always a sub-type of yii\db\BaseActiveRecord.
Loading history...
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)) {
0 ignored issues
show
Bug introduced by
The method getRelation() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

98
        if (in_array($name, $this->_relations) && $this->owner->/** @scrutinizer ignore-call */ getRelation($name, false)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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 single relation with the given value
135
     * @param $name
136
     * @param $value
137
     */
138 19
    protected function setSingleRelation($name, $value)
139
    {
140 19
        $relation = $this->owner->getRelation($name);
141 19
        if (!($value instanceof $relation->modelClass)) {
142 8
            $value = $this->processModelAsArray($value, $relation);
143
        }
144 19
        $this->_newRelationValue[$name] = $value;
145 19
        $this->owner->populateRelation($name, $value);
146 19
    }
147
148
    /**
149
     * Set the named multiple relation with the given value
150
     * @param $name
151
     * @param $value
152
     */
153 21
    protected function setMultipleRelation($name, $value)
154
    {
155 21
        $relation = $this->owner->getRelation($name);
156 21
        $newRelations = [];
157 21
        if (!is_array($value)) {
158 3
            if (!empty($value)) {
159 2
                $value = [$value];
160
            } else {
161 1
                $value = [];
162
            }
163
        }
164 21
        foreach ($value as $entry) {
165 20
            if ($entry instanceof $relation->modelClass) {
166 15
                $newRelations[] = $entry;
167
            } else {
168
                // TODO handle this with one DB request to retrieve all models
169 9
                $newRelations[] = $this->processModelAsArray($entry, $relation);
170
            }
171
        }
172 21
        $this->_newRelationValue[$name] = $newRelations;
173 21
        $this->owner->populateRelation($name, $newRelations);
174 21
    }
175
176
    /**
177
     * Get a BaseActiveRecord model using the given $data parameter.
178
     * $data could either be a model ID or an associative array representing model attributes => values
179
     * @param mixed $data
180
     * @param \yii\db\ActiveQuery $relation
181
     * @return BaseActiveRecord
182
     */
183 13
    protected function processModelAsArray($data, $relation)
184
    {
185
        /** @var BaseActiveRecord $modelClass */
186 13
        $modelClass = $relation->modelClass;
187
        // Get the related model foreign keys
188 13
        if (is_array($data)) {
189 9
            $fks = [];
190
191
            // search PK
192 9
            foreach ($modelClass::primaryKey() as $modelAttribute) {
193 9
                if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) {
194 7
                    $fks[$modelAttribute] = $data[$modelAttribute];
195
                } else {
196 7
                    $fks = [];
197 7
                    break;
198
                }
199
            }
200 9
            if (empty($fks)) {
201
                // Get the right link definition
202 7
                if ($relation->via instanceof BaseActiveRecord) {
203
                    $viaQuery = $relation->via;
0 ignored issues
show
Documentation Bug introduced by
It seems like $relation->via of type yii\db\BaseActiveRecord is incompatible with the declared type object|array of property $via.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
204
                    $link = $viaQuery->link;
205 7
                } elseif (is_array($relation->via)) {
206 2
                    list($viaName, $viaQuery) = $relation->via;
207 2
                    $link = $viaQuery->link;
208
                } else {
209 5
                    $link = $relation->link;
210
                }
211 7
                foreach ($link as $relatedAttribute => $modelAttribute) {
212 7
                    if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) {
213 7
                        $fks[$modelAttribute] = $data[$modelAttribute];
214
                    }
215
                }
216
            }
217
        } else {
218 4
            $fks = $data;
219
        }
220
        // Load existing model or create one if no key was provided and data is not empty
221
        /** @var BaseActiveRecord $relationModel */
222 13
        $relationModel = null;
223 13
        if (!empty($fks)) {
224 8
            $relationModel = $modelClass::findOne($fks);
225
        }
226 13
        if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) {
227 8
            $relationModel = new $modelClass;
228
        }
229 13
        if (($relationModel instanceof BaseActiveRecord) && is_array($data)) {
230 9
            $relationModel->setAttributes($data);
231
        }
232 13
        return $relationModel;
233
    }
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
     * @throws DbException
240
     * @throws \yii\base\InvalidConfigException
241
     */
242 29
    public function beforeValidate(ModelEvent $event)
243
    {
244 29
        if ($this->_relationsSaveStarted === false && !empty($this->_oldRelationValue)) {
245
            /* @var $model BaseActiveRecord */
246 29
            $model = $this->owner;
247 29
            if ($this->saveRelatedRecords($model, $event)) {
248
                // If relation is has_one, try to set related model attributes
249 27
                foreach ($this->_relations as $relationName) {
250 27
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
251 27
                        $relation = $model->getRelation($relationName);
252 27
                        if ($relation->multiple === false && !empty($model->{$relationName})) {
0 ignored issues
show
Bug introduced by
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
253 15
                            Yii::debug("Setting foreign keys for {$relationName}", __METHOD__);
254 15
                            foreach ($relation->link as $relatedAttribute => $modelAttribute) {
0 ignored issues
show
Bug introduced by
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
255 15
                                if ($model->{$modelAttribute} !== $model->{$relationName}->{$relatedAttribute}) {
256 15
                                    $model->{$modelAttribute} = $model->{$relationName}->{$relatedAttribute};
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
     * @throws DbException
275
     * @throws \yii\base\InvalidConfigException
276
     */
277 29
    protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event)
278
    {
279
        if (
280 29
            method_exists($model, 'isTransactional')
281 29
            && is_null($model->getDb()->transaction)
282
            && (
283 29
                ($model->isNewRecord && $model->isTransactional($model::OP_INSERT))
284 21
                || (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE))
285 6
                || $model->isTransactional($model::OP_ALL)
286
            )
287
        ) {
288 23
            $this->_transaction = $model->getDb()->beginTransaction();
289
        }
290
        try {
291 29
            foreach ($this->_relations as $relationName) {
292 29
                if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
293
                    /** @var ActiveQuery $relation */
294 29
                    $relation = $model->getRelation($relationName);
295 29
                    if (!empty($model->{$relationName})) {
296 27
                        if ($relation->multiple === false) {
297 17
                            $relationModel = $model->{$relationName};
298 17
                            $p1 = $model->isPrimaryKey(array_keys($relation->link));
299 17
                            $p2 = $relationModel::isPrimaryKey(array_values($relation->link));
300 17
                            $pettyRelationName = Inflector::camel2words($relationName, true);
301 17
                            if ($relationModel->getIsNewRecord() && $p1 && !$p2) {
302
                                // Save Has one relation new record
303 10
                                $this->saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName);
304
                            } else {
305 10
                                $this->validateRelationModel($pettyRelationName, $relationName, $relationModel);
306
                            }
307
                        } else {
308
                            // Save Has many relations new records
309
                            /** @var BaseActiveRecord $relationModel */
310 18
                            foreach ($model->{$relationName} as $i => $relationModel) {
311 18
                                $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}";
312 18
                                $this->validateRelationModel($pettyRelationName, $relationName, $relationModel);
313
                            }
314
                        }
315
                    }
316
                }
317
            }
318 27
            if (!$event->isValid) {
319
                throw new Exception('One of the related model could not be validated');
320
            }
321 2
        } catch (Exception $e) {
322 2
            Yii::warning(get_class($e) . ' was thrown while saving related records during beforeValidate event: ' . $e->getMessage(), __METHOD__);
323 2
            $this->_rollback();
324 2
            $model->addError($model->formName(), $e->getMessage());
325 2
            $event->isValid = false; // Stop saving, something went wrong
326 2
            return false;
327
        }
328 27
        return true;
329
    }
330
331
    /**
332
     * Validate and save the model if it is new or changed
333
     * @param BaseActiveRecord $model
334
     * @param ModelEvent $event
335
     * @param $pettyRelationName
336
     * @param $relationName
337
     */
338 10
    protected function saveModelRecord(BaseActiveRecord $model, ModelEvent $event, $pettyRelationName, $relationName)
339
    {
340 10
        $this->validateRelationModel($pettyRelationName, $relationName, $model);
341 10
        if ($event->isValid && (count($model->dirtyAttributes) || $model->isNewRecord)) {
342 10
            Yii::debug("Saving {$pettyRelationName} relation model", __METHOD__);
343 10
            $model->save(false);
344
        }
345 8
    }
346
347
    /**
348
     * Validate a relation model and add an error message to owner model attribute if needed
349
     * @param string $pettyRelationName
350
     * @param string $relationName
351
     * @param BaseActiveRecord $relationModel
352
     */
353 27
    protected function validateRelationModel($pettyRelationName, $relationName, BaseActiveRecord $relationModel)
354
    {
355
        /** @var BaseActiveRecord $model */
356 27
        $model = $this->owner;
357 27
        if (!is_null($relationModel) && ($relationModel->isNewRecord || count($relationModel->getDirtyAttributes()))) {
358 19
            if (array_key_exists($relationName, $this->_relationsScenario)) {
359 7
                $relationModel->setScenario($this->_relationsScenario[$relationName]);
360
            }
361 19
            Yii::debug("Validating {$pettyRelationName} relation model using " . $relationModel->scenario . ' scenario', __METHOD__);
362 19
            if (!$relationModel->validate()) {
363 4
                $this->_addError($relationModel, $model, $relationName, $pettyRelationName);
364
            }
365
        }
366 27
    }
367
368
    /**
369
     * Attach errors to owner relational attributes
370
     * @param $relationModel
371
     * @param $owner
372
     * @param $relationName
373
     * @param $pettyRelationName
374
     */
375 5
    private function _addError($relationModel, $owner, $relationName, $pettyRelationName)
376
    {
377 5
        foreach ($relationModel->errors as $attributeErrors) {
378 5
            foreach ($attributeErrors as $error) {
379 5
                $owner->addError($relationName, "{$pettyRelationName}: {$error}");
380
            }
381
        }
382 5
    }
383
384
    /**
385
     * Rollback transaction if any
386
     * @throws DbException
387
     */
388 3
    private function _rollback()
389
    {
390 3
        if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) {
391 2
            $this->_transaction->rollBack(); // If anything goes wrong, transaction will be rolled back
392 2
            Yii::info('Rolling back', __METHOD__);
393
        }
394 3
    }
395
396
    /**
397
     * Link the related models.
398
     * If the models have not been changed, nothing will be done.
399
     * Related records will be linked to the owner model using the BaseActiveRecord `link()` method.
400
     * @throws Exception
401
     */
402 27
    public function afterSave()
403
    {
404 27
        if ($this->_relationsSaveStarted === false) {
405
            /** @var BaseActiveRecord $owner */
406 27
            $owner = $this->owner;
407 27
            $this->_relationsSaveStarted = true;
408
            // Populate relations with updated values
409 27
            foreach ($this->_newRelationValue as $name => $value) {
410 27
                $this->owner->populateRelation($name, $value);
411
            }
412
            try {
413 27
                foreach ($this->_relations as $relationName) {
414 27
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
415 27
                        Yii::debug("Linking {$relationName} relation", __METHOD__);
416
                        /** @var ActiveQuery $relation */
417 27
                        $relation = $owner->getRelation($relationName);
418 27
                        if ($relation->multiple === true) { // Has many relation
419 18
                            $this->_afterSaveHasManyRelation($relationName);
420
                        } else { // Has one relation
421 17
                            $this->_afterSaveHasOneRelation($relationName);
422
                        }
423 27
                        unset($this->_oldRelationValue[$relationName]);
424
                    }
425
                }
426 1
            } catch (Exception $e) {
427 1
                Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__);
428 1
                $this->_rollback();
429
                /***
430
                 * Sadly mandatory because the error occurred during afterSave event
431
                 * and we don't want the user/developper not to be aware of the issue.
432
                 ***/
433 1
                throw $e;
434
            }
435 27
            $owner->refresh();
436 27
            $this->_relationsSaveStarted = false;
437 27
            if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) {
438 21
                $this->_transaction->commit();
439
            }
440
        }
441 27
    }
442
443
    /**
444
     * Return array of columns to save to the junction table for a related model having a many-to-many relation.
445
     * @param string $relationName
446
     * @param BaseActiveRecord $model
447
     * @return array
448
     * @throws \RuntimeException
449
     */
450 14
    private function _getJunctionTableColumns($relationName, $model)
451
    {
452 14
        $junctionTableColumns = [];
453 14
        if (array_key_exists($relationName, $this->_relationsExtraColumns)) {
454 1
            if (is_callable($this->_relationsExtraColumns[$relationName])) {
455 1
                $junctionTableColumns = $this->_relationsExtraColumns[$relationName]($model);
456
            } elseif (is_array($this->_relationsExtraColumns[$relationName])) {
457
                $junctionTableColumns = $this->_relationsExtraColumns[$relationName];
458
            }
459 1
            if (!is_array($junctionTableColumns)) {
460
                throw new RuntimeException(
461
                    'Junction table columns definition must return an array, got ' . gettype($junctionTableColumns)
462
                );
463
            }
464
        }
465 14
        return $junctionTableColumns;
466
    }
467
468
    /**
469
     * Compute the difference between two set of records using primary keys "tokens"
470
     * If third parameter is set to true all initial related records will be marked for removal even if their
471
     * properties did not change. This can be handy in a many-to-many relation involving a junction table.
472
     * @param BaseActiveRecord[] $initialRelations
473
     * @param BaseActiveRecord[] $updatedRelations
474
     * @param bool $forceSave
475
     * @return array
476
     */
477 17
    private function _computePkDiff($initialRelations, $updatedRelations, $forceSave = false)
478
    {
479
        // Compute differences between initial relations and the current ones
480
        $oldPks = ArrayHelper::getColumn($initialRelations, function (BaseActiveRecord $model) {
481 13
            return implode('-', $model->getPrimaryKey(true));
482 17
        });
483
        $newPks = ArrayHelper::getColumn($updatedRelations, function (BaseActiveRecord $model) {
484 13
            return implode('-', $model->getPrimaryKey(true));
485 17
        });
486 17
        if ($forceSave) {
487 1
            $addedPks = $newPks;
488 1
            $deletedPks = $oldPks;
489
        } else {
490 16
            $identicalPks = array_intersect($oldPks, $newPks);
491 16
            $addedPks = array_values(array_diff($newPks, $identicalPks));
492 16
            $deletedPks = array_values(array_diff($oldPks, $identicalPks));
493
        }
494 17
        return [$addedPks, $deletedPks];
495
    }
496
497
    /**
498
     * Populates relations with input data
499
     * @param array $data
500
     */
501 4
    public function loadRelations($data)
502
    {
503
        /** @var BaseActiveRecord $model */
504 4
        $model = $this->owner;
505 4
        foreach ($this->_relations as $relationName) {
506 4
            $relation = $model->getRelation($relationName);
507 4
            $modelClass = $relation->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
508
            /** @var ActiveQuery $relationalModel */
509 4
            $relationalModel = new $modelClass;
510 4
            $formName = $relationalModel->formName();
511 4
            if (array_key_exists($formName, $data)) {
512 4
                $model->{$relationName} = $data[$formName];
513
            }
514
        }
515 4
    }
516
517
    /**
518
     * @param $relationName
519
     * @throws DbException
520
     */
521 18
    public function _afterSaveHasManyRelation($relationName)
522
    {
523 18
        $owner = $this->owner;
524 18
        $relation = $owner->getRelation($relationName);
0 ignored issues
show
Bug introduced by
The method getRelation() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

524
        /** @scrutinizer ignore-call */ 
525
        $relation = $owner->getRelation($relationName);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
525
526
        // Process new relations
527 18
        $existingRecords = [];
528
        /** @var ActiveQuery $relationModel */
529 18
        foreach ($owner->{$relationName} as $i => $relationModel) {
530 18
            if ($relationModel->isNewRecord) {
531 10
                if ($relation->via !== null) {
532 9
                    if ($relationModel->validate()) {
533 9
                        $relationModel->save();
534
                    } else {
535 1
                        $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}";
536 1
                        $this->_addError($relationModel, $owner, $relationName, $pettyRelationName);
537 1
                        throw new DbException("Related record {$pettyRelationName} could not be saved.");
538
                    }
539
                }
540 10
                $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $relationModel);
541 10
                $owner->link($relationName, $relationModel, $junctionTableColumns);
542
            } else {
543 13
                $existingRecords[] = $relationModel;
544
            }
545 18
            if (count($relationModel->dirtyAttributes)) {
546 4
                if ($relationModel->validate()) {
547 4
                    $relationModel->save();
548
                } else {
549
                    $pettyRelationName = Inflector::camel2words($relationName, true);
550
                    $this->_addError($relationModel, $owner, $relationName, $pettyRelationName);
551
                    throw new DbException("Related record {$pettyRelationName} could not be saved.");
552
                }
553
            }
554
        }
555 17
        $junctionTablePropertiesUsed = array_key_exists($relationName, $this->_relationsExtraColumns);
556
557
        // Process existing added and deleted relations
558 17
        list($addedPks, $deletedPks) = $this->_computePkDiff(
559 17
            $this->_oldRelationValue[$relationName],
560 17
            $existingRecords,
561 17
            $junctionTablePropertiesUsed
562
        );
563
564
        // Deleted relations
565
        $initialModels = ArrayHelper::index($this->_oldRelationValue[$relationName], function (BaseActiveRecord $model) {
566 13
            return implode('-', $model->getPrimaryKey(true));
567 17
        });
568 17
        $initialRelations = $owner->{$relationName};
569 17
        foreach ($deletedPks as $key) {
570 2
            $owner->unlink($relationName, $initialModels[$key], true);
571
        }
572
573
        // Added relations
574 17
        $actualModels = ArrayHelper::index(
575 17
            $junctionTablePropertiesUsed ? $initialRelations : $owner->{$relationName},
576 17
            function (BaseActiveRecord $model) {
577 17
                return implode('-', $model->getPrimaryKey(true));
578 17
            }
579
        );
580 17
        foreach ($addedPks as $key) {
581 4
            $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $actualModels[$key]);
582 4
            $owner->link($relationName, $actualModels[$key], $junctionTableColumns);
583
        }
584 17
    }
585
586
    /**
587
     * @param $relationName
588
     */
589 17
    private function _afterSaveHasOneRelation($relationName)
590
    {
591 17
        $owner = $this->owner;
592
593 17
        if ($this->_oldRelationValue[$relationName] !== $owner->{$relationName}) {
594 14
            if ($owner->{$relationName} instanceof BaseActiveRecord) {
595 13
                $owner->link($relationName, $owner->{$relationName});
596
            } else {
597 1
                if ($this->_oldRelationValue[$relationName] instanceof BaseActiveRecord) {
598 1
                    $owner->unlink($relationName, $this->_oldRelationValue[$relationName]);
599
                }
600
            }
601
        }
602 17
        if ($owner->{$relationName} instanceof BaseActiveRecord) {
603 15
            $owner->{$relationName}->save();
604
        }
605 17
    }
606
}
607