Files
mareike/app/Providers/UploadFileProvider.php
T
2026-09-04 09:27:48 +02:00

61 lines
2.1 KiB
PHP

<?php
namespace App\Providers;
use App\Models\CostUnit;
use App\ValueObjects\InvoiceFile;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
class UploadFileProvider {
private UploadedFile $file;
private CostUnit $costUnit;
public function __construct(UploadedFile $file, CostUnit $costUnit) {
$this->file = $file;
$this->costUnit = $costUnit;
}
/**
* Das Ablageverzeichnis der Belege einer Kostenstelle, relativ zur Disk `local`
* (Wurzel `storage/app/private`).
*
* Öffentlich, weil Belege nicht nur aus einem Upload entstehen: Eine Beitragserstattung erzeugt ihren
* Eigenbeleg im Speicher und legt ihn über den FileWriteProvider ab -- landen soll er trotzdem dort,
* wo alle anderen Belege liegen.
*/
public static function directoryFor(CostUnit $costUnit) : string {
return sprintf('%1$s/invoices/%2$s', currentTenant()->slug, $costUnit->id);
}
public function saveUploadedFile() : ?InvoiceFile {
try {
$directory = self::directoryFor($this->costUnit);
$filename = $this->normalizeFilename($this->file->getClientOriginalName());
$path = $this->file->storeAs(
$directory,
$filename
);
$invoiceFile = new InvoiceFile();
$invoiceFile->filename = $filename;
$invoiceFile->fullPath = $path;
return $invoiceFile;
} catch (\Exception $e) {
return null;
}
}
private function normalizeFilename(string $filename) : string {
return strtolower($filename)
|> function (string $filename) : string { return str_replace(' ', '_', $filename); }
|> function (string $filename) : string { return str_replace('ä', 'ae', $filename); }
|> function (string $filename) : string { return str_replace('ö', 'oe', $filename); }
|> function (string $filename) : string { return str_replace('ü', 'ue', $filename); }
|> function (string $filename) : string { return str_replace('ß', 'ss', $filename); };
}
}