56 lines
1.6 KiB
PHP
56 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use App\Models\AuditLog;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class AuditLogger
|
|
{
|
|
public static function log(string $action, ?object $auditable = null, array $metadata = []): void
|
|
{
|
|
// Normalize metadata so it can be safely JSON encoded (files, dates, objects)
|
|
$safeMetadata = collect($metadata)->map(function ($value) {
|
|
if (is_null($value) || is_scalar($value)) {
|
|
return $value;
|
|
}
|
|
|
|
if ($value instanceof \DateTimeInterface) {
|
|
return $value->format('c');
|
|
}
|
|
|
|
if ($value instanceof \Illuminate\Http\UploadedFile) {
|
|
return [
|
|
'original_name' => $value->getClientOriginalName(),
|
|
'size' => $value->getSize(),
|
|
'mime' => $value->getMimeType(),
|
|
];
|
|
}
|
|
|
|
if (is_array($value)) {
|
|
return $value;
|
|
}
|
|
|
|
if ($value instanceof \JsonSerializable) {
|
|
return $value->jsonSerialize();
|
|
}
|
|
|
|
if (is_object($value)) {
|
|
return method_exists($value, 'toArray')
|
|
? $value->toArray()
|
|
: (string) $value;
|
|
}
|
|
|
|
return $value;
|
|
})->toArray();
|
|
|
|
AuditLog::create([
|
|
'user_id' => optional(Auth::user())->id,
|
|
'action' => $action,
|
|
'auditable_type' => $auditable ? get_class($auditable) : null,
|
|
'auditable_id' => $auditable->id ?? null,
|
|
'metadata' => $safeMetadata,
|
|
]);
|
|
}
|
|
}
|