Passed
Push — master ( 928dfb...f13e36 )
by Alban
02:07
created

SaveRelationsBehavior::startTransactionForModel()   B

Complexity

Conditions 8
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 8

Importance

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