Passed
Push — master ( 98923a...928dfb )
by Alban
02:05
created

src/SaveRelationsBehavior.php (8 issues)

Labels
Severity
1
<?php
2
3
namespace lhs\Yii2SaveRelationsBehavior;
4
5
use RuntimeException;
6
use Yii;
7
use yii\base\Behavior;
8
use yii\base\Component;
9
use yii\base\Exception;
10
use yii\base\ModelEvent;
11
use yii\base\UnknownPropertyException;
12
use yii\db\ActiveQuery;
13
use yii\db\BaseActiveRecord;
14
use yii\db\Exception as DbException;
15
use yii\db\Transaction;
16
use yii\helpers\ArrayHelper;
17
use yii\helpers\Inflector;
18
19
/**
20
 * This Active Record Behavior allows to validate and save the Model relations when the save() method is invoked.
21
 * List of handled relations should be declared using the $relations parameter via an array of relation names.
22
 * @author albanjubert
23
 */
24
class SaveRelationsBehavior extends Behavior
25
{
26
27
    public $relations = [];
28
    private $_relations = [];
29
    private $_oldRelationValue = []; // Store initial relations value
30
    private $_newRelationValue = []; // Store update relations value
31
    private $_relationsSaveStarted = false;
32
    private $_transaction;
33
34
35
    private $_relationsScenario = [];
36
    private $_relationsExtraColumns = [];
37
38
    //private $_relationsCascadeDelete = []; //TODO
39
40
    /**
41
     * @inheritdoc
42
     */
43 35
    public function init()
44
    {
45 35
        parent::init();
46 35
        $allowedProperties = ['scenario', 'extraColumns'];
47 35
        foreach ($this->relations as $key => $value) {
48 34
            if (is_int($key)) {
49 34
                $this->_relations[] = $value;
50
            } else {
51 28
                $this->_relations[] = $key;
52 28
                if (is_array($value)) {
53 28
                    foreach ($value as $propertyKey => $propertyValue) {
54 28
                        if (in_array($propertyKey, $allowedProperties)) {
55 28
                            $this->{'_relations' . ucfirst($propertyKey)}[$key] = $propertyValue;
56
                        } else {
57 28
                            throw new UnknownPropertyException('The relation property named ' . $propertyKey . ' is not supported');
58
                        }
59
                    }
60
                }
61
            }
62
        }
63 35
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68 34
    public function events()
69
    {
70
        return [
71 34
            BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
72 34
            BaseActiveRecord::EVENT_AFTER_INSERT    => 'afterSave',
73 34
            BaseActiveRecord::EVENT_AFTER_UPDATE    => 'afterSave',
74
        ];
75
    }
76
77
    /**
78
     * Check if the behavior is attached to an Active Record
79
     * @param Component $owner
80
     * @throws RuntimeException
81
     */
82 35
    public function attach($owner)
83
    {
84 35
        if (!($owner instanceof BaseActiveRecord)) {
85 1
            throw new RuntimeException('Owner must be instance of yii\db\BaseActiveRecord');
86
        }
87 34
        parent::attach($owner);
88 34
    }
89
90
    /**
91
     * Override canSetProperty method to be able to detect if a relation setter is allowed.
92
     * Setter is allowed if the relation is declared in the `relations` parameter
93
     * @param string $name
94
     * @param boolean $checkVars
95
     * @return boolean
96
     */
97 33
    public function canSetProperty($name, $checkVars = true)
98
    {
99
        /** @var BaseActiveRecord $owner */
100 33
        $owner = $this->owner;
101 33
        if (in_array($name, $this->_relations) && $owner->getRelation($name, false)) {
102 32
            return true;
103
        }
104 1
        return parent::canSetProperty($name, $checkVars);
105
    }
106
107
    /**
108
     * Override __set method to be able to set relations values either by providing a model instance,
109
     * a primary key value or an associative array
110
     * @param string $name
111
     * @param mixed $value
112
     * @throws \yii\base\InvalidArgumentException
113
     */
114 32
    public function __set($name, $value)
115
    {
116
        /** @var BaseActiveRecord $owner */
117 32
        $owner = $this->owner;
118 32
        if (in_array($name, $this->_relations)) {
119 32
            Yii::debug("Setting {$name} relation value", __METHOD__);
120 32
            if (!isset($this->_oldRelationValue[$name])) {
121 32
                if ($owner->isNewRecord) {
122 15
                    if ($owner->getRelation($name)->multiple === true) {
0 ignored issues
show
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
123 7
                        $this->_oldRelationValue[$name] = [];
124
                    } else {
125 13
                        $this->_oldRelationValue[$name] = null;
126
                    }
127
                } else {
128 18
                    $this->_oldRelationValue[$name] = $owner->{$name};
129
                }
130
            }
131 32
            if ($owner->getRelation($name)->multiple === true) {
132 21
                $this->setMultipleRelation($name, $value);
133
            } else {
134 19
                $this->setSingleRelation($name, $value);
135
            }
136
        }
137 32
    }
138
139
    /**
140
     * Set the named single relation with the given value
141
     * @param $name
142
     * @param $value
143
     * @throws \yii\base\InvalidArgumentException
144
     */
145 19
    protected function setSingleRelation($name, $value)
146
    {
147
        /** @var BaseActiveRecord $owner */
148 19
        $owner = $this->owner;
149 19
        $relation = $owner->getRelation($name);
150 19
        if (!($value instanceof $relation->modelClass)) {
0 ignored issues
show
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
151 8
            $value = $this->processModelAsArray($value, $relation);
152
        }
153 19
        $this->_newRelationValue[$name] = $value;
154 19
        $owner->populateRelation($name, $value);
155 19
    }
156
157
    /**
158
     * Set the named multiple relation with the given value
159
     * @param $name
160
     * @param $value
161
     * @throws \yii\base\InvalidArgumentException
162
     */
163 21
    protected function setMultipleRelation($name, $value)
164
    {
165
        /** @var BaseActiveRecord $owner */
166 21
        $owner = $this->owner;
167 21
        $relation = $owner->getRelation($name);
168 21
        $newRelations = [];
169 21
        if (!is_array($value)) {
170 3
            if (!empty($value)) {
171 2
                $value = [$value];
172
            } else {
173 1
                $value = [];
174
            }
175
        }
176 21
        foreach ($value as $entry) {
177 20
            if ($entry instanceof $relation->modelClass) {
0 ignored issues
show
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
178 15
                $newRelations[] = $entry;
179
            } else {
180
                // TODO handle this with one DB request to retrieve all models
181 9
                $newRelations[] = $this->processModelAsArray($entry, $relation);
182
            }
183
        }
184 21
        $this->_newRelationValue[$name] = $newRelations;
185 21
        $owner->populateRelation($name, $newRelations);
186 21
    }
187
188
    /**
189
     * Get a BaseActiveRecord model using the given $data parameter.
190
     * $data could either be a model ID or an associative array representing model attributes => values
191
     * @param mixed $data
192
     * @param \yii\db\ActiveQuery $relation
193
     * @return BaseActiveRecord
194
     */
195 13
    protected function processModelAsArray($data, $relation)
196
    {
197
        /** @var BaseActiveRecord $modelClass */
198 13
        $modelClass = $relation->modelClass;
199
        // Get the related model foreign keys
200 13
        if (is_array($data)) {
201 9
            $fks = [];
202
203
            // search PK
204 9
            foreach ($modelClass::primaryKey() as $modelAttribute) {
205 9
                if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) {
206 7
                    $fks[$modelAttribute] = $data[$modelAttribute];
207
                } else {
208 7
                    $fks = [];
209 7
                    break;
210
                }
211
            }
212 9
            if (empty($fks)) {
213
                // Get the right link definition
214 7
                if ($relation->via instanceof BaseActiveRecord) {
215
                    /** @var BaseActiveRecord|array $viaQuery */
216
                    $viaQuery = $relation->via;
217
                    $link = $viaQuery->link;
218 7
                } elseif (is_array($relation->via)) {
219 2
                    list($viaName, $viaQuery) = $relation->via;
220 2
                    $link = $viaQuery->link;
221
                } else {
222 5
                    $link = $relation->link;
223
                }
224 7
                foreach ($link as $relatedAttribute => $modelAttribute) {
225 7
                    if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) {
226 7
                        $fks[$modelAttribute] = $data[$modelAttribute];
227
                    }
228
                }
229
            }
230
        } else {
231 4
            $fks = $data;
232
        }
233
        // Load existing model or create one if no key was provided and data is not empty
234
        /** @var BaseActiveRecord $relationModel */
235 13
        $relationModel = null;
236 13
        if (!empty($fks)) {
237 8
            $relationModel = $modelClass::findOne($fks);
238
        }
239 13
        if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) {
240 8
            $relationModel = new $modelClass;
241
        }
