| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <?php
- namespace App\Services;
- use App\Models\OperationAudit;
- use Illuminate\Database\Eloquent\Model;
- class OperationAuditService
- {
- private const SENSITIVE_KEYS = ['secret', 'key', 'password', 'token', 'private'];
- public static function record(string $resourceType, ?int $resourceId, string $action, $before, $after, ?string $createdAt = null, ?array $actor = null): void
- {
- $admin = request()->user ?? null;
- $attributes = [
- 'resource_type' => $resourceType,
- 'resource_id' => $resourceId,
- 'action' => $action,
- 'changes' => [
- 'before' => self::sanitize(self::toArray($before)),
- 'after' => self::sanitize(self::toArray($after)),
- ],
- 'operator_id' => $actor !== null ? ($actor['operator_id'] ?? null) : ($admin->id ?? null),
- 'operator_name' => $actor !== null ? (string) ($actor['operator_name'] ?? '') : (string)($admin->username ?? ''),
- ];
- if ($createdAt !== null) $attributes['created_at'] = $createdAt;
- OperationAudit::query()->create($attributes);
- }
- public static function actor(): array
- {
- $admin = request()->user ?? null;
- return [
- 'operator_id' => $admin->id ?? null,
- 'operator_name' => (string)($admin->username ?? ''),
- ];
- }
- private static function toArray($value): array
- {
- if ($value instanceof Model) {
- return $value->toArray();
- }
- return is_array($value) ? $value : [];
- }
- private static function sanitize(array $value): array
- {
- foreach ($value as $key => $item) {
- $normalized = strtolower((string)$key);
- foreach (self::SENSITIVE_KEYS as $needle) {
- if (str_contains($normalized, $needle)) {
- $value[$key] = empty($item) ? null : '******';
- continue 2;
- }
- }
- if (is_array($item)) {
- $value[$key] = self::sanitize($item);
- }
- }
- return $value;
- }
- }
|