clusev/app/Livewire/Modals/FileEditor.php

106 lines
2.4 KiB
PHP

<?php
namespace App\Livewire\Modals;
use App\Models\AuditEvent;
use App\Models\Server;
use App\Services\FleetService;
use Illuminate\Support\Facades\Auth;
use LivewireUI\Modal\ModalComponent;
use Throwable;
/**
* View / edit a remote text file over SFTP. Loads lazily (wire:init), refuses
* binary or oversized files, and writes back on save with an AuditEvent.
*/
class FileEditor extends ModalComponent
{
public int $serverId;
public string $path;
public string $name;
public string $content = '';
public bool $binary = false;
public bool $tooBig = false;
public bool $loaded = false;
public ?string $error = null;
public function mount(int $serverId, string $path, string $name): void
{
$this->serverId = $serverId;
$this->path = $path;
$this->name = $name;
}
public static function modalMaxWidth(): string
{
return 'lg';
}
public function load(FleetService $fleet): void
{
$server = Server::find($this->serverId);
if (! $server) {
$this->error = 'Server nicht gefunden.';
$this->loaded = true;
return;
}
try {
$r = $fleet->readFile($server, $this->path);
$this->content = $r['content'];
$this->binary = $r['binary'];
$this->tooBig = $r['tooBig'];
} catch (Throwable $e) {
$this->error = $e->getMessage();
}
$this->loaded = true;
}
public function save(FleetService $fleet): void
{
$this->error = null;
$server = Server::find($this->serverId);
if (! $server) {
$this->error = 'Server nicht gefunden.';
return;
}
try {
$fleet->writeFile($server, $this->path, $this->content);
} catch (Throwable $e) {
$this->error = $e->getMessage();
return;
}
AuditEvent::create([
'user_id' => Auth::id(),
'server_id' => $server->id,
'actor' => Auth::user()?->name ?? 'system',
'action' => 'file.edit',
'target' => $this->path,
'ip' => request()->ip(),
]);
$this->dispatch('fileSaved');
$this->dispatch('notify', message: '„'.$this->name.'" gespeichert.');
$this->closeModal();
}
public function render()
{
return view('livewire.modals.file-editor');
}
}