-
Notifications
You must be signed in to change notification settings - Fork 1
/
RelationFollowBehavior.php
78 lines (66 loc) · 2.24 KB
/
RelationFollowBehavior.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace diiimonn\behaviors;
use Yii;
use yii\db\ActiveRecord;
use yii\base\Behavior;
/**
* Class RelationFollowBehavior
* @package diiimonn\behaviors
*/
class RelationFollowBehavior extends Behavior
{
/**
* @var ActiveRecord
*/
public $owner;
public $relations = [];
/**
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
];
}
public function afterSave()
{
$data = [];
if (isset($_POST[$this->owner->formName()])) {
$data = $_POST[$this->owner->formName()];
}
if ($data) {
foreach ($data as $attribute => $value) {
if (!in_array($attribute, $this->relations)) {
continue;
}
if (is_array($value)) {
$relation = $this->owner->getRelation($attribute);
if ($relation->via !== null) {
/** @var ActiveRecord $foreignModel */
$foreignModel = $relation->modelClass;
$this->owner->unlinkAll($attribute, true);
if (is_array(current($value))) {
foreach($value as $data) {
if (isset($data[$foreignModel::primaryKey()[0]]) && $data[$foreignModel::primaryKey()[0]] > 0) {
$fm = $foreignModel::findOne($data[$foreignModel::primaryKey()[0]]);
$fm->load($data, '');
$this->owner->link($attribute, $fm);
}
}
} else {
foreach($value as $fk) {
if (preg_match('~^\d+$~', $fk)) {
$this->owner->link($attribute, $foreignModel::findOne($fk));
}
}
}
}
} else {
$this->owner->unlinkAll($attribute, true);
}
}
}
}
}