Merge branch 'develop'
# Conflicts: # app/controller/IndexController.php
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
namespace app\common\traits;
|
||||
|
||||
use app\common\audit\AuditBuffer;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
trait Auditable
|
||||
{
|
||||
// 可在模型中设置:
|
||||
// public $auditDisabled = true; // 关闭该模型的日志
|
||||
// public $auditScene = 'alias'; // 覆盖默认场景(默认=表名)
|
||||
|
||||
public static function bootAuditable()
|
||||
{
|
||||
static::created(function (Model $m) {
|
||||
if (self::isMuted($m)) return;
|
||||
AuditBuffer::instance()->pushModelChange(self::scene($m), $m->getKey(), [], $m->getAttributes());
|
||||
});
|
||||
|
||||
static::updated(function (Model $m) {
|
||||
if (self::isMuted($m)) return;
|
||||
$dirty = $m->getDirty();
|
||||
if (!$dirty) return;
|
||||
$old = []; $new = [];
|
||||
foreach (array_keys($dirty) as $k) {
|
||||
$old[$k] = $m->getOriginal($k);
|
||||
$new[$k] = $m->getAttribute($k);
|
||||
}
|
||||
AuditBuffer::instance()->pushModelChange(self::scene($m), $m->getKey(), $old, $new);
|
||||
});
|
||||
|
||||
static::deleted(function (Model $m) {
|
||||
if (self::isMuted($m)) return;
|
||||
AuditBuffer::instance()->pushModelChange(self::scene($m), $m->getKey(), $m->getAttributes(), []);
|
||||
});
|
||||
}
|
||||
|
||||
protected static function scene(Model $m): string
|
||||
{
|
||||
return property_exists($m, 'auditScene') && $m->auditScene ? $m->auditScene : $m->getTable();
|
||||
}
|
||||
|
||||
protected static function isMuted(Model $m): bool
|
||||
{
|
||||
if (property_exists($m, 'auditDisabled') && $m->auditDisabled) return true;
|
||||
return $m->getTable() === 'sys_op_log'; // 避免自记录
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user