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