matab-panel/app/Observers/SyncObserver.php

75 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\SyncLog;
use Illuminate\Database\Eloquent\Model;
class SyncObserver
{
public function created(Model $model): void
{
if (app()->bound('sync.applying')) {
return;
}
SyncLog::create([
'datetime' => now(),
'ip' => request()->ip() ?? '127.0.0.1',
'user' => auth()->user()?->name ?? 'system',
'table_name' => $model->getTable(),
'action' => 'created',
'record_id' => $model->getKey(),
'changed_data' => $model->getAttributes(),
]);
}
public function updated(Model $model): void
{
if (app()->bound('sync.applying')) {
return;
}
$dirty = $model->getDirty();
if (empty($dirty)) {
return;
}
$changedData = [];
foreach ($dirty as $field => $rawValue) {
$changedData[$field] = $rawValue instanceof \BackedEnum
? $rawValue->value
: (is_object($rawValue) ? (string) $rawValue : $rawValue);
}
SyncLog::create([
'datetime' => now(),
'ip' => request()->ip() ?? '127.0.0.1',
'user' => auth()->user()?->name ?? 'system',
'table_name' => $model->getTable(),
'action' => 'updated',
'record_id' => $model->getKey(),
'changed_data' => $changedData,
]);
}
public function deleted(Model $model): void
{
if (app()->bound('sync.applying')) {
return;
}
SyncLog::create([
'datetime' => now(),
'ip' => request()->ip() ?? '127.0.0.1',
'user' => auth()->user()?->name ?? 'system',
'table_name' => $model->getTable(),
'action' => 'deleted',
'record_id' => $model->getKey(),
'changed_data' => null,
]);
}
}