242 13
        if (($relationModel instanceof BaseActiveRecord) && is_array($data)) {
243 9
            $relationModel->setAttributes($data);
244
        }
245 13
        return $relationModel;
246
    }
247
248
    /**
249
     * Before the owner model validation, save related models.
250
     * For `hasOne()` relations, set the according foreign keys of the owner model to be able to validate it
251
     * @param ModelEvent $event
252
     * @throws DbException
253
     * @throws \yii\base\InvalidConfigException
254
     */
255 29
    public function beforeValidate(ModelEvent $event)
256
    {
257 29
        if ($this->_relationsSaveStarted === false && !empty($this->_oldRelationValue)) {
258
            /* @var $model BaseActiveRecord */
259 29
            $model = $this->owner;
260 29
            if ($this->saveRelatedRecords($model, $event)) {
261
                // If relation is has_one, try to set related model attributes
262 27
                foreach ($this->_relations as $relationName) {
263 27
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
264 27
                        $relation = $model->getRelation($relationName);
265 27
                        if ($relation->multiple === false && !empty($model->{$relationName})) {
0 ignored issues
show
Accessing multiple on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
266 15
                            Yii::debug("Setting foreign keys for {$relationName}", __METHOD__);
267 15
                            foreach ($relation->link as $relatedAttribute => $modelAttribute) {
0 ignored issues
show
Accessing link on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
268 15
                                if ($model->{$modelAttribute} !== $model->{$relationName}->{$relatedAttribute}) {
269 15
                                    $model->{$modelAttribute} = $model->{$relationName}->{$relatedAttribute};
270
                                }
271
                            }
272
                        }
273
                    }
274
                }
275
            }
276
        }
