Globinours/app/Services/AuditService.php

40 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
final class AuditService
{
public static function log(
string $action,
string $path,
?string $summary = null,
?string $entityType = null,
?int $entityId = null,
array $metadata = [],
): void {
$safe = [];
foreach ($metadata as $key => $value) {
if (in_array(strtolower((string) $key), ['password', 'password_confirm', 'csrf'], true)) {
continue;
}
if (is_scalar($value) || $value === null) {
$safe[$key] = $value;
}
}
DB::pdo()
->prepare(
'INSERT INTO audit_log(user_id,action,method,path,entity_type,entity_id,summary,metadata,ip_address) VALUES(:user,:action,:method,:path,:type,:entity,:summary,:meta,:ip)',
)
->execute([
':user' => Auth::id(),
':action' => $action,
':method' => $_SERVER['REQUEST_METHOD'] ?? 'CLI',
':path' => $path,
':type' => $entityType,
':entity' => $entityId,
':summary' => $summary,
':meta' => $safe ? json_encode($safe, JSON_UNESCAPED_UNICODE) : null,
':ip' => $_SERVER['REMOTE_ADDR'] ?? null,
]);
}
}