Passed
Push — master ( 7fe533...3075d5 )
by Alban
02:03
created

SaveRelationsBehavior::saveModelRecord()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 2
nop 4
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 4
rs 9.2
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 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;
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...
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
     * @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, $event);
0 ignored issues
show
Unused Code introduced by
The call to lhs\Yii2SaveRelationsBeh...validateRelationModel() has too many arguments starting with $event. ( Ignorable by Annotation )

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

340
        $this->/** @scrutinizer ignore-call */ 
341
               validateRelationModel($pettyRelationName, $relationName, $model, $event);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

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