AuditTrailBehavior.php 10.5 KB
Newer Older
Marcello Pivanti's avatar
Marcello Pivanti committed
1
<?php
Aster's avatar
Aster committed
2
namespace arter\amos\audit;
Marcello Pivanti's avatar
Marcello Pivanti committed
3

Aster's avatar
Aster committed
4
use arter\amos\audit\models\AuditTrail;
Marcello Pivanti's avatar
Marcello Pivanti committed
5
6
7
8
9
10
11
12
13

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\helpers\Json;
use yii\db\Query;

/**
 * Class AuditTrailBehavior
Aster's avatar
Aster committed
14
 * @package arter\amos\audit
Marcello Pivanti's avatar
Marcello Pivanti committed
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
 *
 * @property \yii\db\ActiveRecord $owner
 */
class AuditTrailBehavior extends Behavior
{

    /**
     * Array with fields to save
     * You don't need to configure both `allowed` and `ignored`
     * @var array
     */
    public $allowed = [];

    /**
     * Array with fields to ignore
     * You don't need to configure both `allowed` and `ignored`
     * @var array
     */
    public $ignored = [];

    /**
     * Array with classes to ignore
     * @var array
     */
    public $ignoredClasses = [];

    /**
     * Timestamp attributes should, in most cases, be ignored. If both AudittrailBehavior and
     * TimestampBehavior logs the created_at and updated_at fields, the data is saved twice.
     * In case you want to log them, you can unset the column from this timestamp column name suggestions.
     * Set to null to disable this filter and log all columns.
     * @var null|array
     */
    public $timestamp_fields = ['created', 'updated', 'created_at', 'updated_at', 'timestamp'];

    /**
     * Is the behavior is active or not
     * @var boolean
     */
    public $active = true;

    /**
     * Date format to use in stamp - set to "Y-m-d H:i:s" for datetime or "U" for timestamp
     * @var string
     */
    public $dateFormat = 'Y-m-d H:i:s';

    /**
     * @var array
     */
    private $_oldAttributes = [];

    /**
     * Array with fields you want to override before saving the row into audit_trail table
     * @var array
     */
    public $override = [];

    /**
     * @inheritdoc
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
            ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
            ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
            ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
        ];
    }

    /**
     *
     */
    public function afterFind()
    {
        $this->setOldAttributes($this->owner->getAttributes());
    }

    /**
     *
     */
    public function afterInsert()
    {
        $this->audit('CREATE');
        $this->setOldAttributes($this->owner->getAttributes());
    }

    /**
     *
     */
    public function afterUpdate()
    {
        $this->audit('UPDATE');
        $this->setOldAttributes($this->owner->getAttributes());
    }

    /**
     *
     */
    public function afterDelete()
    {
        $this->audit('DELETE');
        $this->setOldAttributes([]);
    }

    /**
     * @param $action
     * @throws \yii\db\Exception
     */
    public function audit($action)
    {
        // Not active? get out of here
        if (!$this->active) {
            return;
        }
        
        // Lets check if the whole class should be ignored
        if (sizeof($this->ignoredClasses) > 0 && array_search(get_class($this->owner), $this->ignoredClasses) !== false) {
            return;
        }
        
        // If this is a delete then just write one row and get out of here
        if ($action == 'DELETE') {
            $this->saveAuditTrailDelete();
            return;
        }
        
        // Now lets actually write the attributes
        $this->auditAttributes($action);
    }

    /**
     * Clean attributes of fields that are not allowed or ignored.
     *
     * @param $attributes
     * @return mixed
     */
    protected function cleanAttributes($attributes)
    {
        $attributes = $this->cleanAttributesAllowed($attributes);
        $attributes = $this->cleanAttributesIgnored($attributes);
        $attributes = $this->cleanAttributesOverride($attributes);
        return $attributes;
    }

    /**
     * Unset attributes which are not allowed
     *
     * @param $attributes
     * @return mixed
     */
    protected function cleanAttributesAllowed($attributes)
    {
        if (sizeof($this->allowed) > 0) {
            foreach ($attributes as $f => $v) {
                if (array_search($f, $this->allowed) === false) {
                    unset($attributes[$f]);
                }
            }
        }
        return $attributes;
    }

    /**
     * Unset attributes which are ignored
     *
     * @param $attributes
     * @return mixed
     */
    protected function cleanAttributesIgnored($attributes)
    {
        if(is_array($this->timestamp_fields) && count($this->timestamp_fields) > 0) {
            $this->ignored = array_merge($this->ignored, $this->timestamp_fields);
        }

        if (count($this->ignored) > 0) {
            foreach ($attributes as $f => $v) {
                if (array_search($f, $this->ignored) !== false) {
                    unset($attributes[$f]);
                }
            }
        }
        return $attributes;
    }

