-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBehavior.php
137 lines (114 loc) · 3.1 KB
/
Behavior.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
/**
* @since 23.07.13 15:06
* @author Arsen Abdusalamov
*/
namespace mekegi\ArLogger;
use \Yii;
use \CLogger;
use \CActiveRecordBehavior;
Use \Exception;
abstract class Behavior extends CActiveRecordBehavior
{
const EVENT_DELETE = 'delete';
const EVENT_SAVE = 'save';
public $bactrace = false;
public $dontLogFields = [];
protected $_oldAttributes = [];
/**
* @since 23.07.13 15:26
* @author Arsen Abdusalamov
* @return []
*/
protected function getDiffs()
{
$new = $this->owner->attributes;
$old = $this->getOldAttributes();
$res = array_diff_assoc($new, $old);
unset($res['updated_at']);
foreach($this->dontLogFields as $key) {
unset($res[$key]);
}
foreach ($res as $key=>$value) {
if ($this->normalize($value) == $this->normalize($old[$key])) {
unset($res[$key]);
}
}
return $res;
}
/**
* @since 26.09.13 16:48
* @author Arsen Abdusalamov
* @return false
*/
protected function normalize($value)
{
$trimVal = preg_replace('/^(.*)\.0+/', '$1', trim($value));
return empty($trimVal) || in_array($trimVal, ['0000-00-00 00:00:00', '0.0'], true)
? NULL
: $trimVal;
}
public function afterFind($event)
{
$result = parent::afterFind($event);
$this->setOldAttributes($this->owner->getAttributes());
return $result;
}
protected function getOldAttributes()
{
return $this->_oldAttributes;
}
protected function setOldAttributes($value)
{
$this->_oldAttributes = $value;
}
/**
* @since 22.07.13 16:17
* @author Arsen Abdusalamov
* @return array
*/
protected function getBackTrace($skip = 8, $lineNumber = 2)
{
if (!$this->bactrace) {
return [];
}
$result = [];
$backtrace = debug_backtrace(0);
for ($i = $skip; ($i - $skip) < $lineNumber; $i++) {
if (!isset($backtrace[$i])) {
break;
}
$result[] = (empty($backtrace[$i]['file']) ? '(closure)' : $backtrace[$i]['file'])
. ':' . (empty($backtrace[$i]['line']) ? '(closure)' : $backtrace[$i]['line']);
}
return $result;
}
public function afterDelete($event)
{
parent::afterDelete($event);
try {
if ($diff = $this->getDiffs()) {
$this->logChanges(self::EVENT_DELETE, $diff);
}
}
catch (Exception $e) {
Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
}
}
public function afterSave($event)
{
parent::afterSave($event);
try {
if ($diff = $this->getDiffs()) {
$this->logChanges(self::EVENT_SAVE, $diff);
}
}
catch (Exception $e) {
Yii::log($e->getMessage(), CLogger::LEVEL_ERROR);
}
}
/**
*
*/
abstract protected function logChanges($title, array $diff);
}