277 29
    }
278
279
    /**
280
     * For each related model, try to save it first.
281
     * If set in the owner model, operation is done in a transactional way so if one of the models should not validate
282
     * or be saved, a rollback will occur.,
283
     * This is done during the before validation process to be able to set the related foreign keys.
284
     * @param BaseActiveRecord $model
285
     * @param ModelEvent $event
286
     * @return bool
287
     * @throws DbException
288
     * @throws \yii\base\InvalidConfigException
289
     */
290 29
    protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event)
291
    {
292
        if (
293 29
            method_exists($model, 'isTransactional')
294 29
            && is_null($model->getDb()->transaction)
295
            && (
296 29
                ($model->isNewRecord && $model->isTransactional($model::OP_INSERT))
297 21
                || (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE))
298 6
                || $model->isTransactional($model::OP_ALL)
299
            )
300
        ) {
301 23
            $this->_transaction = $model->getDb()->beginTransaction();
302
        }
303
        try {
304 29
            foreach ($this->_relations as $relationName) {
305 29
                if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
306
                    /** @var ActiveQuery $relation */
307 29
                    $relation = $model->getRelation($relationName);
308 29
                    if (!empty($model->{$relationName})) {
309 27
                        if ($relation->multiple === false) {
310 17
                            $this->_prepareHasOneRelation($model, $relationName, $event);
311
                        } else {
312 18
                            $this->_prepareHasManyRelation($model, $relationName);
313
                        }
314
                    }
315
                }
316
            }
317 27
            if (!$event->isValid) {
318
                throw new Exception('One of the related model could not be validated');
319
            }
320 2
        } catch (Exception $e) {
321 2
            Yii::warning(get_class($e) . ' was thrown while saving related records during beforeValidate event: ' . $e->getMessage(), __METHOD__);
322 2
            $this->_rollback();
323 2
            $model->addError($model->formName(), $e->getMessage());
324 2
            $event->isValid = false; // Stop saving, something went wrong
325 2
            return false;
326
        }
327 27
        return true;
328
    }
329
330
    /**
331
     * Validate a relation model and add an error message to owner model attribute if needed
332
     * @param string $pettyRelationName
333
     * @param string $relationName
334
     * @param BaseActiveRecord $relationModel
335
     */
