Skip to content

Commit 19a44c9

Browse files
committed
split main method into smaller methods
1 parent 7915a46 commit 19a44c9

File tree

1 file changed

+35
-10
lines changed

1 file changed

+35
-10
lines changed

src/LinkAllBehavior.php

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,22 @@
1313

1414
/**
1515
* LinkAllBehavior
16-
*
16+
*
1717
* Wraps the functionality of `ActiveRecordBase::link()` and `ActiveRecordBase::unlink()`
1818
* to allow a list of models to be linked, and optionally unlinking existing models.
19-
*
19+
*
2020
* Checks are performed to ensure existing links are not duplicated.
2121
*
2222
* @property BaseActiveRecord $owner
23-
*
23+
*
2424
* @author Brett O'Donnell <cornernote@gmail.com>
2525
*/
2626
class LinkAllBehavior extends Behavior
2727
{
2828

2929
/**
3030
* Manages the relationships between models.
31-
*
31+
*
3232
* @param string $name the case sensitive name of the relationship.
3333
* @param BaseActiveRecord[] $models the related models to be linked.
3434
* @param array $extraColumns additional column values to be saved into the junction table.
@@ -47,16 +47,41 @@ public function linkAll($name, $models, $extraColumns = [], $unlink = true, $del
4747
$oldModels = $this->owner->{$name};
4848
$oldModelPks = ArrayHelper::map($oldModels, $modelPk, $modelPk);
4949

50-
// remove old links
5150
if ($unlink) {
52-
foreach ($oldModels as $oldModel) {
53-
if (!in_array($oldModel->{$modelPk}, $newModelPks)) {
54-
$this->owner->unlink($name, $oldModel, $delete);
55-
}
51+
$this->unlink($name, $modelPk, $oldModels, $newModelPks, $delete);
52+
}
53+
$this->link($name, $modelPk, $models, $oldModelPks, $extraColumns);
54+
}
55+
56+
/**
57+
* Remove old links
58+
*
59+
* @param string $name
60+
* @param int|string $modelPk
61+
* @param BaseActiveRecord[] $oldModels
62+
* @param array $newModelPks
63+
* @param bool $delete
64+
*/
65+
protected function unlink($name, $modelPk, $oldModels, $newModelPks, $delete)
66+
{
67+
foreach ($oldModels as $oldModel) {
68+
if (!in_array($oldModel->{$modelPk}, $newModelPks)) {
69+
$this->owner->unlink($name, $oldModel, $delete);
5670
}
5771
}
72+
}
5873

59-
// add new links
74+
/**
75+
* Add new links
76+
*
77+
* @param string $name
78+
* @param int|string $modelPk
79+
* @param BaseActiveRecord[] $models
80+
* @param array $oldModelPks
81+
* @param array $extraColumns
82+
*/
83+
protected function link($name, $modelPk, $models, $oldModelPks, $extraColumns)
84+
{
6085
foreach ($models as $newModel) {
6186
if (!in_array($newModel->{$modelPk}, $oldModelPks)) {
6287
$this->owner->link($name, $newModel, $extraColumns);

0 commit comments

Comments
 (0)