radfusion/app/Services/AuditTrail/ActivityLogger.php
2024-12-30 22:15:59 +06:00

103 lines
2.0 KiB
PHP

<?php
namespace App\Services\AuditTrail;
use App\Models\Study;
use DB;
use Illuminate\Contracts\Auth\Authenticatable;
class ActivityLogger
{
private ?int $studyId = null;
private ?int $userId = null;
private int $activity;
private int $category;
private ?string $url = null;
private ?string $notes = null;
private ?string $userAgent = null;
public function __construct()
{
$this->category = Category::GENERAL;
}
public function on(Study $study): static
{
$this->studyId = $study->id;
return $this;
}
public function by(Authenticatable|int $user): static
{
if ($user == null) {
return $this;
}
if ($user instanceof Authenticatable) {
$this->userId = (int) $user->getAuthIdentifier();
} else {
$this->userId = $user;
}
return $this;
}
public function did(int $activity): static
{
$this->activity = $activity;
return $this;
}
public function category(int $category): static
{
$this->category = $category;
return $this;
}
public function url(?string $url = null): static
{
$this->url = $url ?? request()->url();
return $this;
}
public function notes(string $notes): static
{
$this->notes = $notes;
return $this;
}
public function ua(?string $agent = null): static
{
$this->userAgent = $agent ?? request()->userAgent();
return $this;
}
public function log(): bool
{
return DB::table('audit_logs')->insert([
'study_id' => $this->studyId,
'user_id' => $this->userId,
'category' => $this->category,
'activity' => $this->activity,
'ip_addr' => request()->ip(),
'user_agent' => $this->userAgent,
'url' => $this->url,
'notes' => $this->notes,
'created_at' => now(),
'updated_at' => now(),
]);
}
}