    /**
     * attributes which need to get override with a new value
     *
     * @param $attributes
     * @return mixed
     */
    protected function cleanAttributesOverride($attributes)
    {
        if (sizeof($this->override) > 0 && sizeof($attributes) >0) {
            foreach ($this->override as $field => $queryParams) {
                $newOverrideValues = $this->getNewOverrideValues($attributes[$field], $queryParams);
                $saveField = \yii\helpers\ArrayHelper::getValue($queryParams, 'saveField', $field);

                if (count($newOverrideValues) >1) {
                    $attributes[$saveField] = implode(', ',
                                        \yii\helpers\ArrayHelper::map($newOverrideValues, $queryParams['returnField'], $queryParams['returnField'])
                    );
                } elseif (count($newOverrideValues) == 1) {
                    $attributes[$saveField] = $newOverrideValues[0][$queryParams['returnField']];
                }
            }
        }
        return $attributes;
    }

    /**
     * @param string $searchFieldValue
     * @param string $queryParams
     * @return mixed
     */
    private function getNewOverrideValues($searchFieldValue, $queryParams)
    {
        $query = new Query;

        $query
            ->select($queryParams['returnField'])
            ->from($queryParams['tableName'])
            ->where([$queryParams['searchField'] => $searchFieldValue]);

        $rows = $query->all();

        return $rows;
    }


    /**
     * @param string $action
     * @throws \yii\db\Exception
     */
    protected function auditAttributes($action)
    {
        // Get the new and old attributes
        $newAttributes = $this->cleanAttributes($this->owner->getAttributes());
        $oldAttributes = $this->cleanAttributes($this->getOldAttributes());

        // ensure to handle serialized attributes properly
        foreach($newAttributes as $key => $value) {
            if(is_array($newAttributes[$key])) {
                $newAttributes[$key] = Json::encode($newAttributes[$key]);
            }
        }

        foreach($oldAttributes as $key => $value) {
            if(is_array($oldAttributes[$key])) {
                $oldAttributes[$key] = Json::encode($oldAttributes[$key]);
            }
        }

        // If no difference then get out of here
        if (count(array_diff_assoc($newAttributes, $oldAttributes)) <= 0) {
            return;
        }
        
        // Get the trail data
        $entry_id = $this->getAuditEntryId();
        $user_id = $this->getUserId();
        $model = $this->owner->className();
        $model_id = $this->getNormalizedPk();
        $created = date($this->dateFormat);

        $this->saveAuditTrail($action, $newAttributes, $oldAttributes, $entry_id, $user_id, $model, $model_id, $created);
    }

    /**
     * Save the audit trails for a create or update action
     *
     * @param $action
     * @param $newAttributes
     * @param $oldAttributes
     * @param $entry_id
     * @param $user_id
     * @param $model
     * @param $model_id
     * @param $created
     * @throws \yii\db\Exception
     */
    protected function saveAuditTrail($action, $newAttributes, $oldAttributes, $entry_id, $user_id, $model, $model_id, $created)
    {
        // Build a list of fields to log
        $rows = array();
        foreach ($newAttributes as $field => $new) {
            $old = isset($oldAttributes[$field]) ? $oldAttributes[$field] : '';
            // If they are not the same lets write an audit log
            if ($new != $old) {
                $rows[] = [$entry_id, $user_id, $old, $new, $action, $model, $model_id, $field, $created];
            }
        }
        // Record the field changes with a batch insert
        if (!empty($rows)) {
            $columns = ['entry_id', 'user_id', 'old_value', 'new_value', 'action', 'model', 'model_id', 'field', 'created'];
            $audit = Audit::getInstance();
            $audit->getDb()->createCommand()->batchInsert(AuditTrail::tableName(), $columns, $rows)->execute();
        }
    }

    /**
     * Save the audit trails for a delete action
     */
    protected function saveAuditTrailDelete()
    {
        $audit = Audit::getInstance();
        $audit->getDb()->createCommand()->insert(AuditTrail::tableName(), [
            'action' => 'DELETE',
            'entry_id' => $this->getAuditEntryId(),
            'user_id' => $this->getUserId(),
            'model' => $this->owner->className(),
            'model_id' => $this->getNormalizedPk(),
            'created' => date($this->dateFormat),
        ])->execute();
    }

    /**
     * @return array
     */
    public function getOldAttributes()
    {
        return $this->_oldAttributes;
    }

    /**
     * @param $value
     */
    public function setOldAttributes($value)
    {
        $this->_oldAttributes = $value;
    }

    /**
     * @return string
     */
    protected function getNormalizedPk()
    {
        $pk = $this->owner->getPrimaryKey();
        return is_array($pk) ? json_encode($pk) : $pk;
    }

    /**
     * @return int|null|string
     */
    protected function getUserId()
    {
        return Audit::getInstance()->getUserId();
    }

    /**
     * @return models\AuditEntry|null|static
     * @throws \Exception
     */
    protected function getAuditEntryId()
    {
        $module = Audit::getInstance();
        
        if (!$module) {
            $module = \Yii::$app->getModule(Audit::findModuleIdentifier());
        }
        
        if (!$module) {
            throw new \Exception('Audit module cannot be loaded');
        }
        
        $entry = Audit::getInstance()->getEntry(true);
        
        return (empty($entry)) ? null : $entry->id;
    }

}