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 | /** @var BaseActiveRecord|array $viaQuery */ |
||
221 | $viaQuery = $relation->via; |
||
0 ignored issues
–
show
|
|||
222 | $link = $viaQuery->link; |
||
223 | 7 | } elseif (is_array($relation->via)) { |
|
224 | 2 | list($viaName, $viaQuery) = $relation->via; |
|
225 | 2 | $link = $viaQuery->link; |
|
226 | } else { |
||
227 | 5 | $link = $relation->link; |
|
228 | } |
||
229 | 7 | foreach ($link as $relatedAttribute => $modelAttribute) { |
|
230 | 7 | if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { |
|
231 | 7 | $fks[$modelAttribute] = $data[$modelAttribute]; |
|
232 | } |
||
233 | } |
||
234 | } |
||
235 | } else { |
||
236 | 4 | $fks = $data; |
|
237 | } |
||
238 | // Load existing model or create one if no key was provided and data is not empty |
||
239 | /** @var BaseActiveRecord $relationModel */ |
||
240 | 13 | $relationModel = null; |
|
241 | 13 | if (!empty($fks)) { |
|
242 | 8 | $relationModel = $modelClass::findOne($fks); |
|
243 | } |
||
244 | 13 | if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) { |
|
245 | 8 | $relationModel = new $modelClass; |
|
246 | } |
||
247 | 13 | if (($relationModel instanceof BaseActiveRecord) && is_array($data)) { |
|
248 | 9 | $relationModel->setAttributes($data); |
|
249 | } |
||
250 | 13 | return $relationModel; |
|
251 | } |
||
252 | |||
253 | /** |
||
254 | * Before the owner model validation, save related models. |
||
255 | * For `hasOne()` relations, set the according foreign keys of the owner model to be able to validate it |
||
256 | * @param ModelEvent $event |
||
257 | * @throws DbException |
||
258 | * @throws \yii\base\InvalidConfigException |
||
259 | */ |
||
260 | 29 | public function beforeValidate(ModelEvent $event) |
|
261 | { |
||
262 | 29 | if ($this->_relationsSaveStarted === false && !empty($this->_oldRelationValue)) { |
|
263 | /* @var $model BaseActiveRecord */ |
||
264 | 29 | $model = $this->owner; |
|
265 | 29 | if ($this->saveRelatedRecords($model, $event)) { |
|
266 | // If relation is has_one, try to set related model attributes |
||
267 | 27 | foreach ($this->_relations as $relationName) { |
|
268 | 27 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|
269 | /** @var ActiveQuery $relation */ |
||
270 | 27 | $relation = $model->getRelation($relationName); |
|
271 | 27 | if ($relation->multiple === false && !empty($model->{$relationName})) { |
|
272 | 15 | Yii::debug("Setting foreign keys for {$relationName}", __METHOD__); |
|
273 | 15 | foreach ($relation->link as $relatedAttribute => $modelAttribute) { |
|
274 | 15 | if ($model->{$modelAttribute} !== $model->{$relationName}->{$relatedAttribute}) { |
|
275 | 15 | $model->{$modelAttribute} = $model->{$relationName}->{$relatedAttribute}; |
|
276 | } |
||
277 | } |
||
278 | } |
||
279 | } |
||
280 | } |
||
281 | } |
||
282 | } |
||
283 | 29 | } |
|
284 | |||
285 | /** |
||
286 | * For each related model, try to save it first. |
||
287 | * If set in the owner model, operation is done in a transactional way so if one of the models should not validate |
||
288 | * or be saved, a rollback will occur., |
||
289 | * This is done during the before validation process to be able to set the related foreign keys. |
||
290 | * @param BaseActiveRecord $model |
||
291 | * @param ModelEvent $event |
||
292 | * @return bool |
||
293 | * @throws DbException |
||
294 | * @throws \yii\base\InvalidConfigException |
||
295 | */ |
||
296 | 29 | protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event) |
|
297 | { |
||
298 | if ( |
||
299 | 29 | method_exists($model, 'isTransactional') |
|
300 | 29 | && is_null($model->getDb()->transaction) |
|
301 | && ( |
||
302 | 29 | ($model->isNewRecord && $model->isTransactional($model::OP_INSERT)) |
|
303 | 21 | || (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE)) |
|
304 | 6 | || $model->isTransactional($model::OP_ALL) |
|
305 | ) |
||
306 | ) { |
||
307 | 23 | $this->_transaction = $model->getDb()->beginTransaction(); |
|
308 | } |
||
309 | try { |
||
310 | 29 | foreach ($this->_relations as $relationName) { |
|
311 | 29 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|
312 | /** @var ActiveQuery $relation */ |
||
313 | 29 | $relation = $model->getRelation($relationName); |
|
314 | 29 | if (!empty($model->{$relationName})) { |
|
315 | 27 | if ($relation->multiple === false) { |
|
316 | 17 | $this->_prepareHasOneRelation($model, $relationName, $event); |
|
317 | } else { |
||
318 | 18 | $this->_prepareHasManyRelation($model, $relationName); |
|
319 | } |
||
320 | } |
||
321 | } |
||
322 | } |
||
323 | 27 | if (!$event->isValid) { |
|
324 | throw new Exception('One of the related model could not be validated'); |
||
325 | } |
||
326 | 2 | } catch (Exception $e) { |
|
327 | 2 | Yii::warning(get_class($e) . ' was thrown while saving related records during beforeValidate event: ' . $e->getMessage(), __METHOD__); |
|
328 | 2 | $this->_rollback(); |
|
329 | 2 | $model->addError($model->formName(), $e->getMessage()); |
|
330 | 2 | $event->isValid = false; // Stop saving, something went wrong |
|
331 | 2 | return false; |
|
332 | } |
||
333 | 27 | return true; |
|
334 | } |
||
335 | |||
336 | /** |
||
337 | * Validate a relation model and add an error message to owner model attribute if needed |
||
338 | * @param string $pettyRelationName |
||
339 | * @param string $relationName |
||
340 | * @param BaseActiveRecord $relationModel |
||
341 | */ |
||
342 | 27 | protected function validateRelationModel($pettyRelationName, $relationName, BaseActiveRecord $relationModel) |
|
343 | { |
||
344 | /** @var BaseActiveRecord $model */ |
||
345 | 27 | $model = $this->owner; |
|
346 | 27 | if (!is_null($relationModel) && ($relationModel->isNewRecord || count($relationModel->getDirtyAttributes()))) { |
|
347 | 19 | if (array_key_exists($relationName, $this->_relationsScenario)) { |
|
348 | 7 | $relationModel->setScenario($this->_relationsScenario[$relationName]); |
|
349 | } |
||
350 | 19 | Yii::debug("Validating {$pettyRelationName} relation model using " . $relationModel->scenario . ' scenario', __METHOD__); |
|
351 | 19 | if (!$relationModel->validate()) { |
|
352 | 4 | $this->_addError($relationModel, $model, $relationName, $pettyRelationName); |
|
353 | } |
||
354 | |||
355 | } |
||
356 | 27 | } |
|
357 | |||
358 | /** |
||
359 | * Attach errors to owner relational attributes |
||
360 | * @param $relationModel |
||
361 | * @param $owner |
||
362 | * @param $relationName |
||
363 | * @param $pettyRelationName |
||
364 | */ |
||
365 | 5 | private function _addError($relationModel, $owner, $relationName, $pettyRelationName) |
|
366 | { |
||
367 | 5 | foreach ($relationModel->errors as $attributeErrors) { |
|
368 | 5 | foreach ($attributeErrors as $error) { |
|
369 | 5 | $owner->addError($relationName, "{$pettyRelationName}: {$error}"); |
|
370 | } |
||
371 | } |
||
372 | 5 | } |
|
373 | |||
374 | /** |
||
375 | * Rollback transaction if any |
||
376 | * @throws DbException |
||
377 | */ |
||
378 | 3 | private function _rollback() |
|
379 | { |
||
380 | 3 | if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
|
381 | 2 | $this->_transaction->rollBack(); // If anything goes wrong, transaction will be rolled back |
|
382 | 2 | Yii::info('Rolling back', __METHOD__); |
|
383 | } |
||
384 | 3 | } |
|
385 | |||
386 | /** |
||
387 | * Link the related models. |
||
388 | * If the models have not been changed, nothing will be done. |
||
389 | * Related records will be linked to the owner model using the BaseActiveRecord `link()` method. |
||
390 | * @throws Exception |
||
391 | */ |
||
392 | 27 | public function afterSave() |
|
393 | { |
||
394 | 27 | if ($this->_relationsSaveStarted === false) { |
|
395 | /** @var BaseActiveRecord $owner */ |
||
396 | 27 | $owner = $this->owner; |
|
397 | 27 | $this->_relationsSaveStarted = true; |
|
398 | // Populate relations with updated values |
||
399 | 27 | foreach ($this->_newRelationValue as $name => $value) { |
|
400 | 27 | $owner->populateRelation($name, $value); |
|
401 | } |
||
402 | try { |
||
403 | 27 | foreach ($this->_relations as $relationName) { |
|
404 | 27 | if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing... |
|
405 | 27 | Yii::debug("Linking {$relationName} relation", __METHOD__); |
|
406 | /** @var ActiveQuery $relation */ |
||
407 | 27 | $relation = $owner->getRelation($relationName); |
|
408 | 27 | if ($relation->multiple === true) { // Has many relation |
|
409 | 18 | $this->_afterSaveHasManyRelation($relationName); |
|
410 | } else { // Has one relation |
||
411 | 17 | $this->_afterSaveHasOneRelation($relationName); |
|
412 | } |
||
413 | 27 | unset($this->_oldRelationValue[$relationName]); |
|
414 | } |
||
415 | } |
||
416 | 1 | } catch (Exception $e) { |
|
417 | 1 | Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__); |
|
418 | 1 | $this->_rollback(); |
|
419 | /*** |
||
420 | * Sadly mandatory because the error occurred during afterSave event |
||
421 | * and we don't want the user/developper not to be aware of the issue. |
||
422 | ***/ |
||
423 | 1 | throw $e; |
|
424 | } |
||
425 | 27 | $owner->refresh(); |
|
426 | 27 | $this->_relationsSaveStarted = false; |
|
427 | 27 | if (($this->_transaction instanceof Transaction) && $this->_transaction->isActive) { |
|
428 | 21 | $this->_transaction->commit(); |
|
429 | } |
||
430 | } |
||
431 | 27 | } |
|
432 | |||
433 | /** |
||
434 | * Return array of columns to save to the junction table for a related model having a many-to-many relation. |
||
435 | * @param string $relationName |
||
436 | * @param BaseActiveRecord $model |
||
437 | * @return array |
||
438 | * @throws \RuntimeException |
||
439 | */ |
||
440 | 14 | private function _getJunctionTableColumns($relationName, $model) |
|
441 | { |
||
442 | 14 | $junctionTableColumns = []; |
|
443 | 14 | if (array_key_exists($relationName, $this->_relationsExtraColumns)) { |
|
444 | 1 | if (is_callable($this->_relationsExtraColumns[$relationName])) { |
|
445 | 1 | $junctionTableColumns = $this->_relationsExtraColumns[$relationName]($model); |
|
446 | } elseif (is_array($this->_relationsExtraColumns[$relationName])) { |
||
447 | $junctionTableColumns = $this->_relationsExtraColumns[$relationName]; |
||
448 | } |
||
449 | 1 | if (!is_array($junctionTableColumns)) { |
|
450 | throw new RuntimeException( |
||
451 | 'Junction table columns definition must return an array, got ' . gettype($junctionTableColumns) |
||
452 | ); |
||
453 | } |
||
454 | } |
||
455 | 14 | return $junctionTableColumns; |
|
456 | } |
||
457 | |||
458 | /** |
||
459 | * Compute the difference between two set of records using primary keys "tokens" |
||
460 | * If third parameter is set to true all initial related records will be marked for removal even if their |
||
461 | * properties did not change. This can be handy in a many-to-many relation involving a junction table. |
||
462 | * @param BaseActiveRecord[] $initialRelations |
||
463 | * @param BaseActiveRecord[] $updatedRelations |
||
464 | * @param bool $forceSave |
||
465 | * @return array |
||
466 | */ |
||
467 | 17 | private function _computePkDiff($initialRelations, $updatedRelations, $forceSave = false) |
|
468 | { |
||
469 | // Compute differences between initial relations and the current ones |
||
470 | $oldPks = ArrayHelper::getColumn($initialRelations, function (BaseActiveRecord $model) { |
||
471 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|
472 | 17 | }); |
|
473 | $newPks = ArrayHelper::getColumn($updatedRelations, function (BaseActiveRecord $model) { |
||
474 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|
475 | 17 | }); |
|
476 | 17 | if ($forceSave) { |
|
477 | 1 | $addedPks = $newPks; |
|
478 | 1 | $deletedPks = $oldPks; |
|
479 | } else { |
||
480 | 16 | $identicalPks = array_intersect($oldPks, $newPks); |
|
481 | 16 | $addedPks = array_values(array_diff($newPks, $identicalPks)); |
|
482 | 16 | $deletedPks = array_values(array_diff($oldPks, $identicalPks)); |
|
483 | } |
||
484 | 17 | return [$addedPks, $deletedPks]; |
|
485 | } |
||
486 | |||
487 | /** |
||
488 | * Populates relations with input data |
||
489 | * @param array $data |
||
490 | */ |
||
491 | 4 | public function loadRelations($data) |
|
492 | { |
||
493 | /** @var BaseActiveRecord $model */ |
||
494 | 4 | $model = $this->owner; |
|
495 | 4 | foreach ($this->_relations as $relationName) { |
|
496 | /** @var ActiveQuery $relation */ |
||
497 | 4 | $relation = $model->getRelation($relationName); |
|
498 | 4 | $modelClass = $relation->modelClass; |
|
499 | /** @var ActiveQuery $relationalModel */ |
||
500 | 4 | $relationalModel = new $modelClass; |
|
501 | 4 | $formName = $relationalModel->formName(); |
|
502 | 4 | if (array_key_exists($formName, $data)) { |
|
503 | 4 | $model->{$relationName} = $data[$formName]; |
|
504 | } |
||
505 | } |
||
506 | 4 | } |
|
507 | |||
508 | /** |
||
509 | * @param $relationName |
||
510 | * @throws DbException |
||
511 | */ |
||
512 | 18 | public function _afterSaveHasManyRelation($relationName) |
|
513 | { |
||
514 | /** @var BaseActiveRecord $owner */ |
||
515 | 18 | $owner = $this->owner; |
|
516 | /** @var ActiveQuery $relation */ |
||
517 | 18 | $relation = $owner->getRelation($relationName); |
|
518 | |||
519 | // Process new relations |
||
520 | 18 | $existingRecords = []; |
|
521 | /** @var ActiveQuery $relationModel */ |
||
522 | 18 | foreach ($owner->{$relationName} as $i => $relationModel) { |
|
523 | 18 | if ($relationModel->isNewRecord) { |
|
524 | 10 | if (!empty($relation->via)) { |
|
525 | 9 | if ($relationModel->validate()) { |
|
526 | 9 | $relationModel->save(); |
|
527 | } else { |
||
528 | 1 | $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
|
529 | 1 | $this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
|
530 | 1 | throw new DbException("Related record {$pettyRelationName} could not be saved."); |
|
531 | } |
||
532 | } |
||
533 | 10 | $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $relationModel); |
|
534 | 10 | $owner->link($relationName, $relationModel, $junctionTableColumns); |
|
535 | } else { |
||
536 | 13 | $existingRecords[] = $relationModel; |
|
537 | } |
||
538 | 18 | if (count($relationModel->dirtyAttributes)) { |
|
539 | 4 | if ($relationModel->validate()) { |
|
540 | 4 | $relationModel->save(); |
|
541 | } else { |
||
542 | $pettyRelationName = Inflector::camel2words($relationName, true); |
||
543 | $this->_addError($relationModel, $owner, $relationName, $pettyRelationName); |
||
544 | throw new DbException("Related record {$pettyRelationName} could not be saved."); |
||
545 | } |
||
546 | } |
||
547 | } |
||
548 | 17 | $junctionTablePropertiesUsed = array_key_exists($relationName, $this->_relationsExtraColumns); |
|
549 | |||
550 | // Process existing added and deleted relations |
||
551 | 17 | list($addedPks, $deletedPks) = $this->_computePkDiff( |
|
552 | 17 | $this->_oldRelationValue[$relationName], |
|
553 | 17 | $existingRecords, |
|
554 | 17 | $junctionTablePropertiesUsed |
|
555 | ); |
||
556 | |||
557 | // Deleted relations |
||
558 | $initialModels = ArrayHelper::index($this->_oldRelationValue[$relationName], function (BaseActiveRecord $model) { |
||
559 | 13 | return implode('-', $model->getPrimaryKey(true)); |
|
560 | 17 | }); |
|
561 | 17 | $initialRelations = $owner->{$relationName}; |
|
562 | 17 | foreach ($deletedPks as $key) { |
|
563 | 2 | $owner->unlink($relationName, $initialModels[$key], true); |
|
564 | } |
||
565 | |||
566 | // Added relations |
||
567 | 17 | $actualModels = ArrayHelper::index( |
|
568 | 17 | $junctionTablePropertiesUsed ? $initialRelations : $owner->{$relationName}, |
|
569 | 17 | function (BaseActiveRecord $model) { |
|
570 | 17 | return implode('-', $model->getPrimaryKey(true)); |
|
571 | 17 | } |
|
572 | ); |
||
573 | 17 | foreach ($addedPks as $key) { |
|
574 | 4 | $junctionTableColumns = $this->_getJunctionTableColumns($relationName, $actualModels[$key]); |
|
575 | 4 | $owner->link($relationName, $actualModels[$key], $junctionTableColumns); |
|
576 | } |
||
577 | 17 | } |
|
578 | |||
579 | /** |
||
580 | * @param $relationName |
||
581 | * @throws \yii\base\InvalidCallException |
||
582 | */ |
||
583 | 17 | private function _afterSaveHasOneRelation($relationName) |
|
584 | { |
||
585 | /** @var BaseActiveRecord $owner */ |
||
586 | 17 | $owner = $this->owner; |
|
587 | |||
588 | 17 | if ($this->_oldRelationValue[$relationName] !== $owner->{$relationName}) { |
|
589 | 14 | if ($owner->{$relationName} instanceof BaseActiveRecord) { |
|
590 | 13 | $owner->link($relationName, $owner->{$relationName}); |
|
591 | } else { |
||
592 | 1 | if ($this->_oldRelationValue[$relationName] instanceof BaseActiveRecord) { |
|
593 | 1 | $owner->unlink($relationName, $this->_oldRelationValue[$relationName]); |
|
594 | } |
||
595 | } |
||
596 | } |
||
597 | 17 | if ($owner->{$relationName} instanceof BaseActiveRecord) { |
|
598 | 15 | $owner->{$relationName}->save(); |
|
599 | } |
||
600 | 17 | } |
|
601 | |||
602 | /** |
||
603 | * @param BaseActiveRecord $model |
||
604 | * @param $relationName |
||
605 | */ |
||
606 | 18 | private function _prepareHasManyRelation(BaseActiveRecord $model, $relationName) |
|
607 | { |
||
608 | /** @var BaseActiveRecord $relationModel */ |
||
609 | 18 | foreach ($model->{$relationName} as $i => $relationModel) { |
|
610 | 18 | $pettyRelationName = Inflector::camel2words($relationName, true) . " #{$i}"; |
|
611 | 18 | $this->validateRelationModel($pettyRelationName, $relationName, $relationModel); |
|
612 | } |
||
613 | 18 | } |
|
614 | |||
615 | /** |
||
616 | * @param BaseActiveRecord $model |
||
617 | * @param ModelEvent $event |
||
618 | * @param $relationName |
||
619 | */ |
||
620 | 17 | private function _prepareHasOneRelation(BaseActiveRecord $model, $relationName, ModelEvent $event) |
|
621 | { |
||
622 | /** @var ActiveQuery $relation */ |
||
623 | 17 | $relation = $model->getRelation($relationName); |
|
624 | 17 | $relationModel = $model->{$relationName}; |
|
625 | 17 | $p1 = $model->isPrimaryKey(array_keys($relation->link)); |
|
626 | 17 | $p2 = $relationModel::isPrimaryKey(array_values($relation->link)); |
|
627 | 17 | $pettyRelationName = Inflector::camel2words($relationName, true); |
|
628 | 17 | if ($relationModel->getIsNewRecord() && $p1 && !$p2) { |
|
629 | // Save Has one relation new record |
||
630 | 10 | $this->validateRelationModel($pettyRelationName, $relationName, $model->{$relationName}); |
|
631 | 10 | if ($event->isValid && (count($model->dirtyAttributes) || $model->{$relationName}->isNewRecord)) { |
|
632 | 10 | Yii::debug("Saving {$pettyRelationName} relation model", __METHOD__); |
|
633 | 10 | $model->{$relationName}->save(false); |
|
634 | } |
||
635 | } else { |
||
636 | 10 | $this->validateRelationModel($pettyRelationName, $relationName, $relationModel); |
|
637 | } |
||
638 | 15 | } |
|
639 | } |
||
640 |
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..