made = null; $this->settled = false; } public function made(Model $model): void { if (! $this->settled && $this->made === null && ! $model instanceof AuditLog) { $this->made = $model; } } /** * For a controller whose request is about something it did not make (an address that was * banned before, an account that was changed), or about no single thing (null). */ public function about(?Model $model): void { $this->made = $model; $this->settled = true; } public function firstMade(): ?Model { return $this->made; } /** * @param array $details */ public function record( string $event, string $summary, ?Authenticatable $user = null, ?Model $subject = null, array $details = [], ?string $action = null, ?string $email = null, ): AuditLog { // A command has no visitor: no address and no browser. $request = app()->runningInConsole() && ! app()->runningUnitTests() ? null : request(); $about = $subject === null ? null : self::describe($subject); $agent = $request?->userAgent(); $name = $user === null ? null : data_get($user, 'name'); return AuditLog::query()->create([ 'event' => $event, 'action' => $action, 'summary' => Str::limit($summary, 250, '…'), 'subject_type' => $about['type'] ?? null, 'subject_id' => $about['id'] ?? null, 'subject_label' => $about['label'] ?? null, 'details' => $details === [] ? null : $details, 'user_id' => $user?->getAuthIdentifier(), 'user_name' => is_string($name) ? $name : null, 'email' => $email === null ? null : Str::limit($email, 250, '…'), 'ip' => $request?->ip(), 'user_agent' => is_string($agent) ? Str::limit($agent, 490, '…') : null, 'created_at' => now(), ]); } /** * What a model is called in the log: its kind ('post', 'ip_ban'), its id and a name. * * @return array{type: string, id: int|null, label: string} */ public static function describe(Model $model): array { $id = $model->getKey(); $id = is_int($id) ? $id : null; $label = '#'.($id ?? '?'); foreach (['title', 'name', 'label', 'ip', 'slug'] as $attribute) { $value = $model->getAttribute($attribute); if (is_string($value) && trim($value) !== '') { $label = Str::limit(trim($value), 200, '…'); break; } } return ['type' => Str::snake(class_basename($model)), 'id' => $id, 'label' => $label]; } }