Passed
Push — master ( f13e36...6c96cb )
by Alban
02:33
created

SaveRelationsBehavior::prettyRelationName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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