feat: add image upload service

This commit is contained in:
Keith Solomon
2026-07-06 18:36:34 -05:00
parent 6399e2d86c
commit c24964ff96
2 changed files with 132 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace BattleForge\Application;
final class ImageUploadService
{
public function __construct(
private readonly string $userToken,
private readonly string $uploadsRoot,
) {
}
public function store(string $tempPath, string $declaredMime): string
{
$validated = ImageValidator::validate($tempPath, $declaredMime);
$namespace = $this->uploadsRoot . '/' . $this->userToken;
if (!is_dir($namespace)) {
mkdir($namespace, 0700, true);
}
$hash = bin2hex(random_bytes(16));
$filename = $hash . '.' . $validated->extension;
$destination = $namespace . '/' . $filename;
if (!rename($tempPath, $destination)) {
throw new InvalidImageException("Could not move upload to {$destination}.");
}
// Lock the file down: the namespace is already 0700; tighten the
// file itself to 0600 in case the server's umask is permissive.
chmod($destination, 0600);
return '/assets/' . $this->userToken . '/' . $filename;
}
}