336 27
    protected function validateRelationModel($pettyRelationName, $relationName, BaseActiveRecord $relationModel)
337
    {
338
        /** @var BaseActiveRecord $model */
339 27
        $model = $this->owner;
340 27
        if (!is_null($relationModel) && ($relationModel->isNewRecord || count($relationModel->getDirtyAttributes()))) {
341 19
            if (array_key_exists($relationName, $this->_relationsScenario)) {
342 7
                $relationModel->setScenario($this->_relationsScenario[$relationName]);
343
            }
344 19
            Yii::debug("Validating {$pettyRelationName} relation model using " . $relationModel->scenario . ' scenario', __METHOD__);
345 19
            if (!$relationModel->validate()) {
346 4
                $this->_addError($relationModel, $model, $relationName, $pettyRelationName);
347
            }
348
349
        }
350 27
    }
351
352
    /**
353
     * Attach errors to owner relational attributes
354
     * @param $relationModel
355
     * @param $owner
356
     * @param $relationName
357
     * @param $pettyRelationName
358
     */
359 5
    private function _addError($relationModel, $owner, $relationName, $pettyRelationName)
360
    {
361 5
        foreach ($relationModel->errors as $attributeErrors) {
362 5
            foreach ($attributeErrors as $error) {
363 5
                $owner->addError($relationName, "{$pettyRelationName}: {$error}");
364
            }
365
        }
366 5
    }
367
368
    /**
369
     * Rollback transaction if any
370
     * @throws DbException
371
     */
372 3
    private function _rollback()
373
    {
374 3
        if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) {
375 2
            $this->_transaction->rollBack(); // If anything goes wrong, transaction will be rolled back
376 2
            Yii::info('Rolling back', __METHOD__);
377
        }
378 3
    }
379
380
    /**
381
     * Link the related models.
382
     * If the models have not been changed, nothing will be done.
383
     * Related records will be linked to the owner model using the BaseActiveRecord `link()` method.
384
     * @throws Exception
385
     */
386 27
    public function afterSave()
387
    {
388 27
        if ($this->_relationsSaveStarted === false) {
389
            /** @var BaseActiveRecord $owner */
390 27
            $owner = $this->owner;
391 27
            $this->_relationsSaveStarted = true;
392
            // Populate relations with updated values
393 27
            foreach ($this->_newRelationValue as $name => $value) {
394 27
                $this->owner->populateRelation($name, $value);
0 ignored issues
show
The method populateRelation() 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

394
                $this->owner->/** @scrutinizer ignore-call */ 
395
                              populateRelation($name, $value);

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...
395
            }
396
            try {
397 27
                foreach ($this->_relations as $relationName) {
398 27
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
399 27
                        Yii::debug("Linking {$relationName} relation", __METHOD__);
400
                        /** @var ActiveQuery $relation */
401 27
                        $relation = $owner->getRelation($relationName);
402 27
                        if ($relation->multiple === true) { // Has many relation
403 18
                            $this->_afterSaveHasManyRelation($relationName);
404
                        } else { // Has one relation
405 17
                            $this->_afterSaveHasOneRelation($relationName);
406
                        }
407 27
                        unset($this->_oldRelationValue[$relationName]);
408
                    }
409
                }
410 1
            } catch (Exception $e) {
411 1
                Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__);
412 1
                $this->_rollback();
413
                /***
414
                 * Sadly mandatory because the error occurred during afterSave event
415
                 * and we don't want the user/developper not to be aware of the issue.
416
                 ***/
417 1
                throw $e;
418
            }
419 27
            $owner->refresh();
420 27
            $this->_relationsSaveStarted = false;
421 27
            if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) {
422 21
                $this->_transaction->commit();
423
            }
424
        }
425 27
    }
426
427
    /**
428
     * Return array of columns to save to the junction table for a related model having a many-to-many relation.
429
     * @param string $relationName
430
     * @param BaseActiveRecord $model
431
     * @return array
432
     * @throws \RuntimeException
433
     */
434 14
    private function _getJunctionTableColumns($relationName, $model)
