223d57483c
# Conflicts: # app/controller/IndexController.php
48 lines
1.6 KiB
PHP
48 lines
1.6 KiB
PHP
<?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'; // 避免自记录
|
|
}
|
|
} |