| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <?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): void
- {
- $admin = request()->user ?? null;
- OperationAudit::query()->create([
- 'resource_type' => $resourceType,
- 'resource_id' => $resourceId,
- 'action' => $action,
- 'changes' => [
- 'before' => self::sanitize(self::toArray($before)),
- 'after' => self::sanitize(self::toArray($after)),
- ],
- 'operator_id' => $admin->id ?? null,
- 'operator_name' => (string)($admin->username ?? ''),
- ]);
- }
- 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;
- }
- }
|