50 lines
1.3 KiB
PHP
50 lines
1.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\AuditLog;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Carbon;
|
|
|
|
class AuditService
|
|
{
|
|
public function log(
|
|
Model $actor,
|
|
string $action,
|
|
Model|string $target,
|
|
?array $before = null,
|
|
?array $after = null,
|
|
?int $organizationId = null,
|
|
?int $establishmentId = null,
|
|
?string $ip = null,
|
|
): AuditLog {
|
|
[$targetType, $targetId] = $this->resolveTarget($target);
|
|
|
|
return AuditLog::query()->create([
|
|
'actor_type' => $actor->getMorphClass(),
|
|
'actor_id' => $actor->getKey(),
|
|
'organization_id' => $organizationId,
|
|
'establishment_id' => $establishmentId,
|
|
'action' => $action,
|
|
'target_type' => $targetType,
|
|
'target_id' => $targetId,
|
|
'before_data' => $before,
|
|
'after_data' => $after,
|
|
'ip_address' => $ip,
|
|
'created_at' => Carbon::now(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* @return array{0: string, 1: int|null}
|
|
*/
|
|
private function resolveTarget(Model|string $target): array
|
|
{
|
|
if ($target instanceof Model) {
|
|
return [$target->getMorphClass(), $target->getKey()];
|
|
}
|
|
|
|
return [$target, null];
|
|
}
|
|
}
|