Files
root 940afe9319
API CI/CD / Validate (composer + pint) (push) Successful in 2m7s
API CI/CD / Test (PHPUnit) (push) Failing after 2m23s
API CI/CD / Build frontend assets (push) Successful in 2m18s
API CI/CD / Security audit (push) Successful in 31s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
fix unit tests as well as missing code
2026-06-25 14:26:32 -04:00

95 lines
2.7 KiB
PHP

<?php
namespace App\Services\ClassProgress;
use App\Models\ClassProgressAttachment;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
class ClassProgressAttachmentService
{
public function storeAttachments(int $reportId, array $files): array
{
if ($files === []) {
return [];
}
$stored = [];
foreach ($files as $file) {
if (! $file instanceof UploadedFile || ! $file->isValid()) {
continue;
}
$path = $this->storeAttachment($file);
$stored[] = [
'report_id' => $reportId,
'file_path' => $path,
'original_name' => $file->getClientOriginalName(),
'mime_type' => $file->getClientMimeType(),
'file_size' => $file->getSize(),
'created_at' => now(),
];
}
if ($stored !== []) {
ClassProgressAttachment::query()->insert($stored);
}
return $stored;
}
public function resolvePath(string $path): ?string
{
$path = trim($path);
if ($path === '') {
return null;
}
$candidates = [];
if (str_starts_with($path, 'storage/')) {
$relative = ltrim(substr($path, strlen('storage/')), '/');
$disk = (string) config('progress.attachments.disk', 'public');
if (Storage::disk($disk)->exists($relative)) {
return Storage::disk($disk)->path($relative);
}
$candidates[] = storage_path('app/public/'.$relative);
}
if (str_starts_with($path, 'writable/uploads/')) {
$relative = ltrim(substr($path, strlen('writable/uploads/')), '/');
$candidates[] = storage_path('app/'.$relative);
$candidates[] = storage_path('app/public/'.$relative);
}
$candidates[] = storage_path('app/'.ltrim($path, '/'));
$candidates[] = storage_path('app/public/'.ltrim($path, '/'));
foreach ($candidates as $candidate) {
if (is_file($candidate)) {
return $candidate;
}
}
return null;
}
private function storeAttachment(UploadedFile $file): string
{
$disk = (string) config('progress.attachments.disk', 'public');
$directory = (string) config('progress.attachments.directory', 'class_material');
try {
$path = $file->store($directory, $disk);
} catch (\Throwable $e) {
Log::error('Failed to store class progress attachment.', [
'error' => $e->getMessage(),
]);
throw $e;
}
return 'storage/'.ltrim($path, '/');
}
}