145 lines
3.0 KiB
PHP
145 lines
3.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;
|
|
|
|
private ?string $ipAddr = null;
|
|
|
|
private bool $anonymous = false;
|
|
|
|
private ?string $orthancId = null;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->category = Category::GENERAL;
|
|
}
|
|
|
|
public function on(Study|int $study): static
|
|
{
|
|
if ($study instanceof Study) {
|
|
$this->studyId = $study->id;
|
|
} else {
|
|
$this->studyId = (int) $study;
|
|
}
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function by(Authenticatable|int|null $user = null): static
|
|
{
|
|
if ($user === null) {
|
|
$user = auth()->user();
|
|
}
|
|
|
|
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()->path();
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function orthanc(string $uuid): static
|
|
{
|
|
$this->orthancId = $uuid;
|
|
|
|
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 ip(?string $addr = null): static
|
|
{
|
|
$this->ipAddr = $addr ?? request()->ip();
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function anon()
|
|
{
|
|
$this->anonymous = true;
|
|
$this->userId = null;
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function log(bool $initDefaults = true): bool
|
|
{
|
|
if ($initDefaults) {
|
|
$this->ip();
|
|
$this->url();
|
|
$this->ua();
|
|
if ($this->userId === null && ! $this->anonymous) {
|
|
$this->by();
|
|
}
|
|
}
|
|
|
|
return DB::table('audit_logs')
|
|
->insert([
|
|
'study_id' => $this->studyId,
|
|
'user_id' => $this->userId,
|
|
'category' => $this->category,
|
|
'activity' => $this->activity,
|
|
'orthanc_uuid' => $this->orthancId,
|
|
'ip_addr' => $this->ipAddr,
|
|
'user_agent' => $this->userAgent,
|
|
'url' => $this->url,
|
|
'notes' => $this->notes,
|
|
'created_at' => now(),
|
|
]);
|
|
}
|
|
}
|