435
    {
436 14
        $junctionTableColumns = [];
437 14
        if (array_key_exists($relationName, $this->_relationsExtraColumns)) {
438 1
            if (is_callable($this->_relationsExtraColumns[$relationName])) {
439 1
                $junctionTableColumns = $this->_relationsExtraColumns[$relationName]($model);
440
            } elseif (is_array($this->_relationsExtraColumns[$relationName])) {
441
                $junctionTableColumns = $this->_relationsExtraColumns[$relationName];
442
            }
443 1
            if (!is_array($junctionTableColumns)) {
444
                throw new RuntimeException(
445
                    'Junction table columns definition must return an array, got ' . gettype($junctionTableColumns)
446
                );
447
            }
448
        }
449 14
        return $junctionTableColumns;
450
    }
451
452
    /**
453
     * Compute the difference between two set of records using primary keys "tokens"
454
     * If third parameter is set to true all initial related records will be marked for removal even if their
455
     * properties did not change. This can be handy in a many-to-many relation involving a junction table.
456
     * @param BaseActiveRecord[] $initialRelations
457
     * @param BaseActiveRecord[] $updatedRelations
458
     * @param bool $forceSave
459
     * @return array
460
     */
461 17
    private function _computePkDiff($initialRelations, $updatedRelations, $forceSave = false)
462
    {
463
        // Compute differences between initial relations and the current ones
464
        $oldPks = ArrayHelper::getColumn($initialRelations, function (BaseActiveRecord $model) {
465 13
            return implode('-', $model->getPrimaryKey(true));
466 17
        });
467
        $newPks = ArrayHelper::getColumn($updatedRelations, function (BaseActiveRecord $model) {
468 13
            return implode('-', $model->getPrimaryKey(true));
469 17
        });
470 17
        if ($forceSave) {
471 1
            $addedPks = $newPks;
472 1
            $deletedPks = $oldPks;
473
        } else {
474 16
            $identicalPks = array_intersect($oldPks, $newPks);
475 16
            $addedPks = array_values(array_diff($newPks, $identicalPks));
476 16
            $deletedPks = array_values(array_diff($oldPks, $identicalPks));
477
        }
478 17
        return [$addedPks, $deletedPks];
479
    }
480
481
    /**
482
     * Populates relations with input data
483
     * @param array $data
484
     */
485 4
    public function loadRelations($data)
486
    {
487
        /** @var BaseActiveRecord $model */
488 4
        $model = $this->owner;
489 4
        foreach ($this->_relations as $relationName) {
490 4
            $relation = $model->getRelation($relationName);
491 4
            $modelClass = $relation->modelClass;
0 ignored issues
show
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
492
            /** @var ActiveQuery $relationalModel */
493 4
            $relationalModel = new $modelClass;
494 4
            $formName = $relationalModel->formName();
495 4
            if (array_key_exists($formName, $data)) {
496 4
                $model->{$relationName} = $data[$formName];
497
            }
498
        }
499 4
    }
500
501
    /**
502
     * @param $relationName
503
     * @throws DbException
504
     */
505 18
    public function _afterSaveHasManyRelation($relationName)
506
    {
507
        /** @var BaseActiveRecord $owner */
508 18
        $owner = $this->owner;
509 18
        $relation = $owner->getRelation($relationName);
510
511
        // Process new relations
512 18
        $existingRecords = [];
513
        /** @var ActiveQuery $relationModel */
514 18
        foreach ($owner->{$relationName} as $i => $relationModel) {
515 18
            if ($relationModel->isNewRecord) {
516 10
                if (!empty($relation->via)) {
0 ignored issues
show
Accessing via on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
517 9
                    if ($relationModel->validate()) {
518 9
                        $relationModel->save();
519
                    } else {
520 1
                        $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}";
521 1
                        $this->_addError($relationModel, $owner, $relationName, $pettyRelationName);
522 1
                        throw new DbException("Related record {$pettyRelationName} could not be saved.");
523
                    }
524
                }
525 10
                $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $relationModel);
526 10
                $owner->link($relationName, $relationModel, $junctionTableColumns);
527
            } else {
528 13
                $existingRecords[] = $relationModel;
529
            }
530 18
            if (count($relationModel->dirtyAttributes)) {
531 4
                if ($relationModel->validate()) {
532 4
                    $relationModel->save();
533
                } else {
534
                    $pettyRelationName = Inflector::camel2words($relationName, true);
535
                    $this->_addError($relationModel, $owner, $relationName, $pettyRelationName);
536
                    throw new DbException("Related record {$pettyRelationName} could not be saved.");
537
                }
538
            }
