-
Notifications
You must be signed in to change notification settings - Fork 0
/
AttrsWatcherBehavior.php
108 lines (96 loc) · 2.95 KB
/
AttrsWatcherBehavior.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php
namespace lebedyncrs\attrswatcher;
use yii\base\Behavior;
use yii\db\BaseActiveRecord;
use yii\base\InvalidConfigException;
/**
*
*/
class AttrsWatcherBehavior extends Behavior {
const FROM = 'from';
const TO = 'to';
const ATTRIBUTE = 'attribute';
/**
* @var array
*/
public $attributes;
/**
* @var mixed
*/
public $values;
/**
* @inheritdoc
*/
public function events() {
return [
BaseActiveRecord::EVENT_AFTER_VALIDATE => 'setAttribute',
];
}
/**
* @inheritdoc
*/
public function init() {
parent::init();
if (is_null($this->values)) {
$this->values = time();
}
}
public function setAttribute($event) {
foreach ($this->attributes as $key => $value) {
if (is_string($key) && $this->owner->hasAttribute($key)) {
$attrName = $key;
} elseif (is_string($value) && $this->owner->hasAttribute($key)) {
$attrName = $value;
}
if (!isset($attrName)) {
throw new InvalidConfigException("Attribute dosen't exist");
}
if ($this->isAttrChanged($attrName)) {
$this->owner->{$this->attributes[$attrName][self::ATTRIBUTE]} = $this->getValue($this->attributes[$attrName][self::ATTRIBUTE]);
}
}
}
/**
* check if attr is changed
* @param string $attrName
* @return boolean
*/
public function isAttrChanged($attrName) {
if ($this->owner->isAttributeChanged($attrName)) {
$fromExsistence = isset($this->attributes[$attrName][self::FROM]);
$toExsistence = isset($this->attributes[$attrName][self::TO]);
if ($fromExsistence && $toExsistence) {
if ($this->attributes[$attrName][self::FROM] == $this->owner->getOldAttribute($attrName) && $this->owner->{$attrName} == $this->attributes[$attrName][self::TO]) {
return true;
}
return false;
} elseif ($fromExsistence) {
if ($this->attributes[$attrName][self::FROM] == $this->owner->getOldAttribute($attrName)) {
return true;
}
return false;
} elseif ($toExsistence) {
if ($this->attributes[$attrName][self::TO] == $this->owner->{$attrName}) {
return true;
}
return false;
} else {
return true;
}
}
return false;
}
/**
* @param string $attrName
* @return mixed
*/
public function getValue($attrName) {
if (is_array($this->values) && isset($this->values[$attrName])) {
return $this->values[$attrName];
}
if(is_callable($this->values)) {
return call_user_func($this->values);
}
return time();
}
}