539
        }
540 17
        $junctionTablePropertiesUsed = array_key_exists($relationName, $this->_relationsExtraColumns);
541
542
        // Process existing added and deleted relations
543 17
        list($addedPks, $deletedPks) = $this->_computePkDiff(
544 17
            $this->_oldRelationValue[$relationName],
545 17
            $existingRecords,
546 17
            $junctionTablePropertiesUsed
547
        );
548
549
        // Deleted relations
550
        $initialModels = ArrayHelper::index($this->_oldRelationValue[$relationName], function (BaseActiveRecord $model) {
551 13
            return implode('-', $model->getPrimaryKey(true));
552 17
        });
553 17
        $initialRelations = $owner->{$relationName};
554 17
        foreach ($deletedPks as $key) {
555 2
            $owner->unlink($relationName, $initialModels[$key], true);
556
        }
557
558
        // Added relations
559 17
        $actualModels = ArrayHelper::index(
560 17
            $junctionTablePropertiesUsed ? $initialRelations : $owner->{$relationName},
561 17
            function (BaseActiveRecord $model) {
562 17
                return implode('-', $model->getPrimaryKey(true));
563 17
            }
564
        );
565 17
        foreach ($addedPks as $key) {
566 4
            $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $actualModels[$key]);
567 4
            $owner->link($relationName, $actualModels[$key], $junctionTableColumns);
568
        }
569 17
    }
570
571
    /**
572
     * @param $relationName
573
     * @throws \yii\base\InvalidCallException
574
     */
575 17
    private function _afterSaveHasOneRelation($relationName)
576
    {
577
        /** @var BaseActiveRecord $owner */
578 17
        $owner = $this->owner;
579
580 17
        if ($this->_oldRelationValue[$relationName] !== $owner->{$relationName}) {
581 14
            if ($owner->{$relationName} instanceof BaseActiveRecord) {
582 13
                $owner->link($relationName, $owner->{$relationName});
583
            } else {
584 1
                if ($this->_oldRelationValue[$relationName] instanceof BaseActiveRecord) {
585 1
                    $owner->unlink($relationName, $this->_oldRelationValue[$relationName]);
586
                }
587
            }
588
        }
589 17
        if ($owner->{$relationName} instanceof BaseActiveRecord) {
590 15
            $owner->{$relationName}->save();
591
        }
592 17
    }
593
594
    /**
595
     * @param BaseActiveRecord $model
596
     * @param $relationName
597
     */
598 18
    private function _prepareHasManyRelation(BaseActiveRecord $model, $relationName)
599
    {
600
        /** @var BaseActiveRecord $relationModel */
601 18
        foreach ($model->{$relationName} as $i => $relationModel) {
602 18
            $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}";
603 18
            $this->validateRelationModel($pettyRelationName, $relationName, $relationModel);
604
        }
605 18
    }
606
607
    /**
608
     * @param BaseActiveRecord $model
609
     * @param ModelEvent $event
610
     * @param $relationName
611
     */
612 17
    private function _prepareHasOneRelation(BaseActiveRecord $model, $relationName, ModelEvent $event)
613
    {
614
        /** @var ActiveQuery $relation */
615 17
        $relation = $model->getRelation($relationName);
616 17
        $relationModel = $model->{$relationName};
617 17
        $p1 = $model->isPrimaryKey(array_keys($relation->link));
618 17
        $p2 = $relationModel::isPrimaryKey(array_values($relation->link));
619 17
        $pettyRelationName = Inflector::camel2words($relationName, true);
620 17
        if ($relationModel->getIsNewRecord() && $p1 && !$p2) {
621
            // Save Has one relation new record
622 10
            $this->validateRelationModel($pettyRelationName, $relationName, $model->{$relationName});
623 10
            if ($event->isValid && (count($model->dirtyAttributes) || $model->{$relationName}->isNewRecord)) {
624 10
                Yii::debug("Saving {$pettyRelationName} relation model", __METHOD__);
625 10
                $model->{$relationName}->save(false);
626
            }
627
        } else {
628 10
            $this->validateRelationModel($pettyRelationName, $relationName, $relationModel);
629
        }
630 15
    }
631
}
632